diff --git "a/3748.jsonl" "b/3748.jsonl" new file mode 100644--- /dev/null +++ "b/3748.jsonl" @@ -0,0 +1,142 @@ +{"seq_id":"20799944039","text":"import pandas as pd\nimport numpy as np\nautos= pd.read_csv('autos.csv',encoding= 'Latin-1')\n\nimport sys\n\nsys.path\n\nautos\n\nautos.head()\n\nautos.info()\n\n# from here we can observe the structure of the data, 20 columns data, most are non-null, and the headers are in camelcase \n\nautos.columns\n\nautos= autos.rename(columns={'dateCrawled':'date_crawled','offerType':'offer_type','yearOfRegistration': 'registration_year',\n 'MonthOfRegistration':'registration_month',\n 'notRepairedDamage':'unrepaired_damage',\n 'dateCreated':'ad_created','dateCrawler':'date_crawled',\n 'nrOfPictures':'pictures_no','postalCode':'post_code',\n 'lastSeen':'last_seen'\n \n \n })\n\nautos.columns\n\n# i have made changes to the column headers, most from camelcase to snakescase which is more like python\n\nautos.head()\n\nautos.describe(include ='all')\n\n# NOTHING- \n\n# unrepaired_demage, picture_no,seller and offer_type are columns that will be deleted because of their lack of informaton\n\nautos['price'].unique().shape\n\nautos['price'].describe()\n\nautos['price'].value_counts()\n\nautos['price'].value_counts().head(20)\n\n\nautos['price'].value_counts().sort_index(ascending=False).head(20)\n\nautos['kilometer'].value_counts().sort_index(ascending=False)\n\nautos=autos[autos['price'].between(1,50000)]\nautos['price'].describe()\n\n# a price of zero isnt realistic was i took a range from $1 to 50k dollars\n\nautos.head()\n\nautos[[ 'date_crawled' , 'ad_created' , 'last_seen' ]][0:5]\n\n\nprint (autos[ 'date_crawled' ].str[: 10 ])\n\nautos[ 'date_crawled' ].str[: 10 ].value_counts(normalize=True, dropna=False).sort_index()\n\nautos[ 'ad_created' ].str[: 10 ].value_counts(normalize=True, dropna=False).sort_index()\n\nautos['last_seen' ].str[: 10 ].value_counts(normalize=True, dropna=False).sort_index()\n\n# the numbers, are very small\n\nautos['registration_year'].describe()\n\nautos['registration_year']\n\n# We will assume the first cars were made in tha early 1900s to about 2016 now. so will remove values outside this scope\n\nautos=autos[autos['registration_year'].between(1990,2018)]\n\nautos['registration_year'].value_counts(normalize=True)\n\n# here we see that most cars were registered during a 26years span\n\nautos['brand'][:20]\n\nautos['brand'].value_counts(normalize=True)\n\n# volkswagen,bmw and opel are leading with 50% of the total market shares\n\nbrand_counts = autos['brand'].value_counts(normalize=True)\ncommon_brands = brand_counts[brand_counts>.05].index\nprint(common_brands)\n\nbrand_mean_prices={}\nfor bran in common_brands:\n bran_comp = autos[autos['brand']==bran]\n mean_price = bran_comp['price'].mean()\n brand_mean_prices[bran]= int(mean_price)\n print(brand_mean_prices)\n\n# audi is the most expensive closely followed by bmw and mercedes_benz,volkswagen is pretty average,then ford and opel are the cheapest\n\nbrand_mean_mileage={}\nfor bran in common_brands:\n bran_comp = autos[autos['brand']==bran]\n mean_mileage = bran_comp['kilometer'].mean()\n brand_mean_mileage[bran]= int(mean_mileage)\n print(brand_mean_mileage)\n\nmean_mileage = pd.Series(brand_mean_mileage).sort_values(ascending=False)\nmean_price= pd.Series(brand_mean_prices).sort_values(ascending=False)\n\naggregated_data = pd.DataFrame(mean_mileage, columns=['mean_mileage'])\naggregated_data[ 'mean_price' ]=mean_price\n\naggregated_data\n\n# opel despite being the cheapest car has the very healthy mileage\n\nautos.columns\n\nautos['vehicleType'].unique()\n\nautos['gearbox'].unique()\n\nautos['fuelType'].unique()\n\nautos['unrepaired_damage'].unique()\n\nwords_translated={'kleinwagen':'supermini',\n 'kombi':'station_wagon',\n 'automatik':'automatic',\n 'benzin':'petrol','nan':'no',\n 'elektro':'electro',\n 'ja':'yes'\n }\nfor each in ['vehicleType', 'gearbox','fuelType','unrepaired_damage']:\n autos[each]= autos[each].map(words_translated)\n \n\nprint(autos['vehicleType'].unique())\nprint(autos['gearbox'].unique())\nprint(autos['fuelType'].unique())\nprint(autos['unrepaired_damage'].unique())\n\n\n","repo_name":"gregtsado/Login-System-Web-Development-","sub_path":"project2.ipynb","file_name":"project2.ipynb","file_ext":"py","file_size_in_byte":4252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"40978879386","text":"# +\n# ## Requirements\n# 1. Begin with an executive summary:\n# - What is your goal?\n# - What are your metrics?\n# - What were your findings?\n# - What risks/limitations/assumptions affect these findings?\n\n# 2. Walk through your model step by step, starting with EDA\n# - What are your variables of interest?\n# - What outliers did you remove?\n# - What types of data imputation did you perform?\n\n# 3. Summarize your statistical analysis, including:\n# - model selection\n# - implementation\n# - evaluation\n# - inference\n\n# 4. Clearly document and label each section\n# - Logically organize your information in a persuasive, informative manner\n# - Include notebook headers and subheaders, as well as clearly formatted markdown for all written components\n# - Include graphs/plots/visualizations with clear labels\n# - Comment and explain the purpose of each major section/subsection of your code\n# - *Document your code for your future self, as if another person needed to replicate your approach*\n# -\n\n# ## Executive Summary\n\n# Helicopter accidents usually make the media as a result of the severity of the the accident. This project aims to investigate circumstances that cause an accident and outcomes of an accident.\n# The project will try to predict outcomes of a helicopter accident.\n#\n# This will be using accidents as per the NTSB database and whether the accident resulted in the death of at least one person on board therefore classifying it as a fatal accident irrespective of the number of people on board.\n#\n# Risks:\n# The provenance of the dataset is not truely understood. \n#\n# Limitations: \n# I had wanted to look at 'currency' of a pilot. Within the UK, the Air Accident Investigation Branch reports (available at https://www.gov.uk/aaib-reports) document a pilot's total flying hours, number of hours flown in the make and model that the accident was in when it is different to total hours, hours flown in the last 90 days and last 28 days. Unfortunately the dataset available from the NTSB (https://www.ntsb.gov/_layouts/ntsb.aviation/index.aspx) did not contain this data.\n#\n# Assumptions:\n# An assumption was made using the purpose of flight column that where the flight was not private, instructional or unknown, then it was professional. The purpose of this classification is a professional pilot must have passed a higher level of test, and is expected to be more experienced than a private pilot. The 'pilot_type' column is therefore a surrogate for truly knowing number of hours flown.\n#\n# The dataset originally contained helicopter accidents from around the world. Upon looking at the proportion of deaths vs survivals in the United States vs the rest of the world, the United States death rate was 1:6 where as the rest of the world was 2:1. Upon closer investigation, not all UK accidents were included in the NTSB dataset, therefore so the assumption was made that 'rest of the world' accidents did not include all accidents and would skew the data, and were dropped.\n#\n# As this is a classification problem (fatality or not), algorithms that will be used will be logistic regression, decision trees, random forest, KNN, and also Pymc3 to look at probability of two models of Robinson helicopter.\n#\n# The dataset contains unknown values in order to keep the maximum number of rows. Each of models will be run with the entire dataset, the dataset with rows containing unknown values removed, and the dataset with columns containing unknown values removed.\n#\n# The project found that of all helicopter accidents, less than 15% of them result in a fatality (falality being defined as at least one person being killed). With such a high baseline, it was not able to achieve a score higher than the baseline.\n# The precision and recall for non-fatal flights was typically good, however was 0 for fatal accidents.\n#\n#\n\n# +\n# 2. Walk through your model step by step, starting with EDA\n# - What are your variables of interest?\n# - What outliers did you remove?\n# - What types of data imputation did you perform?\n\n# +\n# %matplotlib inline\n# %config InlineBackend.figure_format = 'retina'\n\n# Libraries for analysis\nimport pandas as pd\nimport numpy as np\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.svm import SVC, LinearSVC\nfrom sklearn.model_selection import cross_val_score, cross_val_predict\nfrom sklearn import metrics\nfrom sklearn.model_selection import train_test_split, GridSearchCV\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom datetime import timedelta\nfrom datetime import datetime\nfrom statsmodels.tsa.seasonal import seasonal_decompose\nfrom scipy import stats\nfrom statsmodels.tsa.stattools import acf, pacf\nfrom statsmodels.graphics.tsaplots import plot_acf, plot_pacf\n\n# Libraries for visuals\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# -\n\ndf=pd.read_csv('df_without_index.csv')\n\ndf.head(2)\n\n# ## \n\n# ## Looking at the fatalities column to see how the classes are spread out\n\ndf.fatalities.describe()\n\ndf.fatalities.value_counts()\n\nax = df.fatalities.value_counts().plot(kind='bar', edgecolor='black', lw=1, color='forestgreen')\nax.set_ylabel('Counts')\n_ = ax.set_title('Non-Fatal vs. Fatal Accident Counts')\n\n# Noted that my topic is not as grim as it initially sounded! However there is a class imbalance. Will try modelling using class_weight = balanced, as well as SMOTE\n\n# ## \n\n# ## This is an American dataset. I noticed during cleaning that other countries' accidents were also included so looking to see what this means for the spread of data.\n\ndf.country.value_counts()[:10]\n\n# As expected, there are alot of US accidents, however the accidents from other countries need to be investigated further. \n\ndf.event_date.head(1)\n\ndf.event_date.tail(1)\n\n# Used the AAIB website to check how many helicopter accident reports were filed in the UK between 2/1/1982 and 16/4/2019. \n#\n# https://www.gov.uk/aaib-reports?parent=&keywords=&aircraft_category%5B%5D=commercial-rotorcraft&aircraft_category%5B%5D=general-aviation-rotorcraft&date_of_occurrence%5Bfrom%5D=1%2F1%2F1982&date_of_occurrence%5Bto%5D=\n#\n# There were 1002 helicopter accident reports during this period vs 22 in the dataset.\n#\n\n# Will investigate the impact of the rest of the world countries further.\n\ndf.country=[col.strip().lower() for col in df.country]\n\ndf['country']=[col.replace(' ', '_') for col in df.country]\n\ndf['people_on_board']=df.total_fatal_injuries + df.total_serious_injuries + df.total_minor_injuries + df.total_uninjured\ndf.head()\n\nlen(df[(df['country'] != 'united_states') & (df['fatalities'] == 'fatal')])\n\nlen(df[(df['country'] != 'united_states') & (df['fatalities'] == 'non_fatal')])\n\nlen(df[(df['country'] == 'united_states') & (df['fatalities'] == 'fatal')])\n\nlen(df[(df['country'] == 'united_states') & (df['fatalities'] == 'non_fatal')])\n\n# Accidents that occured in the US report a lower fatality rate than accidents reports from the rest of the world.\n\n# ## \n\n# Visualising this difference.\n\ndf.boxplot(column='total_fatal_injuries', by = 'country', rot= 90, figsize =(15,10));\n\n# The boxplot shows that the counts of accidents resulting in at least one fatality. \n# The majority of U.S accidents do not result in a fatality (mean sitting on zero) \n# whereas about 25% of Non_U.S reports are non-fatal.\n\nplt.bar([0,1.5],df[df.country == 'united_states']['fatalities'].value_counts(normalize=True),width=0.5)\nplt.bar([0.5,2],df[df.country != 'united_states']['fatalities'].value_counts(normalize=True),width=0.5);\n\n# ## \n\n# +\n#Tableau Map to be inserted here\n# -\n\n# Checking to see how many rows I would loose if I were to drop the rest of the world.\n\ndf_country=df[['country', 'total_fatal_injuries', 'total_serious_injuries', 'total_minor_injuries','total_uninjured','fatalities']]\n\n\n# +\ndef US_or_not(x):\n \n if 'united_states' in x:\n return 'US'\n else:\n return 'Non_US'\n \ndf_country['us_or_not'] = df.country.map(US_or_not)\nprint(df_country['us_or_not'].unique())\nprint(df_country['us_or_not'].value_counts()) \n# -\n\n\n\ndf_country.boxplot(column='total_fatal_injuries', by = 'us_or_not', figsize =(12,12));\n\n# Deciding to remove rest of the world from the dataset and to refine my project question to 'Surviving a Helicopter Accident in the U.S'. \n#\n# Decision to remove the rest of the world is based on: \n# \n# Proportions of fatalities vs non-fatalities between the US and the rest of the world and the presence of rest of the world skewing the results.\n# Domain knowledge of UK accidents. The UK data within the dataset, is not a complete (fatal and non-fatal). \n#\n# Assumption is that other countries data within the dataset will also be incomplete therefore skewing the data and giving a false result.\n\n# ## \n\n# ## Making a datafame that includes U.S accidents only\n\nus_df=df[(df['country']== 'united_states')]\n\n# ## \n\n# +\nfig, ax = plt.subplots(figsize=(9, 7))\n\nmask = np.zeros_like(us_df.corr(), dtype=np.bool)\nmask[np.triu_indices_from(mask)] = True\n\nax = sns.heatmap(us_df.corr(), mask=mask, annot=True, ax=ax)\n\nax.set_xticklabels(ax.xaxis.get_ticklabels(), fontsize=14)\nax.set_yticklabels(ax.yaxis.get_ticklabels(), fontsize=14)\n\nplt.show()\n# -\n\n# The strongest positive correlation is between people on board, and total uninjured.\n\n# ## \n\n# ## Visualising the correlation of people on board vs total_uninjured\n\n# +\nfig,ax = plt.subplots(figsize=(12,12))\nsns.swarmplot(us_df['people_on_board'],us_df['total_uninjured'])\nax.set_ylabel('Counts of Uninjured')\n_ = ax.set_title('Uninjured vs people on board')\nplt.xlabel('Number of people on board');\n\n\nplt.show()\n# -\n\n# ## \n\n# ## Looking at Pilot Type\n\n# The pilot type column was made from data in the purpose of fight column. \n# \n# The reason for the generation of this column is due to the assumption that a professional pilot will have received training to a higher level than a private pilot, and will have more experience. \n#\n# Personal or private purpose of flight = pilot type -private\n# Instructional = pilot type -Instructional\n# Unknown = pilot type - Unknown\n# All others (which will be pilots who fly for a career) = professional\n#\n\n# I've kept the category of 'unknown' pilot types in my dataset for now as not to drop rows, although for this plot dropping it as it does not add value. Note that the pilot type column was a made up column using the purpose of flight column. \n\npilot=us_df[['pilot_type', 'total_fatal_injuries', 'total_serious_injuries', 'total_minor_injuries', 'total_uninjured']]\n\n# +\nfig,ax = plt.subplots()\nax=pilot.groupby('pilot_type').sum().drop('unknown', axis=0).plot(kind='bar', figsize=(12,8), ax=ax);\n\nax.set_ylabel('Counts (sum)')\n_ = ax.set_title('Injuries by Pilot Type')\nplt.xlabel('Pilot Type');\n\n# -\n\n# Professional pilots have more accidents but this is likely to be because they fly more often.\n\n# +\nfig,ax = plt.subplots()\nax=pilot.groupby('pilot_type').mean().drop('unknown', axis=0).plot(kind='bar', figsize=(12,8),ax=ax);\n\nax.set_ylabel('Mean')\n_ = ax.set_title('Injuries by Pilot Type')\nplt.xlabel('Pilot Type');\n# -\n\n# Putting numbers into proportion, professional pilots are still involved with more accidents that end up with a fatality.\n\npilot.groupby('pilot_type').total_fatal_injuries.describe()\n\n# ## \n\n# ## Now taking a closer look at instructional flights\n\n# Instructional is an interesting subset as this includes flights with instructor and student, as well as just students because students are technically unlicensed and fly on the instructors licence when flying solo.\n\nlen(us_df[(us_df['pilot_type'] == 'instructional') & (us_df['fatalities'] != 'fatal')&(us_df['people_on_board']==2)])\n\nlen(us_df[(us_df['pilot_type'] == 'instructional') & (us_df['fatalities'] != 'fatal')&(us_df['people_on_board']==1)])\n\nlen(us_df[(us_df['pilot_type'] == 'instructional') & (us_df['fatalities'] == 'fatal')&(us_df['people_on_board']==2)])\n\nlen(us_df[(us_df['pilot_type'] == 'instructional') & (us_df['fatalities'] == 'fatal')&(us_df['people_on_board']==1)])\n\n# It looks like seven students have died while flying solo\n\n# ## \n\n# ## Now looking at weather\n\n# A private helicopter pilot is taught to fly using visual references, and therefore must stay out of cloud where you can quickly loose your sense of direction, attitude. Within the dataset, fine weather is defined as VMC, and clouds/limited visibility is IMC. \n#\n# This is to investigate accidents where the pilot has ended up in IMC.\n\nweather = us_df[['weather_condition','total_fatal_injuries',\n 'total_serious_injuries', 'total_minor_injuries', 'total_uninjured']]\n\n# +\nfig,ax = plt.subplots()\nax=weather.groupby(['weather_condition'])[ 'total_fatal_injuries',\n 'total_serious_injuries', 'total_minor_injuries', 'total_uninjured'].sum().drop('unknown', axis=0).plot(kind='bar', figsize = (14,8));\n\nax.set_ylabel('Sum of Injuries')\nax.set_title('Accident Severity by Weather Condition')\nplt.xlabel('Weather Condition');\n# -\n\n# Most accidents happen in fine weather. \n\n# +\nfig,ax = plt.subplots()\nweather.groupby(['weather_condition'])[ 'total_fatal_injuries',\n 'total_serious_injuries', 'total_minor_injuries', 'total_uninjured'].mean().drop('unknown').plot(kind='bar', figsize = (14,8),ax=ax);\n\nax.set_ylabel('Mean Number of Injuries')\nax.set_title('Accident Severity by Weather Condition')\nplt.xlabel('Weather Condition');\n\n# -\n\n# It looks like inadvertently ending up in IMC is as bad as it sounds.\n\n# ## \n\n# ## Does day of the week make a difference?\n\ndow = us_df[['day_of_week','total_fatal_injuries',\n 'total_serious_injuries', 'total_minor_injuries', 'total_uninjured']]\n\ndow.groupby('day_of_week').total_fatal_injuries.value_counts()\n\nax = us_df.day_of_week.value_counts().plot(kind='bar', edgecolor='black', lw=1, color='forestgreen', figsize = (12,8));\nax.set_ylabel('Counts of accidents')\n_ = ax.set_title('Days of all accidents')\nplt.xlabel('Days of the Week');\n\nax=dow.groupby(['day_of_week'])[ 'total_fatal_injuries',\n 'total_serious_injuries', 'total_minor_injuries', 'total_uninjured'].mean().plot(kind='bar', figsize = (14,8));\nax.set_ylabel('Counts of injuries')\n_ = ax.set_title('Accident severity by day of the week')\nplt.xlabel('Days of the Week');\n\n\n# It looks like Sunday is the most fatal day to fly.\n\nax=dow.groupby(['day_of_week'])[ 'total_fatal_injuries',\n 'total_serious_injuries', 'total_minor_injuries', 'total_uninjured'].sum().plot(kind='bar', figsize = (14,8));\nax.set_ylabel('Counts of injuries')\n_ = ax.set_title('Accident severity by day of the week')\nplt.xlabel('Days of the Week');\n\n# ## \n\n# Also wondering about if there is anything to be seen with private pilots seasonal safety, ie, if they have not flown over the Winter and are therefore rusty and more dangerous in Spring. Google says the American winter starts at the end of December, and that seasons are felt from about latitude 40N\n\nseason=us_df[(us_df['latitude']>40) & (us_df['pilot_type']=='private')]\n\nseason.groupby(['month'])['total_fatal_injuries',\n 'total_serious_injuries', 'total_minor_injuries', 'total_uninjured'].sum().plot(kind='bar', figsize = (14,8))\nplt.ylabel('Sum')\nplt.xlabel('Month')\nplt.title(\"Sum of Private Pilot's Accidents by Month\");\n\n# While the number of fatalities is greater in April than earlier in the year, September, October and December look to be more fata..\n\n# Looking at all accidents by month.\n\nus_df.groupby(['month'])['total_fatal_injuries',\n 'total_serious_injuries', 'total_minor_injuries', 'total_uninjured'].sum().plot(kind='bar', figsize = (14,8))\nplt.ylabel('Sum')\nplt.title(\"Sum of All Accidents by Month\");\n\n# No trends to be seen.\n\n# ## \n\n# ## Looking at Helicopter types\n\nfig,ax=plt.subplots(figsize = [15,10])\nax = us_df.make.value_counts().plot(kind='bar', edgecolor='black', lw=1, color='forestgreen')\nax.set_ylabel('Counts')\nax.set_xlabel('Helicopter Makes')\n_ = ax.set_title('Counts of Makes of Helicopters involved in Accidents')\n\n# Without knowing the number of flights (without accidents) it is difficult to say if this is relevant. Of private pilots\n# in the UK, common helicopter makes are Robinson, Bell and Eurocopter.\n\nfig,ax = plt.subplots(figsize = [15,10])\nax = us_df.model.value_counts().plot(kind='bar', edgecolor='black', lw=1, color='forestgreen')\nax.set_ylabel('Counts')\n_ = ax.set_title('Models of Helicopters in NTSB data')\n\n# There are several models of very few values. This is not helpful for modelling therefore will make a 'minority' model for models of less than 30 counts.\n\ntemp=us_df.model.value_counts()\nmodel_dict={}\nfor model in temp.index:\n model_dict[model]= temp.loc[model]\n\n\n# +\ndef threshold(model, model_dict):\n if model_dict[model]>30:\n return model\n else:\n return 'minority'\n \nus_df['model1']=us_df.model.apply(threshold, model_dict=model_dict)\n# -\n\nus_df.model1.value_counts()\n\n# ## \n\nfig,ax = plt.subplots(figsize = [15,10])\nax = us_df.model1.value_counts().plot(kind='bar', edgecolor='black', lw=1, color='forestgreen')\nax.set_ylabel('Counts')\n_ = ax.set_title('Models of Helicopters in NTSB data')\n\n# ## \n\n# ## Looking at spread of fatalities over time\n\nus_df['date'] = pd.to_datetime(us_df.event_date)\nus_df.set_index('date', inplace=True, drop = True)\nus_df.head()\n\nfig,ax = plt.subplots(figsize = [15,10])\nus_df.resample('Q')['make'].count().plot(figsize = [15,5])\n_ = ax.set_title('Accidents over Time')\nplt.xlabel('Years')\nax.set_ylabel('Counts of Accidents');\n\n# It's interesting to see that there are very few reports before 2003. On looking at the NTSB website, the first spreadsheet of aviation accidents/incidents was 1998. \n# From looking at the graph above, I've made the assumption that before 2003, there may not have been thorough processes/reporting protocols in place resulting in adhoc reporting until 2003. \n\nus_df['year']= us_df.index.year\n\nus_df.groupby(['year'])['total_fatal_injuries'].sum().plot(kind='bar', figsize = (14,8))\nplt.ylabel('Count')\nplt.title(\"Sum of Fatalities by Month\");\n\nus_df.groupby(['year'])['total_fatal_injuries'].mean().plot(kind='bar', figsize = (14,8))\nplt.ylabel('Count')\nplt.title(\"Sum of All Accidents by Year\");\n\n# The graphs above show that of the few reports prior to 2003, it was mainly accidents that had a fatality that were reported. For this reason, I will only work with reports from 2003 onwards.\n#\n#\n\nmask_2003 = us_df['year'] >2002\nusdf2003= us_df[mask_2003]\n\nusdf2003.event_date.head(1)\n\nusdf2003.event_date.tail(1)\n\n# ## \n\n# ## Dropping unnecessary columns\n\n# Dropping phase of flight as it does not add value, and I have broad phase of flight. \n#\n# Dropping purpose of flight as information from this column has been used to generate the pilot type column where there is an assumption that all accidents that are not private, instructional or unknown are professional pilots who fly for a career therefore are trained to a higher level,and they also have more experience.\n# \n# Dropping year, event_date as they are not needed.\n# \n# Dropping amateur_built as this is replicated in Make.\n#\n# Dropping aircraft_damage as this as a result of the accident.\n#\n# Dropping model as there is now a column model1 with grouped minorities.\n#\n# Dropping longitude and latitude as they do not add value - already used in EDA in Tableau.\n#\n# Dropping the 'injuries' columns so my target isn't in my predictor\n#\n# Dropping location\n\nusdf2003.columns\n\nusdf2003=usdf2003.drop(['phase_of_flight', 'purpose_of_flight', 'year', 'event_date','amateur_built', 'aircraft_damage', 'model', 'longitude', 'latitude'], axis=1)\n\n\nusdf2003=usdf2003.drop(['total_fatal_injuries',\n 'total_serious_injuries', 'total_minor_injuries', 'total_uninjured', 'location'], axis=1)\n\nusdf2003=usdf2003.drop(['investigation_type'], axis=1)\n\nusdf2003=usdf2003.drop(['injury_severity'], axis=1)\n\nusdf2003=usdf2003.drop(['country'], axis=1)\n\nusdf2003=usdf2003.reset_index().drop(columns=['date'])\n\nusdf2003.head()\n\nusdf2003.to_csv('usdf_2003_without_index.csv')\n\nusdf2003.columns\n\n\n","repo_name":"BronwynMiddleton/Capstone","sub_path":"Part 4 .ipynb","file_name":"Part 4 .ipynb","file_ext":"py","file_size_in_byte":20098,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"12740176800","text":"# # Reader\n#\n# Queueの使い方\n# http://qiita.com/knok/items/2dd15189cbca5f9890c5\n\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\n# %matplotlib inline\n\nimg_file = './../images/cat.jpeg'\njpeg_r = tf.read_file(img_file)\nimage = tf.image.decode_jpeg(jpeg_r, channels=3) # channel = 3 (rgb)\n\nsess = tf.Session()\ninit = tf.initialize_all_variables()\nsess.run(init)\nx = sess.run(image)\nprint(x.shape)\nprint(x)\n\nplt.imshow(x)\n","repo_name":"nipe0324/machine_learning_notebooks","sub_path":"tf-basic/apx_reader.ipynb","file_name":"apx_reader.ipynb","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"1405210752","text":"# + [markdown] id=\"CIqC4q9wV6Ft\"\n# https://thinkinfi.com/fasttext-word-embeddings-python-implementation/#:~:text=FastText%20(an%20extension%20of%20word2vec,still%20shared%20with%20other%20words.\n\n# + id=\"TvM-AmirWAnH\"\n#https://thinkinfi.com/fasttext-word-embeddings-python-implementation/#:~:text=FastText%20(an%20extension%20of%20word2vec,still%20shared%20with%20other%20words.\n\n# + id=\"zUCQegjtSSpc\"\nimport pandas as pd\nimport numpy as np\nimport re\nfrom tqdm import tqdm\n \nimport nltk\nen_stop = set(nltk.corpus.stopwords.words('english'))\n \nfrom gensim.models.fasttext import FastText\n \nfrom sklearn.decomposition import PCA\nfrom sklearn.manifold import TSNE\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n \n# Lemmatization\nfrom nltk.stem import WordNetLemmatizer\nstemmer = WordNetLemmatizer()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"vBLRw4uLSa96\" outputId=\"ac81162d-8381-461a-c617-285857ace802\"\nimport nltk\nnltk.download('stopwords')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"_r6f9ghZSVBz\" outputId=\"c9ff11f8-5dd1-46b8-dfb4-049118e1f84e\"\n#https://www.kaggle.com/datasets/yelp-dataset/yelp-dataset?select=yelp_academic_dataset_tip.json\n# Read yelp review tip dataset\nyelp_df = pd.read_json(\"/content/drive/MyDrive/MSc DS_NLP/yelp_academic_dataset_tip.json\", lines=True)\n \nprint('List of all columns')\nprint(list(yelp_df))\n \n# Checking for missing values in our dataframe\n# No there is no missing value\nyelp_df.isnull().sum()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"YhY4iLNeTW5D\" outputId=\"a19b6a28-46ed-410f-9457-6966cf3d07d4\"\n# Subset data for gensim fastText model\nall_sent = list(yelp_df['text'])\nsome_sent = all_sent[0:10000]\nsome_sent[0:10]\n\n\n# + id=\"x_VL_RowTdTn\"\n# Text cleaning function for gensim fastText word embeddings in python\ndef process_text(document):\n \n # Remove extra white space from text\n document = re.sub(r'\\s+', ' ', document, flags=re.I)\n \n # Remove all the special characters from text\n document = re.sub(r'\\W', ' ', str(document))\n \n # Remove all single characters from text\n document = re.sub(r'\\s+[a-zA-Z]\\s+', ' ', document)\n \n # Converting to Lowercase\n document = document.lower()\n \n # Word tokenization \n tokens = document.split()\n # Lemmatization using NLTK\n lemma_txt = [stemmer.lemmatize(word) for word in tokens]\n # Remove stop words\n lemma_no_stop_txt = [word for word in lemma_txt if word not in en_stop]\n # Drop words \n tokens = [word for word in tokens if len(word) > 3]\n \n clean_txt = ' '.join(lemma_no_stop_txt)\n \n return clean_txt\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"Ewb6E9vaTldZ\" outputId=\"99dad49e-998a-47b8-e20e-5341a452d472\"\nimport nltk\nnltk.download('wordnet')\n\n# + id=\"DO8e5RYRTgL5\"\nclean_corpus = [process_text(sentence) for sentence in tqdm(some_sent) if sentence.strip() !='']\n \nword_tokenizer = nltk.WordPunctTokenizer()\nword_tokens = [word_tokenizer.tokenize(sent) for sent in tqdm(clean_corpus)]\nword_tokens\n\n# + id=\"8_yh7EBuTiQy\"\n# Defining values for parameters\nembedding_size = 300\nwindow_size = 5\nmin_word = 5\ndown_sampling = 1e-2\n \nfast_Text_model = FastText(word_tokens,\n size=embedding_size,\n window=window_size,\n min_count=min_word,\n sample=down_sampling,\n workers = 4,\n sg=1,\n iter=100)\n\n\n# + id=\"VOIBkUGrTrEo\"\nfrom gensim.models import Word2Vec\n# Save fastText gensim model\nfast_Text_model.save(\"ft_model_yelp\")\n# Load saved gensim fastText model\nfast_Text_model = Word2Vec.load(\"ft_model_yelp\")\n\n# + id=\"gC9X3znDT5l2\"\n# Check word embedding for a perticular word\nfast_Text_model.wv['chicken']\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"GxH0pPsTT6Qy\" outputId=\"e0d4311d-3b6a-4d5f-a2a4-f2aa9b5dc26c\"\n# Dimention must be 300\nfast_Text_model.wv['chicken'].shape\n\n# + id=\"_TRXIShXT_sw\"\n# Check top 10 similar word for a given word by gensim fastText\nfast_Text_model.wv.most_similar('chicken', topn=10)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"lfVQ1f1sUEF4\" outputId=\"4c238f6b-0bbb-4529-8ddd-64be9e5a7086\"\n# Check top 10 similarity score between two word\nfast_Text_model.wv.similarity('beer', 'drink')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"A--LXZgYUJ8l\" outputId=\"f3575211-38e9-4499-d11d-83edbb0fc978\"\n# Most opposite to a word\nfast_Text_model.wv.most_similar(negative=[\"chicken\"], topn=10)\n\n\n# + id=\"cVr-ACKjUOOR\"\n# tsne plot for below word\n# for_word = 'food'\ndef tsne_plot(for_word, w2v_model):\n # trained fastText model dimention\n dim_size = w2v_model.wv.vectors.shape[1]\n \n arrays = np.empty((0, dim_size), dtype='f')\n word_labels = [for_word]\n color_list = ['red']\n \n # adds the vector of the query word\n arrays = np.append(arrays, w2v_model.wv.__getitem__([for_word]), axis=0)\n \n # gets list of most similar words\n sim_words = w2v_model.wv.most_similar(for_word, topn=10)\n \n # adds the vector for each of the closest words to the array\n for wrd_score in sim_words:\n wrd_vector = w2v_model.wv.__getitem__([wrd_score[0]])\n word_labels.append(wrd_score[0])\n color_list.append('green')\n arrays = np.append(arrays, wrd_vector, axis=0)\n \n #---------------------- Apply PCA and tsne to reduce dimention --------------\n \n # fit 2d PCA model to the similar word vectors\n model_pca = PCA(n_components = 10).fit_transform(arrays)\n \n # Finds 2d coordinates t-SNE\n np.set_printoptions(suppress=True)\n Y = TSNE(n_components=2, random_state=0, perplexity=15).fit_transform(model_pca)\n \n # Sets everything up to plot\n df_plot = pd.DataFrame({'x': [x for x in Y[:, 0]],\n 'y': [y for y in Y[:, 1]],\n 'words_name': word_labels,\n 'words_color': color_list})\n \n #------------------------- tsne plot Python -----------------------------------\n \n # plot dots with color and position\n plot_dot = sns.regplot(data=df_plot,\n x=\"x\",\n y=\"y\",\n fit_reg=False,\n marker=\"o\",\n scatter_kws={'s': 40,\n 'facecolors': df_plot['words_color']\n }\n )\n \n # Adds annotations with color one by one with a loop\n for line in range(0, df_plot.shape[0]):\n plot_dot.text(df_plot[\"x\"][line],\n df_plot['y'][line],\n ' ' + df_plot[\"words_name\"][line].title(),\n horizontalalignment='left',\n verticalalignment='bottom', size='medium',\n color=df_plot['words_color'][line],\n weight='normal'\n ).set_size(15)\n \n \n plt.xlim(Y[:, 0].min()-50, Y[:, 0].max()+50)\n plt.ylim(Y[:, 1].min()-50, Y[:, 1].max()+50)\n \n plt.title('t-SNE visualization for word \"{}'.format(for_word.title()) +'\"')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 388} id=\"rc526h72UaFj\" outputId=\"5f22bc57-0121-400f-a704-d7049a68f4cc\"\n# tsne plot for top 10 similar word to 'chicken'\ntsne_plot(for_word='chicken', w2v_model=fast_Text_model)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"MX7Ar1BhUdlx\" outputId=\"fa944c99-0070-4406-d719-5fafed54a043\"\nnew_data = [['yes', 'this', 'is', 'the', 'word2vec', 'model'],[ 'if',\"you\",\"have\",\"think\",\"about\",\"it\"]]\n \n# Update trained gensim fastText model\nfast_Text_model.build_vocab(new_data, update = True)\n \n# Update gensim fastText model using new data\nnew_model = fast_Text_model.train(new_data, total_examples=fast_Text_model.corpus_count, epochs=fast_Text_model.iter)\n\n\n# + id=\"0Y_fQ6gDUjPx\"\n# Load pretrained fastText word embeddings python with gensim\nfrom gensim.models.fasttext import load_facebook_model\npretrained_fastText_en = load_facebook_model('pretrined fastText model/cc.en.300.bin.gz')\n\n","repo_name":"dhanyahari07/NLP","sub_path":"DeepNLP/14_fast_text.ipynb","file_name":"14_fast_text.ipynb","file_ext":"py","file_size_in_byte":8051,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-jupyter-script","pt":"21"} +{"seq_id":"21737694020","text":"# # Text Processing in Apache Spark\n#\n# We can import pyspark or specifically SparkContext to avoid retyping package name\n\nfrom pyspark import SparkContext\n\n# Do not define spark cotext multiple time\n\nsc = SparkContext(\"local[*]\", \"word_count\")\n\n# default parallelism equals to:\n# - num of cores (defined) in local mode\n# - number of cores defined in oozie job\n\nsc.defaultParallelism\n\n# read file\n\n# !pwd\n\n# !ls data\n\nlines = sc.textFile(\"data/shakespeare.txt\")\n#sc.textFile(\"hdfs://localhost:8020/input/war-and-peace.txt\")\n\nlines\n\ntype(lines)\n\n# RDDs support two types of operations: __transformations__, which create a new dataset from an existing one, and __actions__, which return a value to the driver program after running a computation on the dataset.\n#\n# All __transformations__ in Spark are __lazy__, in that they do not compute their results right away. Instead, they just remember the transformations applied to some base dataset (e.g. a file). The transformations are only computed when an __action requires a result__ to be returned to the __driver program__. This design enables Spark to run more efficiently. For example, we can realize that a dataset created through map will be used in a reduce and return only the result of the reduce to the driver, rather than the larger mapped dataset.\n#\n# ![](imgs/spark_architecture.png)\n# check the file type:\n\nlines.take(10)\n\nwords = lines.flatMap(lambda line: line.split())\n\nwords.take(5)\n\n# ![](imgs/flatMap1)\n\nwords.count()\n\nwordCounts = words.countByValue()\n\ntype(wordCounts)\n\nfor word, count in wordCounts.items():\n print(word, count)\n\n# ### Exercises\n#\n# 1. count only words that begin with uppercase\n# 2. Print 5 lines starting with \"Romeo\" or \"Juliet\" removing whitespace if necessary.\n# 3. Print 20 most popular words written only with UPPERCASE LETTERS\n#\n# ### (Python) hints\n\n\" some string with whitespaces \\t \".strip()\n\n\"Jake likes his dog.\".startswith(\"Anne\")\n\n\"Jake likes his dog.\".startswith(\"Jake\")\n\n\"Anne\" or \"Jake\" # Don't do: string.startswith(a or b)\n\n\"abc,-\".replace(\",\", \"\")\n\n\"abc,-\".replace(\",\", \"\").replace(\"-\", \"\")\n\n# Regular expressions\nimport re\nre.findall(\"[\\w]+\", \"Titus Andronicus Roman-legion\")\n\n\n# ## Heavy computations and lazy evaluation\n\n# a very heavy computation\ndef transform_word(word):\n count = 0\n for i in range(1000):\n count += i\n if len(word)>3:\n return word.lower().replace(' ', 'a').replace('Romeo', 'Julia').replace('b', 'c')\n else:\n return \"veryLongWord\"\n\n\nwords\n\nwords_transformed = words.map(lambda x: transform_word(x))\n\nwords_uppercase = words_transformed.map(lambda x: x.upper())\n\nwords_uppercase.getNumPartitions()\n\nwords_repartitioned = words_uppercase.repartition(8)\n\nwords_repartitioned.getNumPartitions()\n\nword_dict = words_repartitioned.countByValue()\n\nword_dict\n\nsorted(word_dict.items(),key=lambda i: i[1],reverse=True)\n\nwords_repartitioned.take(10)\n\n# ![](imgs/RDD_Operations.png)\n","repo_name":"rafalpa/introduction_to_big_data_nordea","sub_path":"spark/notebooks/03-Action_Transform_WordCount.ipynb","file_name":"03-Action_Transform_WordCount.ipynb","file_ext":"py","file_size_in_byte":2939,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"21"} +{"seq_id":"31600737821","text":"# + [markdown] id=\"TxAFRwRkk824\"\n# \n# \"Open\n# \n\n# + [markdown] id=\"MxEUxKFQgXH2\"\n# ## Upload a video file\n\n# + id=\"of1otpd8gher\"\nfrom google.colab import files\nmy_vidoe = files.upload()\n\n# + [markdown] id=\"dkf44S4phXT1\"\n# ## Clone and Install Annolid\n\n# + id=\"Ukc8U43Kgq7X\"\n# The root folder\n# %cd /content\n# Clone the repo\n# !git clone --recurse-submodules https://github.com/healthonrails/annolid.git\n\n\n# + id=\"SNmoUKrDh0ix\"\n# install annolid\n# %cd /content/annolid/\n# !pip install -e .\n\n# + [markdown] id=\"MXqnKffAid95\"\n# # Extract frames from a video\n\n# + id=\"FtfBslDJih5I\"\nimport glob\nfrom annolid.data.videos import extract_frames\n\n# + id=\"CkYQTznQih67\"\n# You can upload a video or use gdown to download video from Google drive\n# Please change the absolute video path e.g. /content/wbc.mp4\nvideo_file = \"/content/out.mp4\" #@param\nframes = extract_frames(video_file=video_file,num_frames=100,algo=\"random\")\nfor frame in frames:\n print(frame)\n\n# + [markdown] id=\"3xTKahdfj-ir\"\n# ##Extract frames from a folder contains a list videos\n\n# + id=\"IbV4YktAK6NA\"\nvideo_dir = '/content/myvideo' #@param\nnum_frames= 100 #@param\nfor video in glob.glob(video_dir + '/*mp4'):\n frames = extract_frames(video_file=video,\n num_frames=num_frames,\n algo=\"random\")\n for frame in frames:\n print(frame)\n\n\n# + [markdown] id=\"x17arPW4zMez\"\n# # Zip and Download the extracted frames\n\n# + id=\"EhVkv7P5zRWy\"\n# please input the correct absolute folder path for the extracted frames\n# e.g. /content/wbc\n# !zip -r -D my_extracted_video_frames.zip /content/my_video\nfiles.download('my_extracted_video_frames.zip')\n","repo_name":"healthonrails/annolid","sub_path":"docs/tutorials/Extract_frames_from_a_video.ipynb","file_name":"Extract_frames_from_a_video.ipynb","file_ext":"py","file_size_in_byte":1896,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-jupyter-script","pt":"21"} +{"seq_id":"8831913391","text":"\"\"\"\nA guest is considered 'fashionably late' if they arrived after at least half of the party's guests. However, they must not be the very last guest (that's taking it too far). Given an ordered list of arrivals to the party and a name, return whether the guests were fashionably late.\n\"\"\"\n\n\n# +\ndef fashionably_late(arrivals):\n arr = []\n p_len = len(arrivals)\n half_p_len = p_len / 2\n\n for i in range(p_len):\n if i >= half_p_len and i != p_len-1:\n arr.append(arrivals[i])\n return arr \n\n\nparty_attendees = ['Adela', 'Fleda', 'Owen', 'May', 'Mona', 'Gilbert', 'Ford']\nfashionably_late(party_attendees)\n# -\n\n\n","repo_name":"AShabunevich/Kaggle_practice_and_exercises","sub_path":"python/lists.ipynb","file_name":"lists.ipynb","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"21"} +{"seq_id":"31595922725","text":"import pandas as pd\nimport numpy as np\n\niris = pd.read_csv(\"data/iris.csv\")\niris.head()\n\nX = iris[[\"SepalLength\", \"SepalWidth\", \"PetalLength\", \"PetalWidth\"]]\ny = iris[\"species\"]\n\n# +\n# Data distributions\n\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n# %matplotlib inline\n\nsns.set()\nsns.pairplot(iris, hue=\"species\")\n# -\n\n#\n#\n# Data Distribution looks seperable with normal boundries of seperation might be linear seperable or non-linear but no need of special kernels to fit the boundries\n#\n#\n#\n\n# +\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=4)\nlogistic_reg = LogisticRegression()\nlogistic_reg.fit(X_train, y_train)\ny_predict = logistic_reg.predict(X_test)\n\n\n# +\nfrom sklearn.metrics import confusion_matrix\n\n#pipe_svc.fit(X_train, y_train)\n#y_pred = pipe_svc.predict(X_test)\nconfmat = confusion_matrix(y_true=y_test, y_pred=y_predict)\nprint(confmat)\n\n# +\nimport matplotlib.pyplot as plt\n\nfig, ax = plt.subplots(figsize=(2.5, 2.5))\nax.matshow(confmat, cmap=plt.cm.Blues, alpha=0.3)\nfor i in range(confmat.shape[0]):\n for j in range(confmat.shape[1]):\n ax.text(x=j, y=i, s=confmat[i, j], va='center', ha='center')\n\nplt.xlabel('predicted label')\nplt.ylabel('true label')\n\nplt.tight_layout()\nplt.show()\n\n# +\nfrom sklearn import metrics\n\naccuracy = metrics.accuracy_score(y_test, y_predict)\nprint('accuracy scores: %s' % accuracy)\n\n# +\n#Applting k-NN for k = 1 to 40\n\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.cross_validation import cross_val_score\n\nk_range = range(1,40)\naccuracyScore = []\nfor k in k_range:\n knn = KNeighborsClassifier(k)\n accuracy = cross_val_score(knn,X, y, cv=10, scoring=\"accuracy\")\n accuracyScore.append(accuracy.mean())\n\n# +\nimport matplotlib.pyplot as plt\n\nplt.plot(k_range, accuracyScore)\nplt.xlabel(\"K value\")\nplt.ylabel(\"Accuracy for give k\")\nplt.title(\"Accuracy Graph\")\nplt.show()\n\n# +\n#minimum value for 'k' where acuuracy is maximised is 13 post 13 chance of overfiiting is there\n\nimport numpy as np\n\nknn = KNeighborsClassifier(13)\naccuracy = cross_val_score(knn,X, y, cv=10, scoring=\"accuracy\")\n#accuracy.mean()\nprint('CV accuracy: %.3f +/- %.3f' % (np.mean(accuracy), np.std(accuracy)))\n# -\n\n\n","repo_name":"ravi-code-ranjan/uci-machine-learning-repo","sub_path":"iris/ML-Iris.ipynb","file_name":"ML-Iris.ipynb","file_ext":"py","file_size_in_byte":2323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"21"} +{"seq_id":"74990637812","text":"# +\nimport pandas as pd\nimport numpy as np\nfrom itertools import chain\n\nfrom bokeh.models.widgets import Panel, Tabs\nfrom bokeh.io import output_file, show\nfrom bokeh.plotting import figure\nfrom bokeh.models import HoverTool\nimport math\n# -\n\ndf = pd.read_csv(\"fire.csv\")\ndf.head()\n\ndff=df.copy()\ndff = (dff.set_index(dff.columns.drop('county',1).tolist())\n .county.str.split(',', expand=True)\n .stack()\n .reset_index()\n .rename(columns={0:'county'})\n .loc[:, dff.columns]\n)\ndff.drop(['fire_name'],axis=1)\ndff.head()\n\ntemp_df = dff.groupby(['year']).sum().reset_index()\ntemp_df.head()\n\n# +\noutput_file(\"line_chart.html\", title=\"Line Chart\")\n\n\nTOOLS = 'save,pan,box_zoom,reset,wheel_zoom,hover'\np1 = figure(title=\"Year-wise total number of acres\", y_axis_type=\"linear\", plot_height = 600,\n tools = TOOLS, plot_width = 800,y_range=(110000,860000))\np1.xaxis.axis_label = 'Year'\np1.yaxis.axis_label = 'Total acres'\np1.circle(1999, temp_df.acres.min(), size = 10, color = 'red')\np1.circle(2018, temp_df.acres.max(), size = 10, color = 'red')\n\np1.line(temp_df.year, temp_df.acres,line_color=\"purple\", line_width = 3)\np1.select_one(HoverTool).tooltips = [\n ('year', '@x'),\n ('acres', '@y'),\n]\ntab1 = Panel(child=p1, title=\"Acres affected\")\n\n\np2 = figure(x_range=df.fire_name, plot_height=600,plot_width=800, title=\"Number of Deaths\")\np2.vbar(x=df.fire_name, top=df.deaths, width=0.9)\np2.xaxis.major_label_orientation = math.pi/3\np2.xgrid.grid_line_color = None\np2.xaxis.axis_label = 'Fire Name'\np2.yaxis.axis_label = 'Deaths'\nhover=HoverTool(tooltips=[('Fire Name','@x'),('Deaths','@top')])\n\np2.add_tools(hover)\n\ntab2 = Panel(child=p2, title=\"#Deaths\")\n\n\ntabs = Tabs(tabs=[ tab1, tab2 ])\nshow(tabs)\n# -\n\n\n","repo_name":"kvartak2/Data-Visualization-Largest-California-Wildfires-using-Bokeh","sub_path":"Fire.ipynb","file_name":"Fire.ipynb","file_ext":"py","file_size_in_byte":1723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"21"} +{"seq_id":"34609553954","text":"import pandas_datareader as pdr\nimport pandas as pd\n\n# # Quarterly Data\n\n# +\n# TOTAL DEBT ($ Millions)\ndebt = pdr.DataReader('GFDEBTN', data_source='fred', start='1966-01-01')\ndebt.columns = ['Debt ($M)']\n# Nominal GDP\ngdp = pdr.DataReader('GDP', data_source='fred', start='1966-01-01')\ngdp.columns = ['GDP ($B)']\n\n# Debt to GDP ratio\nd_2_g = debt['Debt ($M)'] / (gdp['GDP ($B)'] * 1000)\n\n# Quarterly DataFrame\nquarter_data = pd.concat(objs=[gdp, debt, d_2_g], axis=1)\n# -\n\n# # Annual Data\n\n# +\n# Receipts\nreceipts = pdr.DataReader('FYFR', data_source='fred', start='1966-01-01')\n# Outlays\noutlays = pdr.DataReader('FYONET', data_source='fred', start='1966-01-01')\n# Interest Bill\ni_bill = pdr.DataReader('FYOINT', data_source='fred', start='1966-01-01')\n\n# Shiftimg time to match chronology\nreceipts.index = receipts.index.shift(1, freq='D')\noutlays.index = outlays.index.shift(1, freq='D')\ni_bill.index = i_bill.index.shift(1, freq='D')\n\n#_____calculating statistical numbers_____#\n\n# Surplus/Deficit ($B)\ndeficit = (receipts['FYFR'] - outlays['FYONET']) / 1000\n\n# Surplus/Deficit as a percentage of GDP\ndeficit_per_gdp = deficit / gdp['GDP ($B)']\n \n# Interest bill as a percentage of GDP\ni_bill_gdp = (i_bill['FYOINT']/1000) / gdp['GDP ($B)']\n\n# Liquidity Cover\nlq_cover = receipts['FYFR'] / i_bill['FYOINT']\n \n# Annual Data\nannual = [receipts, outlays, deficit, deficit_per_gdp, i_bill, i_bill_gdp, lq_cover]\nannual_data = pd.concat(objs=annual, axis=1)\nannual_data.head(3)\n# -\n\nquarter_data\n\n# +\ngovt_df = pd.concat(objs=[quarter_data, annual_data], axis=1)\n\nrname_list = ['GDP ($B)', 'Debt ($M)', 'Debt to GDP', 'Receipts', 'Outlays', 'Surplus', 'Surplus%GDP', 'Interest bill', 'Interest%GDP', 'Liquidity Cover']\n\ngovt_df.columns = rname_list\n\ngovt_df\n\n# +\n# Surplus/Deficit\n\n(receipts['FYFR'] - outlays['FYONET']) / 1000\n\n# +\n# Surplus/Deficit as a percentage of GDP\n\n((receipts['FYFR'] - outlays['FYONET']) / 1000) / gdp['GDP ($B)']\n\n# +\n# Interest bill as a percentage of GDP\n\n((i_bill['FYOINT']/1000) / gdp['GDP ($B)']) * 100\n\n# +\n# Liquidity Cover\n\nreceipts['FYFR'] / i_bill['FYOINT']\n# -\n\n# GDP data ($ Billions)\ngdp = pdr.DataReader('GDP', data_source='fred', start='1966-01-01')\ngdp.columns = ['GDP ($B)']\ngdp\n\nd_2_g = debt['Debt ($M)'] / (gdp['GDP ($B)'] * 1000)\n# d_2_g.columns = ['Debt / GDP ratio']\nd_2_g\n\ndf = pd.concat(objs=[gdp, debt, d_2_g], axis=1)\ndf\n\n# Debt to GDP\ndebt_to_gdp = pdr.DataReader('GFDEGDQ188S', data_source='fred', start='1966-01-01')\n\n# FEDERAL RECEIPTS\nreceipts = pdr.DataReader('FYFR', data_source='fred', start='1966-01-01')\nreceipts\n\n# FEDERAL OUTLAYS\noutlays = pdr.DataReader('FYONET', data_source='fred', start='1966-01-01')\noutlays\n\nreceipts.index = receipts.index.shift(1, freq='D')\n\noutlays.index = outlays.index.shift(1, freq='D')\n\nmain_df = pd.concat(objs=[df, receipts, outlays], axis=1)\nmain_df.rename(columns={0:'Debt to GDP', 'FYFR': 'Receipts ($M)', 'FYONET': 'Outlays ($M)'}, inplace=True)\nmain_df\n\nmain_df.rename(columns={0:'Debt to gdp'})\n\nmain_df.to_csv('fed gov stats.csv')\n\n\n","repo_name":"Kiran-Sawant/US-Macro-Spreadsheet","sub_path":"US/Data Spitter/notebooks/Govt Stats.ipynb","file_name":"Govt Stats.ipynb","file_ext":"py","file_size_in_byte":3055,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"34702625183","text":"import numpy as np\nimport time\nfrom scipy import sparse\nimport random\nimport matplotlib.pyplot as plt\n\n\n# +\ndef prep_data():\n x = np.loadtxt(\"simulated_genos\", delimiter=\" \", dtype=\"float32\")\n y = np.array([[1] * 10000 + [0] * 10000], dtype=\"float32\")\n y_c = y - 0.5\n return x, y_c\n\nx, y_c = prep_data()\n# -\n\nX = x[:,:]\nprint (X.shape)\nprint (np.sum(x))\nn = X.shape[0]\np = X.shape[1]\nprint (n,p)\n\nstart_time = time.clock()\n\n\n\n\n# +\nX_sparse = sparse.csr_matrix(X)\nX_T_sparse = sparse.csr_matrix.transpose(X_sparse)\n\n#K = X@X_T_sparse\n#D = P_0@X_sparse\n\n\n\n#A = P_0@K@P_0\n#print (type(A))\n\n\n# +\n\nSVD_result = lg.svds(X_sparse)\nprint (SVD_result[1])\n\n# -\n\nprint (D.shape)\n\n\nimport scipy.sparse.linalg as lg\nX_T_sparse = sparse.csr_matrix.transpose(X_sparse)\nXX = X_sparse@X_T_sparse\ne = lg.eigs(XX)\nprint (e[0])\n\n\nsorted((SVD_result[1])**2)\n\n# +\n\n\nnp.linalg.eig(XX)\n# -\n\nimport scipy.sparse.linalg as lg\nX_T_sparse = sparse.csr_matrix.transpose(X_sparse)\nXX = X_sparse@X_T_sparse\ne = lg.eigsh(XX)\nprint (e[0])\n\nprint (np.linalg.matrix_rank(X))\n\n\nprint (np.linalg.matrix_rank(X@X.T))\n\n# +\n\nprint (np.linalg.matrix_rank(XX))\n# -\n\n\n\n\n\n\n","repo_name":"jiajingchen/BST234-Project","sub_path":"234Project-4.ipynb","file_name":"234Project-4.ipynb","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"17962357192","text":"# ## If - Elif - Else Loop\n\n# +\n# in If elif else - if is mandetory elif, else are optional\n\n# +\nx = 10\n\nif x > 11:\n print('Number is greater than 10')\nelif x < 5:\n print('Number is less than 5')\nelif x >= 5:\n print('Number is greater than 4 & less than 12')\n\n# +\nx = 15\n\nif x == 15:\n x = 150\nelif x == 20:\n x = 200\nelif x == 25:\n x = 250\nelse:\n x = 300\nx\n\n# +\nx = 150\n\nif x == 7:\n x = 150\nelif x == 150:\n x = 200\nelif x == 200:\n x = 250\nelse:\n x = 300\nx\n\n\n# +\n# elif statements maybe 0 or many\n\n# +\ndef fizzBuzz(x):\n\n if x % 3 == 0 and x % 5 == 0:\n return \"FizzBuzz - div by 3&5\"\n\n if x % 3 == 0 or x % 5 == 0:\n if x % 3 == 0:\n return \"Fizz - div by 3\"\n elif x % 5 == 0:\n return \"Buzz - div by 5\"\n else:\n return x\n\n\nprint(fizzBuzz(15))\nprint(fizzBuzz(5))\n\n\n# +\ndef fizzBuzz(x):\n\n if x % 3 == 0 and x % 5 == 0:\n print(\"FizzBuzz - div by 3&5\")\n else:\n print('Not divisible by both 3&5')\n\n if x % 3 == 0 or x % 5 == 0:\n if x % 3 == 0:\n return \"Fizz - div by 3\"\n elif x % 5 == 0:\n return \"Buzz - div by 5\"\n else:\n return x\n else:\n print('not divisible by 3or5')\n\n\nprint(fizzBuzz(15))\nprint(fizzBuzz(5))\n# -\n\n\n\n# ### Write a prg to calculate bmi - body mass index (bmi = weight / height ^ 2).\n#\n# - if bmi <= 18.5 print \"Underweight\"\n# - if bmi <= 25.0 print \"Normal\"\n# - if bmi <= 30.0 print \"Overweight\"\n# - if bmi > 30 print \"Obese\"\n# - Take inputs => 1. Weight, 2. Height\n# - Formulae: bmi = weight / height ** 2\n\n# +\nweight = float(input(\"Enter the weight: \"))\nheight = float(input(\"Enter the height: \"))\n\nbmi = weight / (height**2)\n\nif bmi <= 18.5:\n print(\"underweight\")\nelif bmi <= 25.0:\n print(\"Normal\")\nelif bmi <= 30.0:\n print(\"Overweight\")\nelse:\n print(\"Obese\")\n# -\n\n\n\n# return will exit the loop print will not\n# return stores the value print will not\n# return generally used in fun\n\n\n\n\n# ## For Loop\n\n# ### For + List\n\nwebsites = [\"amazon\", \"flipkart\", \"snapdeal\", \"paytm\"]\n\nfor item in websites:\n print(\"www.\" + item + \".com\")\n\nfor item in websites:\n # print(\"www.{}.com\".format(item), end=\" \")\n print(\"www.{}.com\".format(item))\n\nwebsites = [\"amazon\", \"flipkart\", \"snapdeal\", \"paytm\"]\nextensions = [\"com\", \"org\", \"in\"]\n\nfor i in websites:\n for j in extensions:\n print(f'www.{i}.{j}')\n\nfor web in websites:\n for ext in extensions:\n print(\"www.{}.{}\".format(web, ext))\n\n\n\n# +\n# multiply each element by some no - method 1\n\ng = [1, 2, 3, 4, 5, 6, 7]\n\nh = []\n\nfor i in g:\n h.append(i * 7)\nh\n\n# +\n#multiply each element by some no - method 2\n\ng = [1, 2, 3, 4, 5, 6, 7]\nj = []\n\nfor i in range(len(g)):\n j.append(g[i] * 7)\n\nj\n\n# +\n#multiply each element by some no - method 3\n\ng = [1, 2, 3, 4, 5, 6, 7]\nj = []\n\nfor i in g:\n j = j + [i * 7]\n\nj\n\n# +\na = [2, 12, 13, 15.1, 17, 10, 17.4, 19, 21]\n\nlist_even = []\nlist_odd = []\nlist_float = []\n\nfor i in a:\n if i % 2 == 0:\n list_even.append(i)\n elif i % 2 == 1:\n list_odd.append(i)\n\n else:\n list_float.append(i)\n\nprint(list_even)\nprint(list_odd)\nprint(list_float)\n# -\n\n\n\n# ### for + dict\n\nvk = {\"Name\" : \"Virat\", \"Age\": 31, \"Team\": \"RCB\", \"Role\": \"Captain\"}\n\nvk.keys()\n\n# Iterate through keys\nfor item in vk:\n print(item)\n\n\n\n# Iterate through values\nfor item in vk.values():\n print(item)\n\n\n\n# Iterate through key-value pairs\nfor key, value in vk.items():\n print(key, value)\n\nvk.items()\n\n\n\nfor i in range(0,3):\n for j in range(0,3):\n print(i,j)\n\nfor i in range(0,3):\n for j in range(0,3):\n print(i,j) # completing this for each i then moving to k\n for k in range(4,7):\n print(i,k) # completing this for each i,k then moving to next i \n\n# +\nx=int(input('no of rows : '))\n\nfor i in range(0,x):\n print(\"*\",end='')\n\n# +\nx=int(input('no of rows : '))\n\nfor i in range(0,x):\n print(\"* \",end='')\n\n# +\nx=int(input('no of rows : '))\n\nfor i in range(0,x):\n print(\"*\")\n\n# +\nx=int(input('no of rows : '))\n\nfor i in range(0,x):\n for j in range(0,i+1):\n print(\"*\",end='')\n \n\n# +\nx=int(input('no of rows : '))\n\nfor i in range(0,x): # decides no of rows \n for j in range(0,i+1): # decides the column structure\n print(\"*\",end='')\n print()\n\n# +\nx=int(input('no of rows : '))\n\nfor i in range(0,x): # decides no of rows \n for j in range(0,i+1): # decides the column structure\n print(\"* \",end='') # added space after *\n print()\n\n# +\nx=int(input('no of rows : '))\n\nfor i in range(0,x): # decides no of rows \n for j in range(0,i+1): # decides the column structure\n print(\"* \",end='') # added space after *\n print()\n# -\n\n\n\n#Program to print Left Half Pyramid\nnum_rows = int(input(\"Enter the number of rows\"));\nfor i in range(0, num_rows):\n for j in range(0, i+1):\n print(\"* \", end=\"\")\n print()\n\n#Program to print Left Half Pyramid\nnum_rows = int(input(\"Enter the number of rows\"));\nk = 1\nfor i in range(0, num_rows):\n for j in range(0, k):\n print(\"* \", end=\"\")\n k = k + 1\n print()\n\n# Program to print full pyramid\nnum_rows = int(input(\"Enter the number of rows\"));\nfor i in range(0, num_rows):\n for j in range(0, num_rows-i-1):\n print(end=\" \")\n for j in range(0, i+1):\n print(\"*\", end=\" \")\n print()\n\nn=3\nfor i in range(1,n+1):\n print('*',end=' ')\n print('*'*abs(2-i),end=' ')\n print('*')\n\nTuple1 = ('TechGeek')\nn = 5\nprint(\"\\nTuple with a loop\")\nfor i in range(int(n)):\n Tuple1 = (Tuple1,)\n print(Tuple1)\n\n# +\n# Python program to illustrate\n# enumerate function in loops\nl1 = [\"eat\",\"sleep\",\"repeat\"]\n \n# printing the tuples in object directly\nfor ele in enumerate(l1):\n print (ele)\nprint\n# changing index and printing separately\nfor count,ele in enumerate(l1,100):\n print (count,ele)\n \n#getting desired output from tuple\nfor count,ele in enumerate(l1):\n print(count)\n print(ele)\n# -\n\n\n\n# #### Break Continue & Pass\n\nfor i in 'geeks for geeks':\n if i=='e' or i=='s':\n continue\n print (i)\n\nfor letter in 'geeks for geeks': \n if letter == 'e' or letter == 's':\n continue\n print ('Current Letter :', letter)\n# printing inside the for loop\n\nfor i in 'geeksforgeeks': \n if i == 'e' or i == 's':\n break\n print ('Current i :', i)\n# comes out of for loop after printing\n\n# +\nfor i in 'geeksforgeeks': \n if i == 'e' or i == 's':\n print ('Current i :', i)\n break\n \n# print in the if loop then breaks & comes out of for loop\n# can enter the if loop only for e & s\n# -\n\n# does not matter what condition is it will not execute that loop, execute outof loop\nfor letter in 'geeksforgeeks':\n if letter == 'e' or letter == 's':\n pass\n print ('last Letter :', letter)\n\n# An empty loop\nfor letter in 'geeksforgeeks':\n pass\nprint('Last Letter :', letter)\n\n# +\n#################### FOR LOOP WITH ELSE -- came out because of break ??? #####################################\n\nfor i in range(5):\n print(i)\nelse:\n print('no break')\n\n# +\n############### FOR LOOP WITH ELSE - came out of for loop bcoz of break hence else is not executed ######################\n\nfor i in range(5):\n print(i)\n break\nelse:\n print('no break')\n\n# +\n## See diff of print position - more idea of continue\n\nfor i in range(5):\n print(i)\n continue\n# -\n\nfor i in range(5):\n continue\n print(i)\n\nfor i in range(25,2,-2):\n print (i,end=\" \")\n\n\n\n# #### Break ,Continue & Pass in for loop & def function - diff\n\nfor i in range(25,2,-2):\n pass\n\nfor i in range(25,2,-2):\n continue\n\n\ndef func(x):\n pass\n\n\ndef func(x):\n continue\n\n\n\n\n\n# ## While Loop\n\nl=['harry','sam','soham','sachin','rahul']\ni=0\nwhile i\n\n# \n\n#out link based\nLINKINGS = np.matrix([\n [0,1,1],\n [0,0,1],\n [1,0,0],\n])\nq = 0.5\npageRank(LINKINGS,q,4)\n\n# \n# \n\n# +\n#out link based\nLINKINGS = np.matrix([\n [0,1,1,0,0,0],\n [0,0,0,0,0,0],\n [1,1,0,0,1,0],\n [0,0,0,0,1,1],\n [0,0,0,1,0,1],\n [0,0,0,1,0,0],\n])\nq = 0.15\n\npageRank(LINKINGS,q,4)\n# -\n\n# \n\n# +\n#out link based\nLINKINGS = np.matrix([\n [0,0,0,1],\n [1,0,1,0],\n [1,0,0,0],\n [0,1,1,0],\n])\nq = 0.2\n\npageRank(LINKINGS,q,4)\n# -\n\n# \n# \n\n# +\n#out link based\nLINKINGS = np.matrix([\n [0,1,0,0,0,0],\n [0,0,1,0,0,0],\n [0,0,0,0,1,0],\n [0,1,0,0,0,0],\n [0,0,0,1,0,1],\n [0,0,0,0,0,0],\n])\nq = 0.4\n\npageRank(LINKINGS,q,4)\n# -\n\n\n","repo_name":"thejungwon/dat630_exam_preparation","sub_path":".ipynb_checkpoints/Page_Rank-checkpoint.ipynb","file_name":"Page_Rank-checkpoint.ipynb","file_ext":"py","file_size_in_byte":1662,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"70795337669","text":"print(\"!!! MarkSheet !!!\")\nEnglish = int(input(\"Enter English Marks Obtained !\"))\nPyhsics = int(input(\"Enter Pyhsics Marks Obtained !\"))\nChemistry = int(input(\"Enter Chemistry Marks Obtained !\"))\nIslamiat = int(input(\"Enter Islamiat Marks Obtained !\"))\nMaths = int(input(\"Enter Maths Marks Obtained !\"))\nMarksObtain = English + Pyhsics + Chemistry + Islamiat + Maths\nTotal = 500\nprint(\"Total Marks !\",Total)\nprint(\"Obtained Marks !\",MarksObtain)\nPercentage = (MarksObtain / Total) * 100\nprint(\"Percentage Got !\",Percentage,\"%\")\nif(Percentage>=90):\n print(\"Grade: A\")\nelif(Percentage>=80 and Percentage<90):\n print(\"Grade: B\")\nelif(Percentage>=70 and Percentage<80):\n print(\"Grade: C\")\nelif(Percentage>=60 and Percentage<70):\n print(\"Grade: D\")\nelse:\n print(\"Grade: F\")\n\n# \n\nnumber = int(input(\"Enter a number: \"))\nRemainder = number % 2\nif Remainder > 0 :\n print(\"This is an odd number.\")\nelse :\n print(\"This is an even number.\")\n\t \n\nList = [\"APPLE\",\"BANANA\",\"CAT\",\"DUCK\",\"ELEPHANT\"]\nListLenght = len(List)\nprint(\"The Length Of The List is : \",ListLenght)\n\nList = [1,2,3,4,5]\nSum =sum(List)\nprint(\"The Sum is : \",Sum)\n\nList = [1,2,3,4,5]\nMax = max(List)\nprint(\"Maximum No is : \",Max)\n\nList = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]\nfor i in List:\n if i < 5:\n print(i)\n\n\n","repo_name":"AsadGit89/PythonAssignments_PY00649","sub_path":"Assignment # 2(Roll # PY00649).ipynb","file_name":"Assignment # 2(Roll # PY00649).ipynb","file_ext":"py","file_size_in_byte":1375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"37126000578","text":"# + [markdown] id=\"FpMYK1xZLWmH\"\n#
\n#\n#
M.Sc. DSBA & AI
\n#

Ensemble learning from theory to practice

\n#\n#\n#

\n#
\n#
Boosting
\n#
\n#

\n#\n# The objective of this session is twofold :\n# # + Do some course application exercises (the pdf is on Edunao)\n# # + Use a kind of **ensemble methods** called **boosting** approaches for classification and regression problems in python (`sklearn` module). \n# This lab is free from some of the examples shown in the excellent `Scikit-Learn` documentation on [Adaboost for the classification case](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.AdaBoostClassifier.html) and [Gradient boosting for both classification and regression problems](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.GradientBoostingRegressor.html).\n#\n# Useful reference links:\n# # + [`Scikit-learn` website](https://scikit-learn.org/stable/index.html)\n# # + [`NumPy` documentation](https://docs.scipy.org/doc/numpy/user/index.html)\n# # + [`SciPy` documentation](https://docs.scipy.org/doc/scipy/reference/)\n# # + [`MatPlotLib` documentation](https://matplotlib.org/)\n# # + [Python website](https://www.python.org/)\n#\n#\n#\n\n# + [markdown] id=\"kWn1wT2QLWml\"\n#\n#\n# In his machine learning class project in the late 80’s, Kearns and Valiant asked the following [question](https://www.cis.upenn.edu/~mkearns/papers/boostnote.pdf):\n#\n# Can a set of weak learners be combined to generate a strong learner (with low bias)?\n#\n# The question was [answered in the positive by Schapire (1990)](https://www.cs.princeton.edu/~schapire/papers/strengthofweak.pdf), and implemented, with Freund, in the form of AdaBoost.\n#\n# In the previous lab we study one kind of ensemble methods nammed bagging approaches where the principle is to aggregate several predictions from weak learners while hoping for a better result.\n# An amazing story can illustrate this principle of grouping weak models to improve the final result. This idea was also tested with pigeons. Scientists trained 16 pigeons (weak learners if ever there were ones) to identify pictures of magnified biopsies of possible breast cancers. On average, each pigeon had an accuracy of about 85%, but when the most popular answer among the group was selected, the accuracy jumped to 99% (see this [link](https://www.scientificamerican.com/article/using-pigeons-to-diagnose-cancer/) for more details).\n#\n# The pigeon work above is a form of bootstrap aggregation (also known as bagging). In this lab, we explore two algorithms that use a different approach to answer Kearns and Valiant’s question: **AdaBoost** and **Gradient Boosting**, which are two different implementations of the idea behind boosting. \n#\n# Boosting is the second kind of ensemble methods. The principle of boosting is to evaluate a sequence of weak learners on several slightly modified versions of the training data. The decisions obtained are then combined by a weighted sum to obtain the final model. \n#\n# In the following we will explore the boosted algorithms cited using `Scikit-learn` and present some comparisons.\n#\n#\n# ### AdaBoost\n#\n# The Python library `Scikit-learn` provides a useful implementation of **AdaBoost**. In order to use it, a base estimator (that is to say, a weak learner) must first be selected. In what follows, we will use a `DecisionTreeClassifier`. Once this is done, a `AdaBoostClassifier` object is created, to which is fed the weak learner, the **number of estimators** and the **learning rate** (also known as the **shrinkage parameter**, a small positive number). In general, small learning rates will require a large number of estimators to provide adequate performance. By default, `Scikit-learn`’s implementation uses 50 estimators with a learning rate of 1.\n#\n#\n# ## Two-Moons Classification\n#\n# We use the classic two-moons dataset, consisting of two interleaving half circles with added noise, in order to test and compare classification results for **AdaBoost** (and **Gradient Boosting** in the next part of the lab). This dataset is conveniently built-in to `Scikit-learn` and accessible via `make_moons`, which returns a data matrix `X ` and a label vector `y`. We can treat the dataset as a complete training set as we eventually use cross-validation to estimate the test error.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 265} executionInfo={\"elapsed\": 1074, \"status\": \"ok\", \"timestamp\": 1612363792182, \"user\": {\"displayName\": \"Tami Myriam\", \"photoUrl\": \"\", \"userId\": \"04534705195482337784\"}, \"user_tz\": -60} id=\"FxJNJlOl1rnD\" outputId=\"e901d73d-2112-4cf3-f29f-c0a54bd8bef4\"\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.tree import DecisionTreeClassifier\nimport numpy as np\nimport matplotlib.pyplot as plt\n# %matplotlib inline\nfrom sklearn.datasets import make_moons\nN = 1000\n#The data\nX,Y = make_moons(N,noise=0.2)\nplt.scatter(X[:,0],X[:,1], c=Y)\nplt.show()\n\n# + [markdown] id=\"D2gx2EDwtw2o\"\n# **Question 1:**\n#\n# Classify the data using a decision tree i.e: using `DecisionTreeClassifier` with maximum depth of 3 (this structure will later be used for our weak learners). Then plot the result by using `meshgrid` from `numpy` which is very useful to evaluate functions on a grid.\n#\n# **Solution**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 269} executionInfo={\"elapsed\": 1122, \"status\": \"ok\", \"timestamp\": 1612363795277, \"user\": {\"displayName\": \"Tami Myriam\", \"photoUrl\": \"\", \"userId\": \"04534705195482337784\"}, \"user_tz\": -60} id=\"RbC2ih9ptw2p\" outputId=\"5fc28e1b-c68d-4df9-a2f0-af6d55bbbfbc\"\n# Write code here to classify the data using a decision tree with maximum depth of 3\nclf = DecisionTreeClassifier(max_depth=3)\nclf.fit(X,Y)\n#Thanks to meshgrid from numpy an lindspace create a grid\nxx,yy = np.meshgrid(np.linspace(-1.5,2.5,50),np.linspace(-1,1.5,50))\n#Predict on the grid values by using xx and yy\nZ = clf.predict(np.c_[xx.ravel(), yy.ravel()])\nZ = Z.reshape(xx.shape)\n#Plot the classification result on the two-moons. You can use contourf() to vizualize the classes\nplt.scatter(X[:,0],X[:,1], c = Y)\nplt.contourf(xx,yy,Z,alpha=0.3)\nplt.show()\n\n\n\n# + [markdown] id=\"40gG8bHqtw2u\"\n# **Question 2:**\n#\n# What do you think about the fit of this single decision tree?\n#\n\n# + [markdown] id=\"bqwRF5ps1rnH\"\n# **Solution**\n#\n# As can be seen from the graph above, this single decision tree does not provide the best of fits.\n\n# + [markdown] id=\"I8yoxZmy1rnH\"\n# Next, we obtain an AdaBoost classification. Let’s first consider a model consisting of 10 decision trees, and with a learning rate of 1/10.\n#\n# **Question 3:**\n#\n# Use `AdaBoostClassifier` to classify the data with the decision tree `clf` as weak learner by adding the parameters of 10 estimators and 0.1 for the learning rate value. \n#\n# **Solution**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 269} executionInfo={\"elapsed\": 1267, \"status\": \"ok\", \"timestamp\": 1612363799587, \"user\": {\"displayName\": \"Tami Myriam\", \"photoUrl\": \"\", \"userId\": \"04534705195482337784\"}, \"user_tz\": -60} id=\"EX4XByYXtw2v\" outputId=\"3760be57-683e-43a2-da53-b60668b21308\"\nada = AdaBoostClassifier(clf, n_estimators=10, learning_rate=0.1)\nada.fit(X,Y)\n#Thanks to meshgrid from numpy an lindspace create a grid\nxx,yy = np.meshgrid(np.linspace(-1.5,2.5,50),np.linspace(-1,1.5,50))\n#Predict on the grid values by using xx and yy\nZ = ada.predict(np.c_[xx.ravel(), yy.ravel()])\nZ = Z.reshape(xx.shape)\n#Plot the classification result on the two-moons. You can use contourf() to vizualize the classes\nplt.scatter(X[:,0],X[:,1], c = Y)\nplt.contourf(xx,yy,Z,alpha=0.3)\nplt.show()\n\n# + [markdown] id=\"nKhBerkg1rnH\"\n# **Question 3:**\n#\n# AdaBoosted tree is it better thant a single decision tree to capture the two-moon dataset structure? Can we be in an overfitting situation? \n#\n# **Solution**\n#\n# The AdaBoosted tree is better at capturing the dataset’s structure. Of course, until we evaluate the performance on an independent test set, this could simply be a consequence of overfitting (one of AdaBoost’s main weaknesses, as the procedure is sensitive to outliers and noise). We can guard against this eventuality by adjusting the learning rate (which provides a step size for the algorithm’s iterations).\n\n# + [markdown] id=\"EUiESSAU1rnI\"\n# One of **AdaBoost’s main weaknesses**, as the procedure **is sensitive to outliers and noise**. We can guard against this eventuality by adjusting the **learning rate** which provides a step size for the algorithm’s iterations. \n#\n# To find the optimal value for the learning rate and the number of estimators, one can use the `GridSearchCV` method from `sklearn.model_selection`, which implements **cross-validation** on a **grid of parameters**. It can also be parallelized, in case the efficiency of the algorithm should ever need improving (that is not necessary on such a small dataset, but could prove useful with larger datasets).\n\n# + [markdown] id=\"_0_HbTNY1rnI\"\n# **Question 4:**\n#\n# Using the `GridSearchCV` method, tune both parameters `n_estimators` and `learning_rate`. In other words, search of the values of these parameters allowing to get the best result? For which values do we get this best result? \n#\n# **Solution**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"elapsed\": 130602, \"status\": \"ok\", \"timestamp\": 1612363935345, \"user\": {\"displayName\": \"Tami Myriam\", \"photoUrl\": \"\", \"userId\": \"04534705195482337784\"}, \"user_tz\": -60} id=\"5F7jP2Ir1rnJ\" outputId=\"904af42a-acff-4e9d-dcb5-b50b6559c58c\"\nfrom sklearn.model_selection import GridSearchCV\nparams = {\n 'n_estimators': np.arange(10,300,10), \n 'learning_rate': [0.01, 0.05, 0.1, 1], \n }\ngrid_cv = GridSearchCV(AdaBoostClassifier(), param_grid= params, cv=5, n_jobs=-1)\ngrid_cv.fit(X,Y) \ngrid_cv.best_params_ \nprint('The best parameters values are ', grid_cv.best_params_) \n\n# + [markdown] id=\"oJDPuWTF1rnK\"\n# The results show that, given the selected grid search ranges, the optimal parameters (those that provide the best cross-validation fit for the data) are 200 estimators with a learning rate of 0.1. The following plot of the model of these parameters indeed shows that the fit looks might fine.\n\n# + [markdown] id=\"M0vCQS_-tw2_\"\n# **Question 5:**\n#\n# Plot the model of these parameters. The tuned classification model fits fine?\n#\n# **Solution:**\n#\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 269} executionInfo={\"elapsed\": 935, \"status\": \"ok\", \"timestamp\": 1612364113783, \"user\": {\"displayName\": \"Tami Myriam\", \"photoUrl\": \"\", \"userId\": \"04534705195482337784\"}, \"user_tz\": -60} id=\"5BnT2h8Jtw3A\" outputId=\"cd334d41-2326-4b47-abda-1da7dc66c191\"\nada = grid_cv.best_estimator_\nxx,yy = np.meshgrid(np.linspace(-1.5,2.5,50),np.linspace(-1,1.5,50))\nZ = ada.predict(np.c_[xx.ravel(), yy.ravel()])\nZ = Z.reshape(xx.shape)\nplt.scatter(X[:,0],X[:,1], c = Y)\nplt.contourf(xx,yy,Z,alpha=0.3)\nplt.show()\n\n# + [markdown] id=\"1R3K4pNNLWm0\"\n# ### Gradient Boosting\n#\n# The implementation of Gradient Boosting is simpler than AdaBoost. The idea is to first fit a model, then to compute the residual generated by this model. Next, a new model is trained, but on the residuals instead of on the original response. The resulting model is added to the first one. Those steps are repeated a sufficient number of times. The final model will be a sum of the initial model and of the subsequent models trained on the chain of residuals. See the Boosting lecture for more details. Also, note that initially users adjusted the depth of the weak learners to **stumps depth** (i.e: 2) but now users prefer to vary between stumps to **interaction models** which have a depth more than 3. There is evidence to suggest that a depth value in {4, ..., 8} is adequate for most boost applications (see [Wikipedia](https://en.wikipedia.org/wiki/Gradient_boosting)).\n#\n#\n# Instead of two-moons dataset we now will consider a training set consisting of a noisy parabola.\n#\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 265} executionInfo={\"elapsed\": 735, \"status\": \"ok\", \"timestamp\": 1612364116931, \"user\": {\"displayName\": \"Tami Myriam\", \"photoUrl\": \"\", \"userId\": \"04534705195482337784\"}, \"user_tz\": -60} id=\"Ldqmxd1Q1rnK\" outputId=\"8e2df3b9-ae99-4f53-ff44-72bca4f102dd\"\nN = 200\nX = np.linspace(-1,1,N)\nY = X**2+ np.random.normal(0,0.07,N)\nX = X.reshape(-1,1)\nplt.scatter(X,Y)\nplt.show()\n\n# + [markdown] id=\"_dYfdPAV1rnL\"\n# With this data, we can use `DecisionTreeRegressor` from `sklearn.tree` to fit the initial model H_0.\n#\n# **Question 6:**\n#\n# Fit and plot on these new data a decision tree regressor with a value of 3 for the `max_depth` parameter(such as we choose initially). \n#\n# **Solution**\n#\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 265} executionInfo={\"elapsed\": 978, \"status\": \"ok\", \"timestamp\": 1612364119828, \"user\": {\"displayName\": \"Tami Myriam\", \"photoUrl\": \"\", \"userId\": \"04534705195482337784\"}, \"user_tz\": -60} id=\"bGrC0Dnstw3L\" outputId=\"d217fb9c-29ce-4a86-e68b-e28fe6642a37\"\nfrom sklearn.tree import DecisionTreeRegressor\n#Construct and fit the decision tree model for the regression task\nreg1 = DecisionTreeRegressor(max_depth=3)\nreg1.fit(X,Y)\n#Plot the data and the model fitting\nplt.figure()\nplt.scatter(X,Y)\nplt.plot(X,reg1.predict(X), 'r')\nplt.show()\n \n\n# + [markdown] id=\"vBQR0pu1tw3P\"\n# **Question 7**\n#\n# Now compute the residuals and fit a new model h_1 on it. \n#\n# **Solution**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 267} executionInfo={\"elapsed\": 1217, \"status\": \"ok\", \"timestamp\": 1612364122602, \"user\": {\"displayName\": \"Tami Myriam\", \"photoUrl\": \"\", \"userId\": \"04534705195482337784\"}, \"user_tz\": -60} id=\"C7zexDb81rnM\" outputId=\"09ff3b42-1a63-4426-ab6d-6c9a757fb246\"\n#Compute the residuals named Y2\nY2 = Y - reg1.predict(X)\n#Build and fit a new decision tree regressor on the residuals\nreg2 = DecisionTreeRegressor(max_depth=2)\nreg2.fit(X,Y2)\n#Plot the residuals and the model fiting\nplt.scatter(X,Y2)\nplt.plot(X,reg2.predict(X),'r')\nplt.show()\n\n\n# + [markdown] id=\"qwkNB0FE1rnM\"\n# The resulting model at this step is H_1 = H_0 + h_1.\n#\n# **Question 8**\n#\n# Plot the parabola data and both models fitting H_0 (in green color) and H_1 (in red color).\n#\n# **Solution**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 265} executionInfo={\"elapsed\": 1264, \"status\": \"ok\", \"timestamp\": 1612364125812, \"user\": {\"displayName\": \"Tami Myriam\", \"photoUrl\": \"\", \"userId\": \"04534705195482337784\"}, \"user_tz\": -60} id=\"bs-6u1Ax1rnM\" outputId=\"8e12e195-4d2c-4b96-b090-1c7dae546186\"\nH_0 = reg1.predict(X)\nh_1 = reg2.predict(X)\nH_1 = H_0 + h_1\nplt.scatter(X,Y)\nplt.plot(X,H_1,'r', label = \"H_1=H_0 + h_1\")\nplt.plot(X,H_0,'g', label = \"H_0\")\nplt.legend()\nplt.show()\n\n# + [markdown] id=\"Acwq8XVy1rnN\"\n# Here, you can see that the new model H_1 (in red) is a better fit for the data than H_0 (in green). \n#\n# **Question 9**\n#\n# Repeat this process a second time to get an even better approximation H_2.\n#\n# **Solution**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 265} executionInfo={\"elapsed\": 766, \"status\": \"ok\", \"timestamp\": 1612364129297, \"user\": {\"displayName\": \"Tami Myriam\", \"photoUrl\": \"\", \"userId\": \"04534705195482337784\"}, \"user_tz\": -60} id=\"cMKuf0ya1rnN\" outputId=\"26977956-6c22-4f6b-8774-a3e0b9e5c606\"\nY3 = Y2 - reg2.predict(X)\nreg3 = DecisionTreeRegressor(max_depth=2)\nreg3.fit(X,Y3)\nh = sum(tree.predict(X) for tree in (reg2,reg3))\nH_2 = H_0 + h\n#Plot\nplt.scatter(X,Y)\nplt.plot(X,H_0, label = \"H_0\")\nplt.plot(X,H_1, label = \"H_0 + h_1\")\nplt.plot(X,H_2, label = \"H_0 + h_1 + h_2\")\nplt.legend()\nplt.show()\n\n# + [markdown] id=\"t4VanNGI1rnO\"\n# Doing this manually can be tedious, so we use `GradientBoostingRegressor` from `sklearn.ensemble`, which recreates the steps we have produced above.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 550} executionInfo={\"elapsed\": 1927, \"status\": \"ok\", \"timestamp\": 1612364133119, \"user\": {\"displayName\": \"Tami Myriam\", \"photoUrl\": \"\", \"userId\": \"04534705195482337784\"}, \"user_tz\": -60} id=\"iqIISPt0tw3U\" outputId=\"a606e6fa-898c-4180-a450-50893516cef5\"\nfrom sklearn.ensemble import GradientBoostingRegressor\nfrom sklearn.metrics import mean_squared_error as mse\nfig=plt.figure(figsize=(12, 8), dpi= 80, facecolor='w', edgecolor='k')\nfor n in enumerate([1,3,5,10]):\n gb = GradientBoostingRegressor(max_depth=2, n_estimators=n[1],learning_rate=1)\n gb.fit(X,Y)\n plt.subplot(2,2,n[0]+1)\n plt.scatter(X,Y)\n plt.plot(X,gb.predict(X), 'r')\n acc = mse(Y, gb.predict(X))\n plt.title('n = %i, mse = %f' %(n[1], acc))\n\n# + [markdown] id=\"37BFp83aXPLy\"\n# As we can see from the figure above, increasing the number of steps M leads to a better fit, and thus to a lower **mean squared error (MSE)**. However, this may also lead to overfitting, which is why this M parameter (number of steps) should not be too high. There are many ways to determine the optimal M for a given dataset; cross-validation (as we did for AdaBoost above) is a commonly-used approach.\n\n# + [markdown] id=\"WufxK2Wt1rnO\"\n# **Question 10:**\n#\n# Using the `GridSearchCV` method, tune both parameters `n_estimators` and `learning_rate`. For which values do we get the best result? \n#\n# **Solution:**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 282} executionInfo={\"elapsed\": 24051, \"status\": \"ok\", \"timestamp\": 1612364160240, \"user\": {\"displayName\": \"Tami Myriam\", \"photoUrl\": \"\", \"userId\": \"04534705195482337784\"}, \"user_tz\": -60} id=\"3GXsJPFVtw3b\" outputId=\"62477723-d89f-408c-ec6d-0ee4b9e2c2fc\"\nparams = {\n 'n_estimators': np.arange(1,101),\n 'learning_rate': [0.01, 0.05, 0.1, 1],\n }\ngrid_cv = GridSearchCV(GradientBoostingRegressor(max_depth=2), param_grid= params, cv=5, n_jobs=-1)\ngrid_cv.fit(X,Y)\nprint(\"Best params:\", grid_cv.best_params_)\nclf = grid_cv.best_estimator_\nplt.scatter(X,Y)\nplt.plot(X,clf.predict(X), 'r')\nplt.show()\n\n# + [markdown] id=\"O5GeXo6Jtw3f\"\n# ## Gradient Boosting and Classification\n#\n# With the appropriate loss function, **Gradient Boosting also works for classification**. Here we will apply Gradient boosting in the classification case on the data generated by the make_moons function from `sklearn.dataset`.\n\n# + [markdown] id=\"Zdan4zV-tw3i\"\n# **Question 11**\n#\n# Such we did at the begining, simulate a two-moons dataset with a size of N=1000 and a noise of 0.2. Then build a Gradient Boosted Classifier and plot the fitted model on the dataset to visualize the classes obtained. \n#\n# **Solution**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 269} executionInfo={\"elapsed\": 981, \"status\": \"ok\", \"timestamp\": 1612364165419, \"user\": {\"displayName\": \"Tami Myriam\", \"photoUrl\": \"\", \"userId\": \"04534705195482337784\"}, \"user_tz\": -60} id=\"hgDh20Hm1rnP\" outputId=\"5d2b6f06-c8b9-4abc-fcfb-afed7d7a1b2c\"\nfrom sklearn.ensemble import GradientBoostingClassifier\nN = 1000 \nX,Y = make_moons(N,noise=0.2) \ngbc = GradientBoostingClassifier(n_estimators=9, learning_rate=0.5) \ngbc.fit(X,Y) \nxx,yy = np.meshgrid(np.linspace(-1.5,2.5,50),np.linspace(-1,1.5,50)) \nZ = gbc.predict(np.c_[xx.ravel(), yy.ravel()]) \nZ = Z.reshape(xx.shape) \nplt.scatter(X[:,0],X[:,1], c = Y) \nplt.contourf(xx,yy,Z,alpha=0.3) \nplt.show()\n\n# + [markdown] id=\"B3ioXmz3XYm4\"\n# **Question 12**\n#\n# Import the `accuracy_score` from `sklearn.metrics` and print it for the previous model. Comment the accuracy score value.\n#\n# **Solution**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"elapsed\": 1360, \"status\": \"ok\", \"timestamp\": 1612364168893, \"user\": {\"displayName\": \"Tami Myriam\", \"photoUrl\": \"\", \"userId\": \"04534705195482337784\"}, \"user_tz\": -60} id=\"8f_Q7CFu1rnP\" outputId=\"f2fc6db8-ffb9-484e-afba-2ae244a8334e\"\nfrom sklearn.metrics import accuracy_score\naccuracy_gbc=accuracy_score(y_pred=gbc.predict(X), y_true=Y)#To remove\nprint('Accuracy score ', accuracy_gbc)\n\n# + [markdown] id=\"drqMwrKX1rnP\"\n# We can see that the resulting model has a pretty good accuracy as well. Note that if you didn't split the data in train and test sets the accuracy score obtained is meaningless as without some evaluation of the test error.\n#\n#\n# **Question 13**\n#\n# If you forgot to use `train_test_split()` function from `sklearn.model_selection` do it now and compute the meaningfull accuracy score value (on the test set of the data).\n#\n# **Solution**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 282} executionInfo={\"elapsed\": 1722, \"status\": \"ok\", \"timestamp\": 1612364172659, \"user\": {\"displayName\": \"Tami Myriam\", \"photoUrl\": \"\", \"userId\": \"04534705195482337784\"}, \"user_tz\": -60} id=\"_qmU30Xa1rnQ\" outputId=\"f97d9eb8-5a9e-4bb6-a7cb-3f3badd67abf\"\nfrom sklearn.model_selection import train_test_split\nN = 1000 \nX,Y = make_moons(N,noise=0.2) \nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.3)\ngbc = GradientBoostingClassifier(n_estimators=9, learning_rate=0.5) \ngbc.fit(X_train,Y_train) \nxx,yy = np.meshgrid(np.linspace(-1.5,2.5,50),np.linspace(-1,1.5,50)) \nZ = gbc.predict(np.c_[xx.ravel(), yy.ravel()]) \nZ = Z.reshape(xx.shape) \nplt.scatter(X[:,0],X[:,1], c = Y) \nplt.contourf(xx,yy,Z,alpha=0.3) \nplt.show()\naccuracy_gbc=accuracy_score(y_pred=gbc.predict(X_test), y_true=Y_test)\nprint('Accuracy score ', accuracy_gbc)\n\n# + [markdown] id=\"pzx4b2951rnR\"\n# **Question 14**\n#\n# Tune the parameters `n_estimators`and `learning_rate`. Plot again the result and print the accuracy (on the test set). \n#\n# **Solution**\n\n# + id=\"oLx0gtML1rnR\"\nparams = {\n 'n_estimators': np.arange(1,101),\n 'learning_rate': [0.01, 0.05, 0.1, 1],\n }\ngrid_cv = GridSearchCV(GradientBoostingClassifier(), param_grid= params, cv=5, n_jobs=-1)\ngrid_cv.fit(X_train,Y_train)\nprint(\"Best params:\", grid_cv.best_params_)\ngbc_best = grid_cv.best_estimator_\nxx,yy = np.meshgrid(np.linspace(-1.5,2.5,50),np.linspace(-1,1.5,50))\nZ = gbc_best.predict(np.c_[xx.ravel(), yy.ravel()])\nZ = Z.reshape(xx.shape)\nplt.scatter(X[:,0],X[:,1], c = Y)\nplt.contourf(xx,yy,Z,alpha=0.3)\nplt.show()\naccuracy_gbc_best=accuracy_score(y_pred=gbc_best.predict(X_test), y_true=Y_test)\nprint('Accuracy score for GBC tuned ', accuracy_gbc_best)\n","repo_name":"MarcoF7/My-Portfolio","sub_path":"Python/Master of Science in Artificial Intelligence/Machine Learning/Ensemble Learning - Boosting.ipynb","file_name":"Ensemble Learning - Boosting.ipynb","file_ext":"py","file_size_in_byte":22321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"11321648301","text":"# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# \"Open\n\n# + [markdown] id=\"fdpKxDMEUiTb\"\n# Predicting a Startups Profit/Success Rate using Multiple Linear Regression in Python in given 50 Startups Dataset\n\n# + [markdown] id=\"h4I20jDjwy5n\"\n# Task-8 \n#\n# Akash \n# reg no : GO_STP_4114\n#\n# LinearRegression multiple variable \n\n# + id=\"hKtUvbi6UquT\"\nimport pandas as pd\nimport numpy as np \nimport matplotlib.pyplot as plt \nimport sklearn\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import train_test_split\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 206} id=\"EKPuXgIUU6z5\" outputId=\"5641ea45-db3f-4709-ca52-6a0a430dd9b1\"\ndata = pd.read_csv('/content/50_Startups (1).csv')\ndata.head()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 206} id=\"xY5HsF2jVrVk\" outputId=\"e47c069c-a2e8-4f11-de39-41dd9f1b6d19\"\nx=data.drop(['Profit'],axis =1)\nx=x.drop(['State'],axis=1 )\nx.head()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 0} id=\"dXsBXzi3V5CO\" outputId=\"c9acf511-70cb-4535-8e08-612b5fa9aae1\"\ny= data['Profit']\ny.head()\n\n# + id=\"56bX-7XaWIwN\"\nxtrain,xtest,ytrain,ytest= train_test_split(x,y,test_size=0.33, random_state=42)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 0} id=\"xd-M9yEfXTMJ\" outputId=\"f6e2b792-541c-46a4-fbd4-018947962fb9\"\nmodel= LinearRegression()\nmodel.fit(xtrain,ytrain)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 0} id=\"PtamDlHiXgOc\" outputId=\"8e382360-7146-47c9-931e-483ae98893f4\"\nx_predict=model.predict(xtrain)\nx_predict\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 0} id=\"BV5nDO2LhpGJ\" outputId=\"7bdac747-002c-46a4-e92f-91d5b2c37d8b\"\nytest\n\n# + id=\"JqSbl4MBht4E\"\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 0} id=\"2fL7DKbUkEmT\" outputId=\"addf886f-cc9d-4b0e-8fda-94d6d33aa27b\"\nmodel.predict(xtest)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 0} id=\"MW7lsTTykSux\" outputId=\"8acb1022-1306-41ab-a128-78855fc3a4be\"\nytest\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 265} id=\"Tm2YgSg7kVEs\" outputId=\"312e9191-0c50-4392-8d23-cbb2f81acf83\"\nplt.plot(ytest,color='red',marker= '+')\nplt.show()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 265} id=\"0pzEsfMFkive\" outputId=\"f002e36d-31da-49d6-81fa-dcbaeeff4c97\"\nplt.plot(x_predict,color='blue', marker ='+')\nplt.show()\n\n# + id=\"_egZGhebmADz\"\nfrom sklearn import metrics\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 0} id=\"PLhCvrAHtL0t\" outputId=\"29cb262a-5a21-40ff-9456-657170cdba6b\"\nprint('MAE : ', metrics.mean_absolute_error(x_predict,ytrain))\nprint('MSE : ',metrics.mean_squared_error(x_predict,ytrain))\nprint('RMSE :',np.sqrt(metrics.mean_squared_error(x_predict,ytrain)))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 0} id=\"AYWOb31ZvBix\" outputId=\"f6dc72d4-c638-4114-8762-3e560102eeb5\"\nfrom sklearn.metrics import r2_score\nscore = r2_score(x_predict,ytrain)\nprint('Accuracy : ', score)\n\n# + [markdown] id=\"VNdQl85OwtWz\"\n# THE ACCURACY OF THE MODEL IS 94.52 % \n","repo_name":"akash-ssh/codeql-uboot","sub_path":"Predicting_a_Startups_Profit_Success_Rate.ipynb","file_name":"Predicting_a_Startups_Profit_Success_Rate.ipynb","file_ext":"py","file_size_in_byte":3290,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"18537981981","text":"# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# \"Open\n\n# + [markdown] id=\"HlNY2ePEKb1P\"\n# # Árvores de decisão\n#\n# Árvores de decisão são estruturas de dados baseados em \"se...então\" para classificar ou realizar predições (regressões) de dados numéricos. Em geral, estas árvores são baseadas em perguntas, e as respostas a essas perguntas são responsáveis por classificar a resposta.\n#\n# Ademais, uma ávore de decisão não necessariamente precisa ser baseada em uma única pergunta, e as respostas podem ser dados categóricos ou numéricos.\n#\n# Para cada amostra de dados, descemos na árvore desde o nó raiz até chegarmos a um ponto em que não se faz mais necessário realizar nenhuma \"pergunta\", e é aí em que as classificações são feitas.\n#\n# ## Algoritmo\n#\n# O algoritmo se concentra em: \n#\n# - Dadas as características do dataset e das observações, observar o quão bem cada uma divide os dados entre os labels conhecidos. Uma divisão feita de forma não perfeita, ou seja, com resultados de labels diferentes, é chamada de divisão impura.\n#\n# - Para determinar qual divisão é melhor, temos de ter um meio de calcular a impureza de cada divisão.\n#\n# $$gini=1-(probability\\;of\\;yes)^2 - (probability\\;of\\;no)^2$$\n#\n# - É comum que divisões baseadas em alguma tabela (característica) resultem em nós com quantidades de observações diferentes. Portanto, para calcular a impureza (gini) daquela divisão baseada na característica em questão, tomamos a quantidade de observações nos nós divida pela quantidade total de observações nos dois nós e realizamos uma média ponderada destas divisões com base nos valores de impurezas descobertos.\n#\n# - A característica que possuir o menor índice de Gini é então utilizada como nó separador, podendo levar a mais divisões impuras, requisitando novamente a execução do algoritmo.\n#\n# - Caso uma característica seja numérica contínua, seus valores são ordenados do menor para o maior, as médias entre valores adjacentes são obtidas e estas médias são utilizadas para calcular o gini do nó que faz \"característica numérica < valor\". O menor índice de gini para uma certa média faz com que tal média seja posta no lugar de \"valor\".\n\n# + id=\"ede8c48d\"\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.datasets import load_boston, load_iris\nfrom sklearn.tree import DecisionTreeRegressor, DecisionTreeClassifier\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import mean_absolute_error\n\n# + [markdown] id=\"zggasbNIStT-\"\n# Iremos utilizar uma random tree para classificação no dataset **iris** e para regressão no **boston**.\n\n# + [markdown] id=\"O3Q3s_rcS6vG\"\n# ### Classificador com Random Tree\n\n# + id=\"R92D3qqNSoxx\"\nclassifier = DecisionTreeClassifier()\n\nX, y = load_iris(return_X_y=True)\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=13, test_size=0.2)\n\n# + id=\"yXJ8TbGnTh5V\"\nclassifier.fit(X_train, y_train)\n\ny_preds = classifier.predict(X_test)\n\n# + id=\"UVY6kM53TsL0\" outputId=\"2524a239-48d1-4cd7-85cf-3c1a8b908f4e\" colab={\"base_uri\": \"https://localhost:8080/\"}\naccuracy_score(y_test, y_preds)\n\n# + id=\"sn48bt9SU1r7\" outputId=\"88e97d7b-a0ee-4734-dee3-8640cf6646e4\" colab={\"base_uri\": \"https://localhost:8080/\"}\nprint(classification_report(y_test, y_preds)) # um modelo muito bom (dataset simples)\n\n\n# + [markdown] id=\"M5XRpcPuYbil\"\n# Perceba que uma árvore de decisão possui determinada profundidade, que por padrão do scikit-learn é automática até que se obtenham nós puros. Isto pode ser um fator prejudicial, pois temos então uma grande chance de obter overfitting de dados. \n#\n# Por conta disso, fazemos um procedimento chamado de \"poda\", restrigindo a profundidade máxima da árvore de modo que a mesma aprenda apenas as características gerais dos dados de treino.\n\n# + id=\"x307hUANZbst\"\ndef score_classifier(X_train, X_test, y_train, y_test, max_depth=5):\n classifier = DecisionTreeClassifier(max_depth=max_depth)\n classifier.fit(X_train, y_train)\n return classifier.score(X_test, y_test)\n\n\n# + id=\"MjTBtQ96Y3MD\" outputId=\"ef4fcb23-07bd-4c27-ce56-ca3fa26ebce4\" colab={\"base_uri\": \"https://localhost:8080/\"}\nmax_depths = [2, 5, 7, 9, 11, 13, 15]\n\nfor max_depth in max_depths:\n score = score_classifier(X_train, X_test, y_train, y_test, max_depth)\n print(f'Score: {score} for depht {max_depth}') # best depth -> 7 or 9 -> reduces overfitting\n\n# + [markdown] id=\"2bZ_WsgMbCPg\"\n# ### Regressor com Random Tree\n\n# + id=\"ZgjL934lbFnu\" outputId=\"1729476d-9533-41c5-abb7-9c2a6aba34b4\" colab={\"base_uri\": \"https://localhost:8080/\"}\nX, y = load_boston(return_X_y=True)\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=13, test_size=13)\n\n# + id=\"OZ2mResGcZU9\" outputId=\"6475b17c-bcd4-43ce-a6c6-d207321edd3f\" colab={\"base_uri\": \"https://localhost:8080/\"}\nregressor = DecisionTreeRegressor()\nregressor.fit(X_train, y_train)\n\ny_preds = regressor.predict(X_test)\nmae = mean_absolute_error(y_test, y_preds)\nprint(mae)\n\n\n# + id=\"9mZLP_2tc8r0\"\ndef score_regression(X_train, X_test, y_train, y_test, max_depth=5):\n regressor = DecisionTreeRegressor(max_depth=max_depth)\n regressor.fit(X_train, y_train)\n y_preds = regressor.predict(X_test)\n mae = mean_absolute_error(y_test, y_preds)\n return mae\n\n\n# + id=\"Exzjp-y3dQ2j\" outputId=\"16314a29-f3ae-4ea8-bc22-e1a74e1c01e0\" colab={\"base_uri\": \"https://localhost:8080/\"}\nfor max_depth in max_depths:\n mae = score_regression(X_train, X_test, y_train, y_test, max_depth)\n print(f'Max depth {max_depth} produces MAE {mae}') # -> best max depth: 2 -> reduces underfitting\n\n# + [markdown] id=\"5BjgYcRZxhqu\"\n# ### Feature Importances\n#\n# Podemos utilizar o atributo **feature_importances_** das decision trees para termos noção do quanto cada atributo (coluna do dataset) afeta a predição do modelo. Não é interessante retirar todas as características menos influentes de uma vez, e sim aos poucos, pois muitas características podem possuir certa correlação, podendo afetar mais as predições do modelo após alguma outra ser retirada.\n\n# + id=\"iIlRD9PIxhdX\"\nfrom sklearn.datasets import load_breast_cancer\n\n# + id=\"JZeLXUDAyJTN\"\nX, y = load_breast_cancer(return_X_y=True)\n\n# + id=\"LH44ntA9ybmL\" outputId=\"c8132edc-c958-4b30-cab1-3834c8f01ad7\" colab={\"base_uri\": \"https://localhost:8080/\"}\nmodel = DecisionTreeClassifier()\nmodel.fit(X, y)\n\n# + id=\"3nEAx22kye37\" outputId=\"ffff11cb-be2c-4517-e5ec-1b2b906c4f54\" colab={\"base_uri\": \"https://localhost:8080/\"}\nmodel.feature_importances_\n","repo_name":"williambrunos/Introduction-To-ML","sub_path":"Class_2/Class_2_2/Decision_Trees.ipynb","file_name":"Decision_Trees.ipynb","file_ext":"py","file_size_in_byte":6834,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"21"} +{"seq_id":"72533379254","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport sklearn\nfrom pandas_summary import DataFrameSummary\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn import metrics\n\n# load datasets\ntrain_df = pd.read_csv ( \"../data/TrainingWiDS2021.csv\")\ntest_df = pd.read_csv(\"../data/UnlabeledWiDS2021.csv\")\ndata_dict = pd.read_csv ( \"../data/DataDictionaryWiDS2021.csv\")\n\n# Data shape \nprint (\"Train set: \",train_df.shape)\nprint (\"Test set: \",test_df.shape)\n\ndfs = DataFrameSummary(train_df)\ndfs.summary()\n\n# Top 20 sparse features, mainly labs results \npd.Series(1 - train_df.count() / len(train_df)).sort_values(ascending=False).head(20)\n\n# +\n# Categorical features\n\ncategorical_features=[]\nfor c in train_df.columns:\n col_type = train_df[c].dtype\n if col_type == 'object' or col_type.name == 'category':\n train_df[c] = train_df[c].astype('category')\n categorical_features.append(c)\nprint (categorical_features)\n# -\n\n# Correlation between continuous columns and diabetes column\nmissing = pd.Series(1 - train_df.count() / len(train_df))\n\nkeep_cols = missing[missing<0.7].index.values\n\nreduced_train_df = train_df[keep_cols]\n\nreduced_train_df = reduced_train_df.drop(['Unnamed: 0', 'encounter_id'], axis=1)\n\nreduced_train_df.head()\n\nfloat_feats = list(reduced_train_df.select_dtypes(include='float').columns.values)\nfloat_feats\n\ncorr_cols = float_feats.append('diabetes_mellitus')\n\nfloat_correlations = reduced_train_df[float_feats].corr(method = \"pearson\")\n\nfloat_correlations.style.background_gradient(cmap='Reds')\n\ntop_correlations = float_correlations[['diabetes_mellitus']].sort_values(by='diabetes_mellitus', ascending=False)[0:20]\n\nhigh_float_correlations = top_correlations.index.values\nprint(high_float_correlations)\n\nfloat_correlations[high_float_correlations].loc[high_float_correlations].style.background_gradient(cmap='Reds')\n\n# +\n# basic imputation\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.feature_selection import VarianceThreshold\nfrom sklearn.feature_selection import SelectKBest, chi2, mutual_info_classif\n\n\nnew_features = ['d1_glucose_max'] #'bmi', 'd1_bun_max', 'd1_glucose_min', 'd1_creatinine_max', 'd1_potassium_max', 'age']\n\n\n# -\n\nhigh_float_correlations = high_float_correlations[1::]\n\nX=train_df[high_float_correlations]\ny=train_df['diabetes_mellitus']\n\nX.head()\n\n# +\n# Imputation (fill in with something better later)\nimport numpy as np\nimp_mean = SimpleImputer(missing_values=np.nan, strategy='mean')\nimp_mean.fit(X)\n\nX = imp_mean.transform(X)\nX = pd.DataFrame(X, columns=high_float_correlations)\nX.head()\n# -\n\n#create the train and validation set for cross-validation\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n\n# +\nprint(len(y_test))\nprint(len(y_train))\n\nX_train\n# -\n\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import plot_roc_curve\n\n# +\n# # Create the object for SelectKBest and fit and transform the classification data\n# # k is the number of features you want to select \n# selector = SelectKBest(score_func=mutual_info_classif,k=5).fit(X_train,y_train)\n# X_train_new = selector.transform(X_train)\n\n\n\n\n# +\n\n# # get the column names\n# mask = selector.get_support() #list of booleans\n# new_features = [] # The list of your K best features\n\n# for bool, feature in zip(mask, high_float_correlations):\n# if bool:\n# new_features.append(feature)\n# print(new_features)\n\n# -\n\nnew_features\n\nX_train = X_train[new_features]\nX_test = X_test[new_features]\n\nrfc = RandomForestClassifier(n_estimators=20, random_state=42)\nrfc.fit(X_train, y_train)\nax = plt.gca()\n#rfc_disp2 = plot_roc_curve(rfc, X_train, y_train, ax=ax, alpha=0.8)\nrfc_disp2 = plot_roc_curve(rfc, X_test, y_test, ax=ax, alpha=0.8)\nplt.show()\n\nkaggle_test = test_df[high_float_correlations]\nkaggle_test = imp_mean.transform(kaggle_test)\nkaggle_test = pd.DataFrame(kaggle_test, columns=high_float_correlations)\nkaggle_test = kaggle_test[new_features]\n\npredictions = rfc.predict_proba(kaggle_test)\n\nimport numpy as np\n\nplt.hist(predictions[::,1], density=True)\nplt.title\n\npredictions_train = rfc.predict_proba(X_test)\nplt.hist(predictions_train[::,1],density=True, alpha=0.5, color='r', label='train predictions')\nplt.hist(predictions[::,1], density=True, alpha=0.5, label='kaggle predictions')\nplt.legend()\n\nrfc.classes_\n\n\n","repo_name":"lisamnash/wids_datathon","sub_path":"notebooks/wids_datathon.ipynb","file_name":"wids_datathon.ipynb","file_ext":"py","file_size_in_byte":4466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"21"} +{"seq_id":"26851849310","text":"# +\n#Bibliotecas\n\nimport pandas as pd\nimport numpy as np\n\n\n# +\n#Metodo para separar o STX. retorno em biblioteca\n\ndef tratamento(A):\n STR = A[0:147]\n STX = STR[0:4]\n dia = STR[4:6]\n mes = STR[6:8]\n ano = STR[8:12]\n data = dia +'/'+mes+'/'+ano\n hora = STR[12:14]\n minuto = STR[14:16]\n seg = STR[16:18]\n hora = hora+':'+minuto+':'+seg\n terminal = STR[18:23]\n bomba = STR[23:25]\n produto = STR[25:28]\n vei = STR[28:42]\n rav = STR[42:62]\n odo = STR[62:69]\n hori = STR[69:76]\n volume = STR[76:84]\n operador = STR[84:91]\n rest = STR[91:141].replace(' ','')\n nserie = STR[141:150]\n trat = {'STX':STX ,'DATA':data,'HORA':hora,'TERMINAL':terminal,'BOMBA':bomba,'PRODUTO':produto,'VEICULO':vei,'RAVO':rav,'ODOMETRO':odo,'HORIMETRO':hori,'VOLUME':volume,'OPERADOR':operador,'REST':rest,'NSerie':nserie}\n return trat\n\n\n# +\n#Metodo para pegar os 2 primeiros caracter da string\n\ndef sepa(A):\n p = A[0]\n s = A[1]\n re = A[2:]\n return p,s\n\n\n# +\n#CAminho do arquivo a ser lido\n\ntipo = '.csv'\nfile = 'C:\\GIT\\Python\\Dani\\mercedes'\nfilec = file + tipo \ncolunas = 'Terminal','STX','DATA'\n\n# +\n#Jogando o arquivo para arp\n\narq = pd.read_csv(filec,names=colunas)\n# -\n\narq.STX\n\n# +\n#Criando uma lista com os STX ja tratando\n\nb = []\nfor A in arq.STX:\n b.append(tratamento(A))\n\n# +\n#Transformando uma lista em DataFrame\n\ncol01 = ['STX','DATA','HORA','TERMINAL','BOMBA','PRODUTO','VEICULO','RAVO','ODOMETRO','HORIMETRO','VOLUME','OPERADOR','REST','NSerie']\ndf = pd.DataFrame(b,columns = col01)\n\n# +\n#Gerando lista de infos de veiculos\n\nc = []\nfor X in df.VEICULO:\n c.append(X)\n# -\n\n#Criando um DataFrame com a lista de booleando\nse = pd.DataFrame(c)\n\nse01 = se.drop_duplicates()\n\n# +\n#Salvando a planilha em Excel\n\ntipo1 = '.xlsx'\nfile1 = 'C:\\GIT\\Python\\Dani\\Pronto\\mercedesFinal'\nfilef = file1 + tipo1\nse01.to_excel(filef)\n# -\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"DGO911/Python","sub_path":"Trata_STX_extrai_usuarios.ipynb","file_name":"Trata_STX_extrai_usuarios.ipynb","file_ext":"py","file_size_in_byte":1899,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"21"} +{"seq_id":"24851974187","text":"# # Proyecto Forbes 2000 - 2021 \n# ## Manipulación y transformación de datos con Pandas y Numpy\n# 01.07.23\n#\n# **Pandas**: paquete enfocado en la manipulación y análisis de datos. Está construido sobre Numpy, requiero poco código para manipular datos. Soporta múltiples formatos de atchivos. \n#\n# Pandas trabaja don cos objetos que derivan de los array de Numpy:\n# 1. Pandas Series: array unidimensional de np o vector.\n# 2. DataFrame: estructura principal de Pandas (Matriz).\n\n# +\n# Importemos librerías de trabajo\n# pip list : me muestra qué paquetes tengo instalados\n# pip install : instalo los paquete que desee\n\nimport os #Para directorio de trabajo\nimport numpy as np #Métodos numéricos y arrays\nimport pandas as pd #Manipulación de DF\n\n# +\n# Pandas series = vector\n\nvector = pd.Series(['Julian','Maria','Pedro','Natalia'], index= [3,2,1,4])\nprint(vector)\nprint(vector[1])\nprint(type(vector))\n\n# +\n# Accedo a el dato con el indexado establecido\nprint(vector[1])\n\n# Accedo a varios datos con el indexado\nprint(vector[[1,4,3]])\n\n# +\n# Para crear un data frame, podemos hacer uso de diccionario\n\ndic = {'Nombres': ['Julian','Maria','Pedro','Natalia'],\n 'Edad': [28,30,25,22],\n 'Altura': [173,165,178,170]}\n\nprint(dic['Nombres'])\n\ndf_flia = pd.DataFrame(dic)\n# -\n\nprint(df_flia)\n\n# +\n# Filtros o slicing\n\ndf_flia[1:3] # Filas de la 1 a la 3\ndf_flia[:] # Todo el DF\ndf_flia['Edad'] # Edad\ndf_flia[2:3]['Edad'] #Edad de Pedro\n# -\n\n# ## Proyecto Forbes\n#\n# ### Fortune Global 2000 Companies (2021)\n# Fortune Global 2000 Companies with Sales, Profits, Assets, Market Value\n#\n# List of top 2000 companies with their total sales, total profits, total assets, and total market value\n#\n# Since 2003, Forbes’ Global 2000 list has measured the world’s largest public companies in terms of four equally weighted metrics: assets, market value, sales and profits. Last year’s edition offered a glimpse into the early economic implications of the Covid-19 pandemic. Now, we see the results over 12 months of market turmoil and unfathomable human loss.\n#\n# ### Features\n#\n# - ranking : Ranking\n# - Name : Name de la compania\n# - Country : Country de procedencia de la compania\n# - Sales : Sales\n# - Profits : Profits\n# - Assets : Assets\n# - Market_value : Market_value de la compania en el mercado\n#\n#\n# *Nota: cifras en millones de dolares\n#\n#\n# Source: https://www.forbes.com/lists/global2000/#7e9e39675ac0\n\n# +\n# Establezcamos directorio de trabajo\n\nos.chdir('C:/Users/USUARIO/Desktop/Trabajo/Iberoamericana/Cursos/IA')\n# -\n\nos.getcwd() #Muestreme el directorio de trabajo\nos.listdir() #Archivos en el ditrectorio de trabajo\n\n# +\n# Importar base de datos\n\nforbes21 = pd.read_csv('Data set/Forbes 2000 2021.csv',encoding= 'latin-1',sep=';')\n# -\n\nforbes21\n\n# Para ver la FORMA del DF\nforbes21.shape # (Fila,columna)\n\n# +\n### Data cleaning \n\n# Qué variables tengo\n\nforbes21.columns\n# -\n\n#Cambiar nombre de variables\nforbes21.columns = ['Rank','Company','Country','Sales','Profits','Assets','Market_value']\nforbes21.columns\n\nforbes21.head(n=10) # Top 10 de las empresas de Forbes 21\n#forbes21.tail(n=9) #Las últimas 5\n\nforbes21.info()\n\nforbes21.isna().any()\n\n# +\n# Modifiquemos el formato de los datos (Coerción de datos)\n\nforbes21 = forbes21.replace(',','',regex= True) # regex: expresión regular\nforbes21.head()\n# -\n\nforbes21 = forbes21.replace('\\$','',regex=True) #La expresión regular de $ es con \\$\nforbes21.head()\n\n# +\n# Acceder a filas y columnas\n# Indexing and slicing\n\n#Cómo acceder indicando filas con indexación\nforbes21[:] #Coja todas las filas\nforbes21[999:1010]\nforbes21[1900:]\n\n# +\n#Acceder a columnas\n\nforbes21['Sales']\nforbes21[['Company','Country','Sales']][100:111]\n\n# +\n# Acceder a filas y columnas\n\nforbes21[['Company','Country','Sales']][100:111]\n\n# +\n# Método loc de pandas: df.loc[filas,columnas(labels)]\n\nforbes21.loc[:] #Me muestra todo el df\nforbes21.loc[10:20,['Company','Sales']]\n# -\n\n# Función iloc: df.iloc[filas,columnas] por indices o int\nforbes21.iloc[1,3] #fila 1, columna 3\nforbes21.iloc[:5,[2,4,6]]\nforbes21.iloc[:2,2:]\n\n# +\n#Coercionar datos\n\nforbes21.iloc[:,3:].astype(float) # ¿Cuál es el error?\n\n# +\n#Tenemos un caracter extraño que no puede ser coercionado a float: '-'\n\nforbes21.isin(['-']) # Método de Pandas\n# -\n\nforbes21.isin(['-']).any()\n#forbes21.isin(['-']).any().any()\n\n# +\n# Remplazamos el '-' por NaN que es el missing de Pandas\n\nforbes21['Assets'] = forbes21['Assets'].replace('-',float('nan')) \n# -\n\nforbes21.isin(['-']).any()\n\nforbes21.isna().any()\n\n# Coercionar los datos de str a float\nforbes21.iloc[:,3:] = forbes21.iloc[:,3:].astype(float) \n\nforbes21['Sales'].count(), forbes21['Sales'].mean(), forbes21['Sales'].std(), forbes21['Sales'].var() #Varianza\n\n# +\n# ¿Cuántos datos vacias hay?\n\nforbes21.isna().sum()\n\n# +\n# ¿A qué porcentaje del total de mis datos corresponden las observaciones vacias?\n\n100*forbes21.isna().sum().sum()/forbes21.shape[0] # Vacios sobre numero de registros\n\n# Si los vacios representan menos del 1%, podemos proceder a eliminarlos\n\n# +\n#Dos caminos posibles: eliminar o imputar datos\n\n# Eliminación de datos\n#forbes21 = forbes21.dropna() \n#forbes21.dropna(inplace= True) \n# -\n\n#Ejemplos de groupby\nforbes21.groupby('Country').size()\n\nforbes21[\"Assets\"].fillna(forbes21.groupby('Country')[\"Assets\"].transform(lambda x : x.mean()), inplace=True)\nforbes21[forbes21['Country'] == 'Greece']\n\nforbes21.isna().sum()\n\n# ### Análisis exploratorio de datos [EDA]\n#\n# De explorar y de resumir los datos para poder sacar información relevante y consistente.\n# 1. Métodos tabulares\n# 2. Métodos numéricos\n# 3. Análisis gráfico\n\n# +\n# Cuáles empresas son el top 5 del ranking de forbes 2000 2021\n\nforbes21.head(n=5)['Company']\n\n# +\n#Percentiles\n\nprint(np.percentile(forbes21['Profits'],[25,50,75]))\n\nprint(forbes21['Profits'].quantile([0.25,0.5,0.75]))\n\n# +\n# Valorar el 1% de las empresas con mas ganancias en el mundo\n\np99p = np.percentile(forbes21['Profits'],99)\nprint(p99p)\n\n\n# +\n# Filtrar de mi DF usando la condición de 'Profits' > p99p\n\nforbes21[forbes21['Profits'] > p99p][['Company','Country','Profits']]\n\n# +\n# 1% de las empresas con mayor valor del mercado\n\np99mv = forbes21['Market_value'].quantile(0.99)\nprint(p99mv)\n# -\n\nforbes21[forbes21['Market_value']>p99mv][['Company','Country','Market_value']]\n\n# +\n# Del 1% mas alto en valor de mercado, cuáles están en el 1% con mas ganancias\n# Operadores lógicos: y &, o |\n\nforbes21[(forbes21['Market_value']>p99mv) & (forbes21['Profits']>p99p)][['Company','Country','Market_value','Profits']]\n# -\n\nforbes21[(forbes21['Country']== 'Colombia') & (forbes21['Profits']> 500)]\n\nforbes21[(forbes21['Country']== 'Argentina')]\n\n# +\n# Tablas de frecuencia\n\ntable_country = 100*forbes21['Country'].value_counts()/forbes21['Country'].count()\ntable_country.head(10)\n# -\n\nejemplo = list(range(10))\nejemplo = pd.Series(ejemplo)\ncomparar = [5,6,12]\nprint(ejemplo)\nprint(comparar)\n\n\n# +\n#Comparadores lógicos: ==, !=, >, <, isin\n#Operadores lógicos: & |\n\nejemplo.isin(comparar) \n# -\n\nsuda = ['Argentina','Bolivia','Brazil','Chile','Colombia','Ecuador','Paraguay','Peru','Uruguay','Venezuela']\n\nf_suda = forbes21[forbes21['Country'].isin(suda)]\n\nEUROPE = ['Albania', 'Germany', 'Andorra', 'Armenia', 'Austria', 'Azerbaijan', 'Belgium', 'Belarus', 'Bosnia and Herzegovina', 'Bulgaria', 'Cyprus', 'Croatia', 'Denmark', 'Slovakia', 'Slovenia', 'Spain', 'Estonia', 'Finland', 'France', 'Georgia', 'Greece', 'Hungary', 'Ireland', 'Iceland', 'Italy', 'Kazakhstan', 'Kosovo', 'Latvia', 'Liechtenstein', 'Lithuania', 'Luxembourg', 'North Macedonia', 'Malta', 'Moldova', 'Monaco', 'Montenegro', 'Norway', 'Netherlands', 'Poland', 'Portugal', 'United Kingdom', 'Czech Republic', 'Romania', 'Russia', 'San Marino', 'Serbia', 'Sweden', 'Switzerland', 'Ukraine', 'Vatican City']\n\nf_europe = forbes21[forbes21['Country'].isin(EUROPE)]\n\nf_europe['Country'].value_counts()\n\nf_suda['Country'].value_counts()\n\n# +\n# Métodos numéricos\n\n# Medidas de centralidad: media\n\nprint('Media de ventas:', np.mean(forbes21['Sales']))\nprint('Media de ventas en empresas sudamericanas:',np.mean(f_suda['Sales']))\nprint('Media de ventas en empresas europa:',np.mean(f_europe['Sales']))\n\n# +\n# Medidas de centralidad: mediana\n\nprint('Mediana de ventas:', np.median(forbes21['Sales']))\nprint('Mediana de ventas en empresas sudamericanas:',np.median(f_suda['Sales']))\nprint('Mediana de ventas en empresas europa:',np.median(f_europe['Sales']))\n# -\n\nforbes21.iloc[:,3:].apply(func=np.mean,axis = 0) #0 para columnas, 1 para filas\n\nforbes21.iloc[:,3:].apply(func=np.median,axis = 0)\n\nforbes21.iloc[:,3:].apply(func=np.std,axis = 0)\n\n\ndef cv(data):\n media = np.mean(data)\n sd = np.std(data)\n coef = (sd/media)*100\n return coef\n\n\ncv(forbes21['Sales'])\n\nforbes21.iloc[:,3:].apply(func=cv,axis = 0)\n\n# +\n# outliears: datos atípicos\n\nage = [20,22,19,21,69]\nnp.mean(age)\nnp.median(age)\n# -\n\n# ### Librería gráfica Matplotlib\n#\n# Es una biblioteca de visualización de datos multiplataforma basa en los arrays de numpy\n# - import matplotlib as mpl\n# - import matplotlib.pyplot as plt\n\n#pip install matplotlib\nimport matplotlib.pyplot as plt\n\n# +\n# Bar plot\ntable_suda=f_suda['Country'].value_counts()\ntable_suda\n\nplt.bar(table_suda.index,table_suda.values, color = 'purple', alpha = 0.9, edgecolor = 'white') #Crea el gráfico de barras\nplt.title('Frecuencia de empresas sudamericanas')\nplt.xlabel('Paises sudamericanos')\nplt.ylabel('Frecuencia absoluta')\nplt.grid(color = 'gray',alpha = 0.3, linestyle = 'solid')\n\nplt.show() #Imprime el gráfico\n\n# +\ntable_europe = f_europe['Country'].value_counts()\n\n\nplt.bar(table_europe.index,table_europe.values, color = 'orange', alpha = .9, edgecolor = 'white') #Crea el gráfico de barras\nplt.title('Frecuencia de empresas sudamericanas')\nplt.xlabel('Paises sudamericanos')\nplt.ylabel('Frecuencia absoluta')\nplt.grid(color = 'gray',alpha = 0.3, linestyle = 'solid')\n\nplt.show() #Imprime el gráfico\n\n# +\n# pie chart\n\nplt.pie(table_suda.values,labels=table_suda.index)\nplt.title('Segmento de empresas por paises')\n\nplt.show()\n\n# +\n# Histogramas\n\nplt.hist(forbes21[\"Sales\"], color='purple',edgecolor = 'black')\nplt.grid(color='gray', linestyle='solid', alpha = 0.3)\n\nplt.show()\n\n# +\nplt.hist(forbes21[\"Profits\"], color='orange',edgecolor = 'black')\nplt.grid(color='gray', linestyle='solid', alpha = 0.3)\n\nplt.show()\n\n# +\n# Crear histograma para la columna \"Sales\"\nplt.hist(forbes21['Sales'], alpha=0.5, label='Sales')\n\n# Crear histograma para la columna \"Profits\"\nplt.hist(forbes21['Profits'], alpha=0.5, label='Profits')\n\n# Agregar leyenda\nplt.legend()\n\n# Configurar etiquetas y título\nplt.xlabel('Valor')\nplt.ylabel('Frecuencia')\nplt.title('Histograma de Sales y Profits')\nplt.grid(color='gray', linestyle='solid', alpha = 0.3)\n\n\n# Mostrar el gráfico\nplt.show()\n","repo_name":"julihdez36/Funda_ciencia_dat","sub_path":"3. PandasForbes.ipynb","file_name":"3. PandasForbes.ipynb","file_ext":"py","file_size_in_byte":10858,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"21"} +{"seq_id":"19405762527","text":"# + id=\"Ml54yDaeeZLb\"\nimport os\n\nimport pandas as pd\nimport numpy as np\nimport math\nimport itertools\n\nimport h5py\n\nfrom sklearn import preprocessing\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.model_selection import train_test_split\n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.utils import to_categorical\n\nfrom keras.layers import Dense\nfrom keras.models import Sequential\nfrom keras.optimizers import Adam\n\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"pDdFQzQdfvn1\" outputId=\"1f49e94a-f38b-4653-b035-970e369bd572\"\n# from google.colab import drive\n# drive.mount('/content/gdrive')\n\n# + id=\"2oib_xrMc4zE\"\nIMAGE_SIZE = 256\n# IMAGE_DIRECTORY = './gdrive/MyDrive/Jupyter Programs/Datasets/'\nIMAGE_DIRECTORY = './'\n\n# + id=\"lVTVMbq7c6ZU\"\nfilename = 'train_catvnoncat.h5'\nf = h5py.File(IMAGE_DIRECTORY+filename, 'r')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"l0LI7ucLdNLY\" outputId=\"c5ea9d0a-6200-4b6c-898f-17288fe63b81\"\nlist(f.keys())\n\n# + id=\"IDNegLEpceZ_\"\ndata_train = list(f['train_set_x'])\ndata_label = list(f['train_set_y'])\nprint(len(data_train))\n\n# + id=\"On-tcPX2cl_v\"\nX_tr=np.array(data_train)\ny_tr= np.array(data_label)\n\n# + id=\"jwIYIIrm3MRJ\"\nfilename = 'test_catvnoncat.h5'\nf = h5py.File(IMAGE_DIRECTORY+filename, 'r')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"HS5l5es03UL_\" outputId=\"e1a512bc-d5bc-4387-ff5a-3e6ad55c1433\"\nlist(f.keys())\n\n# + id=\"JPwXmeud3VTJ\"\ndata_test = list(f['test_set_x'])\ndata_label_test = list(f['test_set_y'])\nprint(len(data_test))\n\n# + id=\"JjvHBdxY3nKC\"\nX_test=np.array(data_test)\ny_test= np.array(data_label_test)\n\n# + [markdown] id=\"hpD3hlx8dJct\"\n#\n# # Mostrando alguns exemplos de imagens\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 834} id=\"NyGbrdvLdeN-\" outputId=\"707ea0e3-582f-4ab1-eb12-b32489c3b2af\"\nprint(data_train[1].shape)\nn=20\nplt.figure(figsize=(15, 15))\nfor i in range(n):\n ax = plt.subplot(4, 5, i + 1)\n plt.imshow(data_train[i+10])\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n\nplt.show()\n\n# + [markdown] id=\"moJRsL3zfA96\"\n# # Visualizando se as classes estao razoavelmente balanceadas\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 335} id=\"JY46gmusdo_Q\" outputId=\"5895f372-f2ff-473a-b9a7-bc8837713957\"\nsns.set_style('darkgrid')\nsns.countplot(y_tr,palette='twilight')\n\n# + [markdown] id=\"IBU3yorygSgB\"\n# # Separando os dados em Treinamento e Validacao\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"1GF7En2ngdlZ\" outputId=\"65b6286c-c2ce-4b08-c3f6-2a83fa6a7d4e\"\nX_train,X_val,Y_train,Y_val = train_test_split(X_tr,y_tr,test_size = 0.1)\nprint('Shape of train set feature',X_train.shape)\nprint('Shape of validation set feature',X_val.shape)\nprint('Shape of train set label',Y_train.shape)\nprint('Shape of validation set label',Y_val.shape)\n\nnum_classes=2\ninput_shape = (64,64,3)\n\nY_train = to_categorical(Y_train, num_classes)\nY_val = to_categorical(Y_val, num_classes)\nY_test = to_categorical(y_test, num_classes)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"B4YBYhwAg44N\" outputId=\"b07fbebf-25d7-4653-d17a-ca30effdbd7e\"\nprint(input_shape)\nmodel = keras.Sequential(\n [\n keras.Input(shape=input_shape),\n layers.Conv2D(32, kernel_size=(3, 3), activation=\"selu\"),\n layers.MaxPooling2D(pool_size=(2, 2)),\n layers.Conv2D(64, kernel_size=(3, 3), activation=\"selu\"),\n layers.MaxPooling2D(pool_size=(2, 2)),\n layers.Conv2D(128, kernel_size=(3, 3), activation=\"selu\"),\n layers.MaxPooling2D(pool_size=(2, 2)),\n layers.Conv2D(64, kernel_size=(3, 3), activation=\"selu\"),\n layers.MaxPooling2D(pool_size=(2, 2)),\n layers.Flatten(),\n layers.Dropout(0.5),\n layers.Dense(num_classes, activation=\"sigmoid\"),\n ]\n)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"QElacAktvfNy\" outputId=\"2d6c1f8e-6806-4469-eec1-49f6130ccb16\"\nlr=0.001\n\n# Compile the model.\nmodel.compile(\n optimizer=Adam(learning_rate=lr),\n loss='categorical_crossentropy',\n metrics=['accuracy'],\n)\nmodel.summary()\n# from keras.utils.vis_utils import plot_model\n# plot_model(model, to_file='model_plot.png', show_shapes=True, show_layer_names=True)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"89OL2Y1KwUIo\" outputId=\"4462947e-9d0e-40bc-b617-db7fcc004c66\"\nmodel.fit(X_train, Y_train,validation_data = (X_val, Y_val),epochs=150, batch_size=64)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 545} id=\"4jf7nXlgypjp\" outputId=\"11266d45-3f54-4998-bf05-397f035cd613\"\nacc = model.history.history['accuracy']\nval_acc = model.history.history['val_accuracy']\nloss = model.history.history['loss']\nval_loss = model.history.history['val_loss']\nepochs = range(1, len(acc) + 1)\n\nplt.plot(epochs, acc, 'b', label= 'Training accuracy')\nplt.plot(epochs, val_acc, 'r', label= 'Validation accuracy')\nplt.title('Training and Validation accuracy')\nplt.legend()\n\nplt.figure()\nplt.plot(epochs, loss, 'b', label= 'Training loss')\nplt.plot(epochs, val_loss, 'r', label= 'Validation loss')\nplt.title('Training and Validation loss')\nplt.legend()\n\nplt.show()\n\n# + id=\"2UHJwCzHwvgi\"\nTrainPredictions = model.predict(X_train)\nTrainPredictions = np.argmax(TrainPredictions, axis=1)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 328} id=\"485zb_RGx4VU\" outputId=\"727108f4-3e87-40e4-9f70-22c562a3063e\"\ntrain_labels = np.argmax(Y_train, axis=1)\nconf = confusion_matrix(train_labels, TrainPredictions)\n\nclasses = [0, 1]\n# plot confusion matrix\nplt.imshow(conf, interpolation='nearest', cmap=plt.cm.Greens)\nplt.title(\"Train Confusion Matrix\")\nplt.colorbar()\ntick_marks = np.arange(len(classes))\nplt.xticks(tick_marks, classes)\nplt.yticks(tick_marks, classes)\n\nfmt = 'd'\nthresh = conf.max() / 2.\nfor i, j in itertools.product(range(conf.shape[0]), range(conf.shape[1])):\n plt.text(j, i, format(conf[i, j], fmt),\n horizontalalignment=\"center\",\n color=\"white\" if conf[i, j] > thresh else \"black\")\n\nplt.tight_layout()\nplt.ylabel('True label')\nplt.xlabel('Predicted label')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"6tUinoq52RNK\" outputId=\"a96e5f4e-b6ef-4b08-eb89-fc9b5821eea3\"\nfrom sklearn.metrics import accuracy_score\nprint('\\nAccuracy: {:.4f}\\n'.format(accuracy_score(train_labels, TrainPredictions)))\n\n# + id=\"k1mZW98c2smX\"\nTestPredictions = model.predict(X_test)\nTestPredictions = np.argmax(TestPredictions, axis=1)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 328} id=\"02eZIWfo4XTB\" outputId=\"6cef5d8c-1caf-4a5c-e97c-15c2d794edd6\"\ntest_labels = np.argmax(Y_test, axis=1)\nconf = confusion_matrix(test_labels, TestPredictions)\n\nclasses = [0, 1]\n# plot confusion matrix\nplt.imshow(conf, interpolation='nearest', cmap=plt.cm.Greens)\nplt.title(\"Test Confusion Matrix\")\nplt.colorbar()\ntick_marks = np.arange(len(classes))\nplt.xticks(tick_marks, classes)\nplt.yticks(tick_marks, classes)\n\nfmt = 'd'\nthresh = conf.max() / 2.\nfor i, j in itertools.product(range(conf.shape[0]), range(conf.shape[1])):\n plt.text(j, i, format(conf[i, j], fmt),\n horizontalalignment=\"center\",\n color=\"white\" if conf[i, j] > thresh else \"black\")\n\nplt.tight_layout()\nplt.ylabel('True label')\nplt.xlabel('Predicted label')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"j5G233so4rZ7\" outputId=\"3a9bd16f-7567-47aa-b4c0-4eff43ff9dad\"\nprint('\\nAccuracy: {:.4f}\\n'.format(accuracy_score(test_labels, TestPredictions)))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"WivfHF9K0Q8_\" outputId=\"aa9f322e-3bb5-4d23-b348-0bb8947b69c2\"\nprint(X_test[1].shape)\nx = np.expand_dims(X_test[1], axis=0)\nprint(x.shape)\nPredictions = model.predict(x)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 1000} id=\"CFSXzTy75j74\" outputId=\"5558afcf-3105-46e8-a81d-5930ae4d17fa\"\nn=50\nfor i in range(n):\n #ax = plt.subplot(4, 5, i + 1)\n ax = plt.subplot()\n plt.imshow(data_test[i])\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n plt.show()\n\n Predictions = model.predict(np.expand_dims(X_test[i], axis=0))\n Predictions = np.argmax(Predictions, axis=1)\n if Predictions==0:\n print('NAO E UM GATO')\n else:\n print('E UM GATO')\n# input()\n\n\n","repo_name":"gudeh/AIconexionist21.1","sub_path":"Exercicio6/.ipynb_checkpoints/Exercicio_Cat_vs_Non_Cat-checkpoint.ipynb","file_name":"Exercicio_Cat_vs_Non_Cat-checkpoint.ipynb","file_ext":"py","file_size_in_byte":8306,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"21"} +{"seq_id":"27276855857","text":"# +\nimport pandas as pd\nimport numpy as np\nfrom pdb import set_trace\nfrom sklearn.metrics import confusion_matrix\nimport matplotlib.pyplot as plt\nimport os\nfrom collections import defaultdict\n\nalgos = ['AdaBoost','GradientBoost','RandomForest']\nvaluation = ['mean','dollar_neutral_refreshed','market_cap']\ninterpolation = ['linear','trend']\nfilterStocks = ['no_rule','probability']\ntr_cost = [True,False]\n\ndef feature_imp_dict(df, input_dict):\n for date in df.index:\n tmp_top_10_features = df.loc[date].sort_values(ascending=False).head(10).keys()\n for tmp_feature in tmp_top_10_features:\n input_dict[tmp_feature]=input_dict[tmp_feature]+1\n\n sorted_input_dict = {k: v for k, v in sorted(input_dict.items(), key=lambda item: item[1])}\n for key in sorted_input_dict.keys():\n sorted_input_dict[key] = 100*sorted_input_dict[key]/df.index.shape[0]\n return sorted_input_dict\n\ndef feature_imp_plots(df_adaboost, df_gradientboost, df_randomforest, interp):\n\n color_scheme = {'AdaBoost': 'red','GradientBoost': 'green', 'RandomForest': 'blue'}\n feature_names = ['bm', 'pe_exi', 'pe_op_dil', 'evm', 'debt_at', 'de_ratio', 'liquidity',\n 'roe', 'roa', 'roce', 'DIVYIELD', 'dpr', 'intcov_ratio', 'debt_ebitda',\n 'rect_turn', 'pay_turn', 'at_turn', 'inv_turn', 'cash_ratio',\n 'quick_ratio', 'curr_ratio', 'cash_conversion', '1M_vol', '3M_vol',\n '3M_mom', '12M_mom', 'b_mkt', 'b_smb', 'b_hml', 'b_umd']\n df_adaboost.columns = feature_names\n df_gradientboost.columns = feature_names\n df_randomforest.columns = feature_names\n initial_dict_adaboost = dict.fromkeys(feature_names, 0)\n initial_dict_gradientboost = dict.fromkeys(feature_names, 0)\n initial_dict_randomforest = dict.fromkeys(feature_names, 0)\n adaboost_dict = feature_imp_dict(df_adaboost,initial_dict_adaboost)\n gradientboost_dict = feature_imp_dict(df_gradientboost,initial_dict_gradientboost)\n randomforest_dict = feature_imp_dict(df_randomforest,initial_dict_randomforest)\n\n fig, axs = plt.subplots(3, 1,figsize=(10,15))\n axs[0].bar(randomforest_dict.keys(),randomforest_dict.values(), color = 'red')\n axs[0].set_title('Random Forest')\n axs[1].bar(adaboost_dict.keys(),adaboost_dict.values(), color = 'green')\n axs[1].set_title('AdaBoost')\n axs[2].bar(gradientboost_dict.keys(),gradientboost_dict.values(), color = 'blue')\n axs[2].set_title('GradientBoost')\n\n for ax in axs.flat:\n ax.tick_params(labelrotation=90)\n ax.set(xlabel='Features', ylabel='Feature Importance %')\n \n fig.tight_layout()\n \n fig.savefig(interp+' Feature Importance.png')\n\n return adaboost_dict,gradientboost_dict,randomforest_dict\n\n\n# -\n\ndef timeseriesplot(df1,df2,df3,features1,features2,features3):\n tmpdf1 = df1[features1]\n tmpdf2 = df2[features2]\n tmpdf3 = df3[features3]\n fig, axs = plt.subplots(3, 1,figsize=(10,20))\n axs[0].plot(pd.to_datetime(tmpdf1.index), tmpdf1)\n axs[0].legend(tmpdf1.columns,fontsize = 10)\n axs[0].set_title('AdaBoost')\n axs[1].plot(pd.to_datetime(tmpdf2.index),tmpdf2)\n axs[1].legend(tmpdf2.columns, fontsize = 10)\n axs[1].set_title('GradientBoost')\n axs[2].plot(pd.to_datetime(tmpdf3.index),tmpdf3)\n axs[2].legend(tmpdf3.columns, fontsize = 10)\n axs[2].set_title('Random Forest')\n \n for ax in axs.flat:\n ax.tick_params('x',width = 6,labelrotation=90)\n ax.set(xlabel='Date', ylabel='Feature Importance')\n\n fig.tight_layout()\n fig.savefig('Time series of Feature Importance.png')\n return\n\n\nfor interp in interpolation:\n for algo in algos:\n try:\n test_file_name = './Results/Lagged/'+algo+'_market_cap_no_rule_'+interp+'_feature_importance_lagged.csv'\n test = pd.read_csv(test_file_name, index_col=0)\n except:\n test_file_name = './Results/Lagged/'+algo + '_market_cap_no_rule_True_' + interp + '_feature_importance_lagged.csv'\n test = pd.read_csv(test_file_name, index_col=0)\n if algo == 'AdaBoost':\n adaboost_df = pd.read_csv(test_file_name, index_col=0)\n elif algo == 'GradientBoost':\n gradientboost_df = pd.read_csv(test_file_name, index_col=0)\n elif algo == 'RandomForest':\n randomforest_df = pd.read_csv(test_file_name, index_col=0)\n dict1, dict2, dict3 = feature_imp_plots(adaboost_df,gradientboost_df,randomforest_df,interp)\n\nfor interp in ['Trend']:\n for algo in algos:\n try:\n test_file_name = './Results/Lagged/'+algo+'_market_cap_no_rule_True_'+interp+'_feature_importance_lagged.csv'\n except:\n test_file_name = './Results/Lagged/'+algo + '_market_cap_no_rule_' + interp + '_feature_importance_lagged.csv'\n if algo == 'AdaBoost':\n adaboost_df = pd.read_csv(test_file_name, index_col=0)\n elif algo == 'GradientBoost':\n gradientboost_df = pd.read_csv(test_file_name, index_col=0)\n elif algo == 'RandomForest':\n randomforest_df = pd.read_csv(test_file_name, index_col=0)\n dict1, dict2, dict3 = feature_imp_plots(adaboost_df,gradientboost_df,randomforest_df,interp)\n\nadaboost_df\n\nadaboost_top10 = list(dict1.keys())[-7:]\ngradientboost_top10 = list(dict2.keys())[-7:]\nrandomforest_top10 = list(dict3.keys())[-7:]\ntimeseriesplot(adaboost_df,gradientboost_df,randomforest_df,adaboost_top10,gradientboost_top10,randomforest_top10)\n\ntest_file_name\n\n# +\ntry:\n f1 = './Results/Unlagged/AdaBoost_market_cap_no_rule_Trend_feature_importance.csv'\n test_df = pd.read_csv(f1,index_col=0)\nexcept:\n f1 = './Results/Unlagged/AdaBoost_market_cap_no_rule__True_Trend_feature_importance.csv'\n test_df = pd.read_csv(f1, index_col=0)\n \nf2 = './Results/Unlagged/GradientBoost_market_cap_no_rule_Trend_feature_importance.csv' \nf3 = './Results/Unlagged/RandomForest_market_cap_no_rule_Trend_feature_importance.csv' \nf4 = './Results/Unlagged/AdaBoost_market_cap_no_rule_Trend_feature_importance.csv' \nf5 = './Results/Unlagged/GradientBoost_market_cap_no_rule_Trend_feature_importance.csv' \nf6 = './Results/Unlagged/RandomForest_market_cap_no_rule_Trend_feature_importance.csv' \n \n \nfiles = [f1,f2,f3,f4,f5,f6]\nfor file in files:\n print(file)\n test_series = pd.read_csv(file, index_col = 0)['Long_Only']\n input_series = np.cumprod(1 + test_series.values)\n input_series = np.append([1.0],input_series)\n \n \n \n \n# -\n\ndef maximum_drawdown(input_series):\n input_series = np.cumprod(1 + input_series.values)\n input_series = np.append([1.0],input_series)\n xs = input_series\n i = np.argmax(np.maximum.accumulate(xs) - xs) # end of the period\n j = np.argmax(xs[:i]) # start of period\n plt.plot(xs)\n plt.plot([i, j], [xs[i], xs[j]], 'o', color='Red', markersize=10)\n plt.show()\n return (xs[i]-xs[j])\n\n\ndef max_drawdown(series):\n input_series = np.cumprod(1 + series.values)\n input_series = np.append([1.0],input_series)\n min_now, max_now = input_series[0], input_series[0]\n start_period, end_period = pd.to_datetime('2000-12-31').date(), pd.to_datetime('2000-12-31').date()\n max_period, min_period = pd.to_datetime('2000-12-31').date(), pd.to_datetime('2000-12-31').date()\n drawdown = 0\n for i in range(1,len(input_series)):\n if input_series[i] > max_now:\n max_now = input_series[i]\n min_now = input_series[i]\n max_period = series.index[i-1]\n elif input_series[i] < min_now:\n min_now = input_series[i]\n min_period = series.index[i-1]\n if float((max_now-min_now)/max_now) > drawdown:\n drawdown = float((max_now-min_now)/max_now)\n start_period = max_period\n end_period = min_period\n #print(start_period, test_series.index[i-1], float(drawdown/max_now))\n #print(start_period, end_period, float(drawdown))\n print(start_period, end_period, float(drawdown))\n\n\nalgos = ['AdaBoost','GradientBoost','RandomForest']\nvaluation = ['mean','dollar_neutral_refreshed','market_cap']\ninterpolation = ['linear','trend']\nfilterStocks = ['no_rule','probability']\ntr_cost = [True,False]\nfor tr in tr_cost:\n for interp in interpolation:\n for val in valuation:\n #adaboost\n try:\n f_a_n = './Results/Unlagged/AdaBoost_' + val+'_no_rule_' + str(tr) + '_' + interp + '_returns.csv'\n a_n = pd.read_csv(f_a_n,index_col=0)['Long_Only']\n except:\n f_a_n = './Results/Unlagged/AdaBoost_' + val+'_no_rule_' + interp + '_returns.csv'\n a_n = pd.read_csv(f_a_n,index_col=0)['Long_Only']\n print(f_a_n)\n print(maximum_drawdown(a_n))\n try:\n f_a_p = './Results/Unlagged/AdaBoost_' + val+'_probability_' + str(tr) + '_' + interp + '_returns.csv'\n a_p = pd.read_csv(f_a_p,index_col=0)['Long_Only']\n except:\n f_a_p = './Results/Unlagged/AdaBoost_' + val+'_probability_' + interp + '_returns.csv'\n a_p = pd.read_csv(f_a_p,index_col=0)['Long_Only']\n print(f_a_p)\n print(maximum_drawdown(a_p))\n #gradientboost\n try:\n f_g_n = './Results/Unlagged/GradientBoost_' + val+'_no_rule_' + str(tr) + '_' + interp + '_returns.csv'\n g_n = pd.read_csv(f_g_n,index_col=0)['Long_Only']\n except:\n f_g_n = './Results/Unlagged/GradientBoost_' + val+'_no_rule_' + interp + '_returns.csv'\n g_n = pd.read_csv(f_g_n,index_col=0)['Long_Only']\n print(f_g_n)\n print(maximum_drawdown(g_n)) \n try:\n f_g_p = './Results/Unlagged/GradientBoost_' + val+'_probability_' + str(tr) + '_' + interp + '_returns.csv'\n g_p = pd.read_csv(f_g_p,index_col=0)['Long_Only']\n except:\n f_g_p = './Results/Unlagged/GradientBoost_' + val+'_probability_' + interp + '_returns.csv'\n g_p = pd.read_csv(f_g_p,index_col=0)['Long_Only']\n print(f_g_p)\n print(maximum_drawdown(g_p)) \n #randomforest\n try:\n f_r_n = './Results/Unlagged/RandomForest_' + val+'_no_rule_' + str(tr) + '_' + interp + '_returns.csv'\n r_n = pd.read_csv(f_r_n,index_col=0)['Long_Only']\n except:\n f_r_n = './Results/Unlagged/RandomForest_' + val+'_no_rule_' + interp + '_returns.csv'\n r_n = pd.read_csv(f_r_n,index_col=0)['Long_Only']\n print(f_r_n)\n print(maximum_drawdown(r_n))\n try:\n f_r_p = './Results/Unlagged/RandomForest_' + val+'_probability_' + str(tr) + '_' + interp + '_returns.csv'\n r_p = pd.read_csv(f_r_p,index_col=0)['Long_Only']\n except:\n f_r_p = './Results/Unlagged/RandomForest_' + val+'_probability_' + interp + '_returns.csv'\n r_p = pd.read_csv(f_r_p,index_col=0)['Long_Only']\n print(f_r_p)\n print(maximum_drawdown(r_p))\n\nfile = './Results/Unlagged/AdaBoost_mean_probability_True_linear_returns.csv'\n#print(f_a_n)\nmax_drawdown(pd.read_csv(file,index_col =0)['Long_Only'])\n\nalgos = ['AdaBoost','GradientBoost','RandomForest']\nvaluation = ['mean','dollar_neutral_refreshed','market_cap']\ninterpolation = ['linear','trend']\nfilterStocks = ['no_rule','probability']\ntr_cost = [True,False]\nfor tr in tr_cost:\n for interp in interpolation:\n for val in valuation:\n #adaboost\n try:\n f_a_n = './Results/Lagged/AdaBoost_' + val+'_no_rule_' + str(tr) + '_' + interp + '_returns_lagged.csv'\n a_n = pd.read_csv(f_a_n,index_col=0)['Long_Only']\n except:\n f_a_n = './Results/Lagged/AdaBoost_' + val+'_no_rule_' + interp + '_returns_lagged.csv'\n a_n = pd.read_csv(f_a_n,index_col=0)['Long_Only']\n print(f_a_n)\n print(max_drawdown(a_n))\n try:\n f_a_p = './Results/Lagged/AdaBoost_' + val+'_probability_' + str(tr) + '_' + interp + '_returns_lagged.csv'\n a_p = pd.read_csv(f_a_p,index_col=0)['Long_Only']\n except:\n f_a_p = './Results/Lagged/AdaBoost_' + val+'_probability_' + interp + '_returns_lagged.csv'\n a_p = pd.read_csv(f_a_p,index_col=0)['Long_Only']\n print(f_a_p)\n print(max_drawdown(a_p))\n #gradientboost\n try:\n f_g_n = './Results/Lagged/GradientBoost_' + val+'_no_rule_' + str(tr) + '_' + interp + '_returns_lagged.csv'\n g_n = pd.read_csv(f_g_n,index_col=0)['Long_Only']\n except:\n f_g_n = './Results/Lagged/GradientBoost_' + val+'_no_rule_' + interp + '_returns_lagged.csv'\n g_n = pd.read_csv(f_g_n,index_col=0)['Long_Only']\n print(f_g_n)\n print(max_drawdown(g_n)) \n try:\n f_g_p = './Results/Lagged/GradientBoost_' + val+'_probability_' + str(tr) + '_' + interp + '_returns_lagged.csv'\n g_p = pd.read_csv(f_g_p,index_col=0)['Long_Only']\n except:\n f_g_p = './Results/Lagged/GradientBoost_' + val+'_probability_' + interp + '_returns_lagged.csv'\n g_p = pd.read_csv(f_g_p,index_col=0)['Long_Only']\n print(f_g_p)\n print(max_drawdown(g_p)) \n #randomforest\n try:\n f_r_n = './Results/Lagged/RandomForest_' + val+'_no_rule_' + str(tr) + '_' + interp + '_returns_lagged.csv'\n r_n = pd.read_csv(f_r_n,index_col=0)['Long_Only']\n except:\n f_r_n = './Results/Lagged/RandomForest_' + val+'_no_rule_' + interp + '_returns_lagged.csv'\n r_n = pd.read_csv(f_r_n,index_col=0)['Long_Only']\n print(f_r_n)\n print(max_drawdown(r_n))\n try:\n f_r_p = './Results/Lagged/RandomForest_' + val+'_probability_' + str(tr) + '_' + interp + '_returns_lagged.csv'\n r_p = pd.read_csv(f_r_p,index_col=0)['Long_Only']\n except:\n f_r_p = './Results/Lagged/RandomForest_' + val+'_probability_' + interp + '_returns_lagged.csv'\n r_p = pd.read_csv(f_r_p,index_col=0)['Long_Only']\n print(f_r_p)\n print(max_drawdown(r_p))\n\nimport pandas as pd\nimport numpy as np\nimport pandas_datareader.data as data\nsp100 = data.DataReader('OEF', 'yahoo', pd.to_datetime('20000101', format='%Y%m%d'), pd.to_datetime('20181130', format='%Y%m%d')).resample('BM').last()\nret_sp100 = sp100['Adj Close'].pct_change().shift(-1)\nsp500 = data.DataReader('^GSPC', 'yahoo', pd.to_datetime('20000101', format='%Y%m%d'), pd.to_datetime('20181130', format='%Y%m%d')).resample('BM').last()\nret_sp500 = sp500['Adj Close'].pct_change().shift(-1)\n\nmax_drawdown(pd.Series(ret_sp100.dropna()))\n\nmax_drawdown(pd.Series(ret_sp500.dropna()))\n\n\n","repo_name":"ritvikgoyal/MFE_Projects","sub_path":"Applied_Finance_Project/Feature Importance/Feature_importance.ipynb","file_name":"Feature_importance.ipynb","file_ext":"py","file_size_in_byte":14978,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"21"} +{"seq_id":"17867044955","text":"# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# \"Open\n\n# + [markdown] id=\"H47EwXpAfYhf\"\n# # Bokeh Tutorial\n#\n# Basic functions for make plots using bokeh\n\n# + [markdown] id=\"2RinruXEfoSv\"\n# ## Imports\n\n# + id=\"ip5_QB3YfRwH\"\nimport numpy as np # we will use this later, so import it now\n\nfrom bokeh.io import output_notebook, show\nfrom bokeh.plotting import figure\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"4QEUbogRf5L4\" outputId=\"08cf3334-db2b-44d5-f8fb-3675259afb12\"\noutput_notebook()\nimport bokeh.sampledata\nbokeh.sampledata.download()\n\n# + [markdown] id=\"rKwzZKEwgYds\"\n# ## Plotting\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 417} id=\"2ObvBiymgagI\" outputId=\"ef773c2c-e430-4942-a248-70b51d62c159\"\np = figure(plot_width=400, plot_height=400)\n\n# add a circle renderer with x and y coordinates, size, color, and alpha\np.circle([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], size=15, line_color=\"navy\", fill_color=\"orange\", fill_alpha=0.5)\n\nshow(p) # show the results\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 417} id=\"-CfeXHOzgzgO\" outputId=\"5732a4ea-e058-4ee9-b04d-b5fc979c55fd\"\np = figure(plot_width=400, plot_height=400)\n\n# add a square renderer with a size, color, alpha, and sizes\np.square([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], size=[10, 15, 20, 25, 30], color=\"firebrick\", alpha=0.6)\n\nshow(p) # show the results\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 417} id=\"3-AQwLR_g8kP\" outputId=\"b1cce2f1-6abf-44c6-810d-afd54bd9f36b\"\n# set up some data\nx = [1, 2, 3, 4, 5]\ny = [6, 7, 8, 7, 3]\n\n# create a new plot with figure\np = figure(plot_width=400, plot_height=400)\n\n# add both a line and circles on the same plot\np.line(x, y, line_width=2)\np.circle(x, y, fill_color=\"white\", size=8)\n\nshow(p) # show the results\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 617} id=\"0A43ueJJhDK3\" outputId=\"cadc48df-97c7-4cab-d82f-d1a30f3032a9\"\nfrom bokeh.palettes import Viridis256\nfrom bokeh.util.hex import hexbin\n\nn = 50000\nx = np.random.standard_normal(n)\ny = np.random.standard_normal(n)\n\nbins = hexbin(x, y, 0.1)\n\n# color map the bins by hand, will see how to use linear_cmap later\ncolor = [Viridis256[int(i)] for i in bins.counts/max(bins.counts)*255]\n\n# match_aspect ensures neither dimension is squished, regardless of the plot size\np = figure(tools=\"wheel_zoom,reset\", match_aspect=True, background_fill_color='#440154')\np.grid.visible = False\n\np.hex_tile(bins.q, bins.r, size=0.1, line_color=None, fill_color=color)\n\nshow(p)\n","repo_name":"MateoProjects/UtilsAI","sub_path":"Bokeh_guide.ipynb","file_name":"Bokeh_guide.ipynb","file_ext":"py","file_size_in_byte":2702,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-jupyter-script","pt":"21"} +{"seq_id":"70161772546","text":"import matplotlib.pyplot as plt\n \n\nx=[100,200]\ny=[23,64]\ny1=[150,176]\nx1=[120,144]\nplt.plot(x1,y1,label=\"road\")\nplt.plot(x,y,label=\"railway\")\nplt.xlabel(\"score\")\nplt.ylabel(\"names\")\nplt.legend()\nplt.show()\n\nx=[\"mudit\",\"sanyam\",\"shoubhik\"]\ny=[4,3,2]\nplt.bar(x,y,label=\"Theory\")\nplt.grid(color='yellow')\nplt.xlabel(\"names\")\nplt.ylabel(\"marks\")\nplt.yscale('linear')\nplt.legend()\nplt.show()\n\nx=[22,30,55,66]\ny=[2,44,55,6]\nx1=[13,23]\ny1=[34,21]\nplt.scatter(x,y,label=\"well\",marker='x',s=50)\nplt.scatter(x1,y1,label=\"water\",s=50)\nplt.legend()\nplt.grid(color='g')\nplt.show()\n\n\n","repo_name":"muditimf/ML-Python","sub_path":"graphplot.ipynb","file_name":"graphplot.ipynb","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"25"} +{"seq_id":"15063731525","text":"# ## Alumno : Jorge Diego Garcia Torres\n# ## Prof. Dr. Ricardo Menchaca Méndez\n#\n# ## Tarea : Random Graph (Erdos-Renyi )\n\nimport random\nimport numpy\nfrom numpy import linspace\nimport matplotlib.pyplot as plt\n\n# ### Funciones\n# - Crear Nodo\n# - Contruir RandomGraph\n# - dfs\n# - \n\n# +\n\nn = 100\np = .6\n\nclass Node:\n def __init__(self, index):\n self.index = index\n self.neighbors = []\n\n def __repr__(self):\n return repr(self.index)\n \n\ndef randomGraph(n,p):\n vertices = [Node(i) for i in range(n)]\n edges = [(i,j) for i in range(n) for j in range(i) if np.random.rand() < p]\n\n for (i,j) in edges:\n vertices[i].neighbors.append(vertices[j])\n vertices[j].neighbors.append(vertices[i])\n\n return vertices\n\n\ndef dfsComponent(node, visited):\n for v in node.neighbors:\n if v not in visited:\n visited.add(v)\n dfsComponent(v, visited)\n \n\nG = randomGraph(n,p)\nprint(G)\n\nprint('vecinos')\nprint(G[1].neighbors)\n\n\ncomponentVisited = set([G[0]])\ndfsComponent(G[0], componentVisited)\n\nprint('visited')\nprint(componentVisited)\n\nprint(\"size of component\")\nprint(len(componentVisited))\n\n \n\n# -\n\n# ## Generar grafos de tamaño n = [10, 100, 1000, 3000] y con constante c = [-5,5] \n# ## donde p = logn/n + c/n\n\n# +\nimport numpy as np\nnlist = [10,100,1000,3000]\nc = np.linspace(-5,5,10)\n\nprint(c)\n\ngresult = []\n\nfor i in nlist:\n rlist = []\n for j in c:\n con = 0\n p = ((np.log(i))/i) + (j/i)\n for k in range(10):\n G = randomGraph(i,p)\n componentVisited = set([G[0]])\n dfsComponent(G[0], componentVisited)\n if len(componentVisited) == i:\n con = con+1\n componentVisited = set()\n\n result = con/10\n rlist.append(result)\n \n gresult.append(rlist)\n\nprint(gresult)\n \n# -\n\n# # Graficando Resultados\n\nplt.plot(c,gresult[3],'x-',label='3000')\nplt.plot(c,gresult[2],'x-',label='1000')\nplt.plot(c,gresult[1],'x-',label='100')\nplt.plot(c,gresult[0],'x-',label='10')\nplt.legend()\nplt.show()\n\nprint(np.random.rand())\n\n# # Utilizando libreria networkx \n\n# +\nfrom networkx.generators.random_graphs import erdos_renyi_graph\n\nn = 6\np = 0.1\ng = erdos_renyi_graph(n, p)\n\nprint(g.nodes)\n# [0, 1, 2, 3, 4, 5]\n \nprint(g.edges)\n# [(0, 1), (0, 2), (0, 4), (1, 2), (1, 5), (3, 4), (4, 5)]\n\n# +\nimport networkx as nx\n\nnx.draw(g) \nplt.show()\n\nT=nx.dfs_tree(g, source=0)\nprint(T.nodes)\n\nnx.draw(T) \nplt.show()\n\n# +\nimport numpy as np\nnlist = [10,100,1000,3000]\nc = np.linspace(-5,5,10)\n\nprint(c)\n\ngresult = []\n\nfor i in nlist:\n rlist = []\n for j in c:\n con = 0\n p = ((np.log(i))/i) + (j/i)\n for k in range(10):\n G = g = erdos_renyi_graph(i, p)\n T= nx.dfs_tree(g, source=0)\n #dfsComponent(G[0], componentVisited)\n if len(T.nodes) == i:\n con = con+1\n #componentVisited = set()\n\n result = con/10\n rlist.append(result)\n \n gresult.append(rlist)\n\nprint(gresult)\n# -\n\n# # RESULTADOS\n\nplt.plot(c,gresult[3],'x-',label='3000')\nplt.plot(c,gresult[2],'x-',label='1000')\nplt.plot(c,gresult[1],'x-',label='100')\nplt.plot(c,gresult[0],'x-',label='10')\nplt.legend()\nplt.show()\n","repo_name":"jaycko2791/ProgramasAlgoritmosAleatorios","sub_path":"programa5(erdos)/erdospy.ipynb","file_name":"erdospy.ipynb","file_ext":"py","file_size_in_byte":3234,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"25"} +{"seq_id":"72525452227","text":"import requests\nimport json\nimport xmltodict\n\n# ### 디바이스 기준 좌표 1000m 이내에 있는 모든 타입의 관광 정보 \n\ntourAPI_key ='s8%2FOL9BcK3JUYuSOOnFxFN%2B342crXBDe08GV9iRCN536y1XDkmU4KKKNUaf79BbPODPv9Lj%2BRZ4IYu3ynJ4VWA%3D%3D'\n\nlanguage = {\n \"EngService\":\"EngService\",\n \"JpnService\":\"JpnService\",\n \"ChsService\":\"ChsService\",\n \"ChtService\":\"ChtService\",\n \"GerService\":\"GerService\",\n \"FreService\":\"FreService\",\n \"SpnService\":\"SpnService\",\n \"RusService\":\"RusService\",\n}\n\nrequest_language = language['EngService']\n\n# +\n\nresponse = requests.get(f'http://api.visitkorea.or.kr/openapi/service/rest/{request_language}/locationBasedList?serviceKey={tourAPI_key}&numOfRows=10&pageSize=10&pageNo=1&startPage=1&MobileOS=ETC&MobileApp=AppTest&listYN=Y&arrange=A&mapX=126.981611&mapY=37.568477&radius=1000').content\n\n\n# +\nxmltodict = xmltodict.parse(response)\n\njson_data = json.dumps(xmltodict)\n\ndict_data = json.loads(json_data)\n\nfirst_request = dict_data['response']['body']['items']['item']\n# -\n\nfirst_request\n\nsecond_request = []\n\nfor data in first_request:\n import xmltodict\n test_id = data['contentid']\n\n response = requests.get(\n f'http://api.visitkorea.or.kr/openapi/service/rest/{request_language}/detailCommon?serviceKey={tourAPI_key}'\n f'&numOfRows=10&pageSize=10&pageNo=1&MobileOS=ETC&MobileApp=AppTest&contentId={test_id}'\n f'&defaultYN=Y&addrinfoYN=Y&overviewYN=Y').content\n xmltodict = xmltodict.parse(response)\n json_data = json.dumps(xmltodict)\n dict_data = json.loads(json_data)\n second_request.append(dict_data)\n print('\\n반복문\\n')\n print(dict_data)\n\n\nfirst_request[4]\n\nsecond_request[4]\n\nfor x, y in zip(first_request, second_request):\n print('\\n request \\n',x,'\\n', y,'\\n')\n\n\n","repo_name":"jeonyh0924/kopa","sub_path":"관광공사 공공 API.ipynb","file_name":"관광공사 공공 API.ipynb","file_ext":"py","file_size_in_byte":1786,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-jupyter-script","pt":"25"} +{"seq_id":"7588202626","text":"# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# \"Open\n\n# + [markdown] id=\"yXA3GwWhY9KL\" colab_type=\"text\"\n# # Part 1 - Scalars and Vectors\n#\n# For the questions below it is not sufficient to simply provide answer to the questions, but you must solve the problems and show your work using python (the NumPy library will help a lot!) Translate the vectors and matrices into their appropriate python representations and use numpy or functions that you write yourself to demonstrate the result or property. \n\n# + id=\"q7Ta8PHTWhfz\" colab_type=\"code\" colab={}\n# _____ _ \n#|_ _| | | \n# | | _ __ ___ _ __ ___ _ __| |_ ___ \n# | | | '_ ` _ \\| '_ \\ / _ \\| '__| __/ __|\n# _| |_| | | | | | |_) | (_) | | | |_\\__ \\\n#|_____|_| |_| |_| .__/ \\___/|_| \\__|___/\n# | | \n# |_| \n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom math import e, pi\n\n#Favorite colors\nBlack = \"#000000\"\nPurple = \"#550080\"\nBlue = \"#2727ff\"\nGreen = \"#2b8000\"\nRed = \"#d1001c\"\n\n# + [markdown] id=\"oNOTv43_Zi9L\" colab_type=\"text\"\n# ## 1.1 Create a two-dimensional vector and plot it on a graph\n\n# + id=\"XNqjzQzrkVG7\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 265} outputId=\"5e879316-4fa7-4850-b0d5-da6eff5c3e8a\"\nVect = np.array([7, 3])\n\nfig, ax = plt.subplots()\nax.grid()\nplt.xlim(-1,9)\nplt.ylim(-1,9)\n\nplt.arrow(0,0, \n Vect[0],\n Vect[1],\n head_width=.25,\n head_length=.25,\n linewidth=3,\n color=Purple\n );\n\n# + [markdown] id=\"unKFT619lk3e\" colab_type=\"text\"\n# ## 1.2 Create a three-dimensional vecor and plot it on a graph\n\n# + id=\"atUEd3T6llKm\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 248} outputId=\"939d98b7-354a-43e6-d537-43227f98612d\"\nVect = np.array([[0,0,0, 5,7,3]])\n\nX,Y,Z, U,V,W = zip(*Vect)\n\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\nax.set_xlim([-1, 9])\nax.set_ylim([-1, 9])\nax.set_zlim([-1, 9])\nax.set_xlabel('X')\nax.set_ylabel('Y')\nax.set_zlabel('Z')\n\nax.quiver(0,0,0, \n U,\n V,\n W,\n length=1,\n linewidth=3,\n color= Purple\n );\n\n# + [markdown] id=\"b7qFxbKxZmI2\" colab_type=\"text\"\n# ## 1.3 Scale the vectors you created in 1.1 by $5$, $\\pi$, and $-e$ and plot all four vectors (original + 3 scaled vectors) on a graph. What do you notice about these vectors? \n\n# + id=\"3qpwDlzXkVf5\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 265} outputId=\"cd2407cb-2632-4fe9-8f31-a1e1f4968554\"\nVect = np.array([7, 3])\nVectPi = np.multiply(pi, Vect)\nVecte = np.multiply(-e, Vect)\nVect5 = np.multiply(5, Vect)\n#print(Vect)\n#print(VectPi)\n#print(Vecte)\n#print(Vect5)\nfig, ax = plt.subplots()\nax.grid()\nplt.xlim(-20,36)\nplt.ylim(-9,16)\n\n\nfor Vector, Color in [(Vect, Black), #for some reason I don't see this one on the graph\n (VectPi, Purple), \n (Vecte, Red),\n (Vect5, Green)]: \n plt.arrow(0,0, \n Vector[0],\n Vector[1],\n head_width=.75,\n head_length=.75,\n linewidth=3,\n color=Color\n )\n\n# + [markdown] id=\"wrgqa6sWimbH\" colab_type=\"text\"\n# ## 1.4 Graph vectors $\\vec{a}$ and $\\vec{b}$ and plot them on a graph\n#\n# \\begin{align}\n# \\vec{a} = \\begin{bmatrix} 5 \\\\ 7 \\end{bmatrix}\n# \\qquad\n# \\vec{b} = \\begin{bmatrix} 3 \\\\4 \\end{bmatrix}\n# \\end{align}\n\n# + id=\"I1BGXA_skV-b\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 269} outputId=\"391f2764-84d4-4112-ef6a-3ac599f28809\"\na = np.array([5,7])\nb = np.array([3,4])\nplt.xlim(0,10)\nplt.ylim(0,10)\nfor Vector, Color in [(a, Black),\n (b, Purple)]:\n plt.arrow(0,0, \n Vector[0],\n Vector[1],\n head_width=.75,\n head_length=.75,\n linewidth=3,\n color=Color\n )\n\n# + [markdown] id=\"QN6RU_3gizpw\" colab_type=\"text\"\n# ## 1.5 find $\\vec{a} - \\vec{b}$ and plot the result on the same graph as $\\vec{a}$ and $\\vec{b}$. Is there a relationship between vectors $\\vec{a} \\thinspace, \\vec{b} \\thinspace \\text{and} \\thinspace \\vec{a-b}$\n\n# + id=\"68sWHIOPkXp5\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 269} outputId=\"a898c3dd-51f0-4508-9dec-5a1180b9bd48\"\na = np.array([5,7])\nb = np.array([3,4])\naminb = a-b\nplt.xlim(0,10)\nplt.ylim(0,10)\nfor Vector, Color in [(a, Black),\n (b, Purple),\n (aminb, Blue)]:\n plt.arrow(0,0, \n Vector[0],\n Vector[1],\n head_width=.5,\n head_length=.5,\n linewidth=3,\n color=Color\n )\n# it is shorter however the slope is higher than both a and b\n\n# + [markdown] id=\"1ZPVuJAlehu_\" colab_type=\"text\"\n# ## 1.6 Find $c \\cdot d$\n#\n# \\begin{align}\n# \\vec{c} = \\begin{bmatrix}7 & 22 & 4 & 16\\end{bmatrix}\n# \\qquad\n# \\vec{d} = \\begin{bmatrix}12 & 6 & 2 & 9\\end{bmatrix}\n# \\end{align}\n#\n\n# + id=\"2_cZQFCskYNr\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34} outputId=\"44430f7b-19fb-4c41-8abb-2e7f99be5e1b\"\nc = np.array([7,22,4,16])\nd = np.array([12,6,2,9])\nctimesd = c*d\n\nresult = 0\nfor num in c*d:\n result += num\nresult\n\n# + [markdown] id=\"cLm8yokpfg9B\" colab_type=\"text\"\n# ## 1.7 Find $e \\times f$\n#\n# \\begin{align}\n# \\vec{e} = \\begin{bmatrix} 5 \\\\ 7 \\\\ 2 \\end{bmatrix}\n# \\qquad\n# \\vec{f} = \\begin{bmatrix} 3 \\\\4 \\\\ 6 \\end{bmatrix}\n# \\end{align}\n\n# + id=\"ku-TdCKAkYs8\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 269} outputId=\"c0233be9-d054-4d17-943f-4b337e048c97\"\nve = np.array([5,7,2])\nf = np.array([3,4,6])\netimesf = c*d\nplt.xlim(0,10)\nplt.ylim(0,10)\nfor Vector, Color in [(ve, Black),\n (f, Purple),\n (etimesf, Blue)]:\n plt.arrow(0,0, \n Vector[0],\n Vector[1],\n head_width=.5,\n head_length=.5,\n linewidth=3,\n color=Color\n )\n# again higher slop but also gets much longer and goes out into the distance\n\n# + [markdown] id=\"-TN8wO2-h53s\" colab_type=\"text\"\n# ## 1.8 Find $||g||$ and then find $||h||$. Which is longer?\n#\n# \\begin{align}\n# \\vec{g} = \\begin{bmatrix} 1 \\\\ 1 \\\\ 1 \\\\ 8 \\end{bmatrix}\n# \\qquad\n# \\vec{h} = \\begin{bmatrix} 3 \\\\3 \\\\ 3 \\\\ 3 \\end{bmatrix}\n# \\end{align}\n\n# + id=\"-5VKOMKBlgaA\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 50} outputId=\"d62f7960-a7c2-4d2f-c676-43d9258d50c1\"\ng = np.array([1,1,1,8])\nh = np.array([3,3,3,3])\nprint(np.linalg.norm(g))\nprint(np.linalg.norm(h))\n\n# + [markdown] id=\"njrWIMS-ZAoH\" colab_type=\"text\"\n# # Part 2 - Matrices\n\n# + [markdown] id=\"GjkcAVIOmOnn\" colab_type=\"text\"\n# ## 2.1 What are the dimensions of the following matrices? Which of the following can be multiplied together? See if you can find all of the different legal combinations.\n# \\begin{align}\n# A = \\begin{bmatrix}\n# 1 & 2 \\\\\n# 3 & 4 \\\\\n# 5 & 6\n# \\end{bmatrix}\n# \\qquad\n# B = \\begin{bmatrix}\n# 2 & 4 & 6 \\\\\n# \\end{bmatrix}\n# \\qquad\n# C = \\begin{bmatrix}\n# 9 & 6 & 3 \\\\\n# 4 & 7 & 11\n# \\end{bmatrix}\n# \\qquad\n# D = \\begin{bmatrix}\n# 1 & 0 & 0 \\\\\n# 0 & 1 & 0 \\\\\n# 0 & 0 & 1\n# \\end{bmatrix}\n# \\qquad\n# E = \\begin{bmatrix}\n# 1 & 3 \\\\\n# 5 & 7\n# \\end{bmatrix}\n# \\end{align}\n\n# + id=\"Z69c-uPtnbIx\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 136} outputId=\"33d995c5-34c1-466e-ff7d-3855b88a6f5a\"\nAd = np.array([[3],[2]])\nBd = np.array([[1],[3]])\nCd = np.array([[2],[3]])\nDd = np.array([[3],[3]])\nEd = np.array([[2],[2]])\n#All combinations AC AE BA BD CA CD DA EC\n\n\nA = np.array([[1,2], [3,4], [5,6]])\nB = np.array([[2,4,6]])\nC = np.array([[9,6,3], [4,7,11]])\nD = np.array([[1,0,0], [0,1,0], [0,0,1]])\nE = np.array([[1,3], [5,7]])\n#np.matmul(A,B)\npd.DataFrame(A)\n\n# + [markdown] id=\"lMOlCoM3ncGa\" colab_type=\"text\"\n# ## 2.2 Find the following products: CD, AE, and BA. What are the dimensions of the resulting matrices? How does that relate to the dimensions of their factor matrices?\n\n# + id=\"zhKwiSItoE2F\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 185} outputId=\"0a5af1aa-6f18-4eb3-860a-8b466bf74a84\"\nprint(np.matmul(C,D))\nprint(\"\\n\")\nprint(np.matmul(A,E))\nprint(\"\\n\")\nprint(np.matmul(B,A))\n\n# + [markdown] id=\"p2jmaGLgoFPN\" colab_type=\"text\"\n# ## 2.3 Find $F^{T}$. How are the numbers along the main diagonal (top left to bottom right) of the original matrix and its transpose related? What are the dimensions of $F$? What are the dimensions of $F^{T}$?\n#\n# \\begin{align}\n# F = \n# \\begin{bmatrix}\n# 20 & 19 & 18 & 17 \\\\\n# 16 & 15 & 14 & 13 \\\\\n# 12 & 11 & 10 & 9 \\\\\n# 8 & 7 & 6 & 5 \\\\\n# 4 & 3 & 2 & 1\n# \\end{bmatrix}\n# \\end{align}\n\n# + id=\"Wl3ElwgLqaAn\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 84} outputId=\"dbcca4ab-958a-4402-ccbe-849a56d482a2\"\nF = np.array([[20,19,18,17], \n [16,15,14,13], \n [12,11,10,9], \n [8,7,6,5], \n [4,3,2,1]])\nprint(F.T)\n\n# + [markdown] id=\"13ik2LEEZLHn\" colab_type=\"text\"\n# # Part 3 - Square Matrices\n\n# + [markdown] id=\"sDBAPUwfp7f7\" colab_type=\"text\"\n# ## 3.1 Find $IG$ (be sure to show your work) 😃\n#\n# You don't have to do anything crazy complicated here to show your work, just create the G matrix as specified below, and a corresponding 2x2 Identity matrix and then multiply them together to show the result. You don't need to write LaTeX or anything like that (unless you want to).\n#\n# \\begin{align}\n# G= \n# \\begin{bmatrix}\n# 13 & 14 \\\\\n# 21 & 12 \n# \\end{bmatrix}\n# \\end{align}\n\n# + id=\"ZnqvZBOYqar3\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 67} outputId=\"4ba92346-e126-4288-980a-ba23c00a6784\"\nG = np.array([[13,14], [21,12]])\nI = np.array([[1,0], [0,1]])\nprint(pd.DataFrame(np.matmul(I,G)))\n\n# + [markdown] id=\"DZ_0XTDQqpMT\" colab_type=\"text\"\n# ## 3.2 Find $|H|$ and then find $|J|$.\n#\n# \\begin{align}\n# H= \n# \\begin{bmatrix}\n# 12 & 11 \\\\\n# 7 & 10 \n# \\end{bmatrix}\n# \\qquad\n# J= \n# \\begin{bmatrix}\n# 0 & 1 & 2 \\\\\n# 7 & 10 & 4 \\\\\n# 3 & 2 & 0\n# \\end{bmatrix}\n# \\end{align}\n#\n\n# + id=\"5QShhoXyrjDS\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 50} outputId=\"93b8aaf6-4c96-4941-95af-cef2eab96b0e\"\nH = np.array([[12,11], [7,10]])\nJ = np.array([[0,1,2], [7,10,4], [3,2,0]])\nprint(\"H Det\", np.linalg.det(H))\nprint(\"J Det\", np.linalg.det(J))\n\n# + [markdown] id=\"2gZl1CFwrXSH\" colab_type=\"text\"\n# ## 3.3 Find $H^{-1}$ and then find $J^{-1}$\n\n# + id=\"nyX6De2-rio1\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 134} outputId=\"90c5f79c-d8a2-43d2-99c7-cd1378cc197a\"\nprint(\"H Det\", pd.DataFrame(np.linalg.inv(H)))\nprint(\"J Det\", pd.DataFrame(np.linalg.inv(J)))\n\n# + [markdown] id=\"Vvd4Pe86rjhW\" colab_type=\"text\"\n# ## 3.4 Find $HH^{-1}$ and then find $J^{-1}J$. Is $HH^{-1} == J^{-1}J$? Why or Why not? \n#\n# Please ignore Python rounding errors. If necessary, format your output so that it rounds to 5 significant digits (the fifth decimal place).\n\n# + id=\"Cir51CtOnT5Q\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 151} outputId=\"ebc894d4-32a3-48c9-ea62-5d803b9ae466\"\n#\"{0:.2f}\".format\nprint(np.matmul(H,np.linalg.inv(H)))\nprint(np.matmul(np.linalg.inv(J),J))\nprint(np.matmul(np.linalg.inv(J),J) == np.matmul(H,np.linalg.inv(H)))\n# I can see it both ways because they are both identity matrices however their\n# dimensions are different. To me this means they are different. Also asking\n# python if they are the same it returns false.\n\n# + [markdown] id=\"V0iTO4McYjtk\" colab_type=\"text\"\n# # Stretch Goals: \n#\n# A reminder that these challenges are optional. If you finish your work quickly we welcome you to work on them. If there are other activities that you feel like will help your understanding of the above topics more, feel free to work on that. Topics from the Stretch Goals sections will never end up on Sprint Challenges. You don't have to do these in order, you don't have to do all of them. \n#\n# - Write a function that can calculate the dot product of any two vectors of equal length that are passed to it.\n# - Write a function that can calculate the norm of any vector\n# - Prove to yourself again that the vectors in 1.9 are orthogonal by graphing them. \n# - Research how to plot a 3d graph with animations so that you can make the graph rotate (this will be easier in a local notebook than in google colab)\n# - Create and plot a matrix on a 2d graph.\n# - Create and plot a matrix on a 3d graph.\n# - Plot two vectors that are not collinear on a 2d graph. Calculate the determinant of the 2x2 matrix that these vectors form. How does this determinant relate to the graphical interpretation of the vectors?\n#\n#\n","repo_name":"AidanMahoney73/DS-Unit-1-Sprint-3-Linear-Algebra","sub_path":"module1-vectors-and-matrices/LS_DS_131_Vectors_and_Matrices_Assignment.ipynb","file_name":"LS_DS_131_Vectors_and_Matrices_Assignment.ipynb","file_ext":"py","file_size_in_byte":13160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-jupyter-script","pt":"25"} +{"seq_id":"5002128155","text":"# + [markdown] id=\"ni4T_dwEHFVa\"\n# ## CS 6120: Natural Language Processing - Prof. Ahmad Uzair\n#\n# ### Assignment 2: Text Classification and Neural Network\n# ### Total Points: 100 points\n\n# + [markdown] id=\"loQ22M-bCubq\"\n# In Assignment 2, you will be dealing with text classification using Multinomial Naive Bayes and Neural Networks. You will also be dealing with vector visualization. In the previous assingment you implemented Bag of Words as the feature selection method. However, in this assignment you will be using TF-IDF Vectorization instead of Bag of Words. We recommend starting with this assignment a little early as the datasets are quite large and several parts of the assignment might take long duration to execute. \n\n# + [markdown] id=\"Q3brglC1C0mZ\"\n# ## Question 1 Text Classification\n\n# + [markdown] id=\"IZ1y75IoC3rE\"\n# In the first question you will be dealing with 20 News Group Dataset. You are required to implement TF-IDF vectorization from scratch and perform Multinomial Naive Bayes Classification on the News Group Dataset.\n# You may use appropriate packages or modules for fitting the Multinomial Naive Bayes Model, however, the implementation of the TF-IDF Vectorization should be from the scratch.\n\n# + [markdown] id=\"yRjM45PyC8ML\"\n# The 20 newsgroups dataset comprises around 18000 newsgroups posts on 20 topics split in two subsets: one for training (or development) and the other one for testing (or for performance evaluation). The split between the train and test set is based upon a messages posted before and after a specific date.\n#\n# Link to the original dataset: http://archive.ics.uci.edu/ml/datasets/Twenty+Newsgroups\n#\n# You can also import the dataset from sklearn.datasets\n\n# + id=\"CmFf2INNDJRb\"\n#importing the libraries\nimport numpy as np\nimport sklearn\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.datasets import fetch_20newsgroups\nfrom sklearn.metrics import f1_score\nfrom pprint import pprint\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn import preprocessing\nfrom nltk.corpus import stopwords\nfrom nltk.stem import PorterStemmer\nfrom nltk.tokenize import word_tokenize\nimport pandas as pd\nimport re\nimport numpy as np\nfrom nltk.tokenize import word_tokenize \nimport nltk\nimport contractions\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn import metrics\n\n# + id=\"AEp1SHe5DKCB\"\n# Import the 20 news group dataset utilizing sklearn library\n\nmydata_train = fetch_20newsgroups(subset='train',remove=('headers', 'quotes'))\n\nmydata_test = fetch_20newsgroups(subset='test',remove=('headers', 'quotes'))\n\n\n# + id=\"OscOmcE0DMHa\"\n# Print the news groups(target) in the dataset\n\npprint(list(mydata_train.target_names))\n\n# + id=\"JvQb2r0aDR_J\"\n# What is the type of 'mydata_train' and 'mydata_test'\n\nprint(type(mydata_train))\nprint(type(mydata_test))\n\n# + id=\"ozzwyREhDaMK\"\n# Check the length of the data\n\nprint(len(mydata_train.data))\nprint(len(mydata_train.filenames))\nprint(len(mydata_test.data))\nprint(len(mydata_test.filenames))\n\n# + [markdown] id=\"BlipMuEpDz-K\"\n# ### Expected Output: \n# 11314\n#\n# 11314\n#\n# 7532\n#\n# 7532\n\n# + [markdown] id=\"55FKOBBuEDI2\"\n# ## Extracting Features from the Dataset (20 Points)\n\n# + [markdown] id=\"u4GDENzmEEkG\"\n# In order to perform machine learning on text documents, we first need to turn the text content into numerical feature vectors.\n\n# + [markdown] id=\"OgxfDXmxEHid\"\n# ### TF-IDF Vectorization\n\n# + [markdown] id=\"Q8qNFFYyEKsa\"\n# Our model cannot simply read the text data so we convert it into numerical format. In order to convert the data into numerical format we create vectors from text.\n#\n# For this particular purpose we could either employ Bag of Words or TF-IDF Vectorization\n#\n# Bag of Words just creates a set of vectors containing the count of word occurrences in the document (reviews), while the TF-IDF model contains information on the more important words and the less important ones as well.\n#\n# TF-IDF stands for Term Frequency-Inverse Document Frequency, which instead of giving more weight to words that occur more frequently, it gives a higher weight to words that occur less frequently.\n#\n# Ref:https://www.analyticsvidhya.com/blog/2020/02/quick-introduction-bag-of-words-bow-tf-idf/#:~:text=Bag%20of%20Words%20just%20creates,less%20important%20ones%20as%20well.\n\n# + [markdown] id=\"dLzgRJRZEP3k\"\n# TF-IDF = Term Frequency (TF) * Inverse Document Frequency (IDF)\n\n# + [markdown] id=\"xe5lHi3NE1QJ\"\n# Term Frequency is the measure of the frequency of words in a document. It is the ratio of the number of times the word appears in a document compared to the total number of words in that document.\n#\n# The words that occur rarely in the corpus have a high IDF score. It is the log of the ratio of the number of documents to the number of documents containing the word.\n\n# + [markdown] id=\"HXotAER_EQ8T\"\n# idf(t) = log(N/(df + 1))\n\n# + id=\"2vzVI8ylFAEl\"\ntext = mydata_train.data\ntest = mydata_test.data\n# -\n\n\n\n# + [markdown] id=\"HZ2AatmvFtE-\"\n# ## Preprocessing the Corpus\n# -\n\ntext_label = mydata_train.target\ntest_label = mydata_test.target\n\n# + id=\"XyJbe42AFuHp\"\n# Preprocessing the data\nimport contractions\n\nlines = [] \nword_list = [] \ntrain_labels = []\n \n# tokenization takes here which do updates list word_list and lines\nfor i,(line,label) in enumerate(zip(text,text_label)):\n print('Doc {} of {}'.format(i+1,len(text)),end='\\r')\n expanded_words = [] \n for word in line.split():\n expanded_words.append(contractions.fix(word))\n line = ' '.join(expanded_words)\n \n line = re.sub(r'\\W+', ' ', line)\n line = re.sub(r'\\d+', '', line)\n #print('Line after preprocessing is \\n', line)\n if len(word_tokenize(line))!=0:\n lines.append(word_tokenize(line))\n train_labels.append(label)\n word_list.extend(word_tokenize(line)) \n\n# Make sure the word_list contains unique tokens\nword_list_unique = list( dict.fromkeys(word_list))\nprint()\nprint('Vocabulary count ', len(word_list_unique))\n\n# Calculate the total documents present in the corpus\ntotal_docs = len(lines)\nprint('Total number of docs after clean-up is: ',total_docs)\n \n#Create a dictionary to keep track of index of each word\ndict_idx = {}\nfor i,word in enumerate(word_list_unique):\n dict_idx[word] = i\n \n\n# + id=\"E6M_CoI9FxYb\"\n# Create a frequency dictionary\n \ndef frequency_dict(lines, word_list_unique):\n '''\n lines: list containing all the tokens\n ---\n freq_word: returns a dictionary which keeps the count of the number of documents containing the given word\n '''\n freq_word = {}\n for i,eachWord in enumerate(word_list_unique):\n print('Word {} of {}'.format(i+1,len(word_list_unique)),end='\\r')\n word_doc_count = 0\n for eachLine in lines:\n if eachWord in eachLine:\n word_doc_count+=1 \n freq_word[eachWord] = word_doc_count\n \n \n return freq_word\n\n# + id=\"qFkt9KBgFz43\"\n# Create a dictionary containing the frequency of words utilizing the 'frequency_dict' function\n\n# Expect this chunk to take a comparatively longer time to execute since our dataset is large\n\nfreq_word = frequency_dict(lines, word_list_unique)\nprint()\nwith open('freq_word.txt', 'w') as data:\n data.write(str(freq_word))\n \n\n# +\n#Read dictionary from text file\nimport ast\n \n# reading the data from the file\nwith open('freq_word.txt') as f:\n data = f.read()\nprint(\"Data type before reconstruction : \", type(data))\n \n# reconstructing the data as a dictionary\nfreq_word = ast.literal_eval(data)\n \nprint(\"Data type after reconstruction : \", type(freq_word))\n#print(d)\n\n# + id=\"vLvPijR_GKHn\"\n# Create a function to calculate the Term Frequency\n\ndef term_frequency(document, word):\n '''\n document: list containing the entire corpus\n word: word whose term frequency is to be calculated\n ---\n tf: returns term frequency value\n '''\n numberofwords = len(document)\n countofword = 0\n if word in document:\n countofword = document.count(word)\n \n tf = countofword/numberofwords\n \n return tf\n\n\n# + id=\"HA99G_yAGLCC\"\n# Create a function to calculate the Inverse Document Frequency\n \ndef inverse_df(word,lines):\n '''\n word: word whose inverse document frequency is to be calculated\n ---\n idf: return inverse document frequency value\n '''\n\n numofdocs = len(lines) \n \n idf = np.log(numofdocs/(freq_word[word]+1)) \n \n return idf\n\n\n# + id=\"F0irgwv2GRfE\"\n#Create a function to combine the term frequencies (TF) and inverse document (IDF) frequencies calculated above to get TF-IDF\n\ndef tfidf(sentence,dict_idx):\n '''\n sentence: list containing the entire corpus\n dict: dictionary keeping track of index of each word\n ---\n tf_idf_vec: returns computed tf-idf\n '''\n\n tf_idf_vec = []\n for i,eachSentence in enumerate(sentence):\n print('Sentence {} of {}'.format(i+1,len(sentence)),end='\\r')\n samplefeatures = [0] * len(dict_idx)\n \n for eachWord in eachSentence:\n if eachWord in dict_idx:\n samplefeatures[dict_idx[eachWord]] = term_frequency(eachSentence,eachWord) * inverse_df(eachWord,sentence)\n \n tf_idf_vec.append(samplefeatures)\n \n return tf_idf_vec\n\n\n# -\n\n# Tf-IDF is the feature vector. So, its shape should be (n_samples,n_features) where n_samples is the number of documents in the dataset i.e. 11314 and the n_features is the vocabulary length since we are associating a number(tf-idf) with each unique word in the vocabulary\n\n# + id=\"_VKJhqatGWpV\"\n#Compute the vectors utilizing the 'tfidf' function created above to obtain a TF-IDF Encoded text corpus\n\ntf_idf_vec = tfidf(lines, dict_idx)\nprint()\n\n# +\nprint(type(tf_idf_vec))\n\ntf_idf_vec = np.asarray(tf_idf_vec)\n\nprint(tf_idf_vec.shape)\n# class : approximately 11004 or more list 99374 . Its 10.1G that needs to be get into the array depending upon the GPU it will show\n\n# + [markdown] id=\"LE0UGUaSGb8I\"\n# ## Multinomial Naive Bayes (10 Points)\n\n# + id=\"yWYcxrdJGfDC\"\n#Fit a Multinomial Naive Bayes Model on our dataset\n\nmodel = MultinomialNB(alpha=.01)\nmodel.fit(tf_idf_vec, train_labels)\n\n\n# + id=\"G6CiQB4qGfqH\"\n#Perform testing on the train dataset\n\n# Perform all pre-processing and feature extraction on the test data\n\npred = model.predict(tf_idf_vec)\n\n# + id=\"yCLagGu6Gh6T\"\n#Calculate the F1 Score and the Accuracy\n\nF1_score = metrics.f1_score(train_labels, pred, average='macro')\nAccuracy = metrics.accuracy_score(train_labels, pred)\nprint(\"F1 Score: \", F1_score)\nprint(\"Accuracy: \", Accuracy)\n\n#F1 Score: 0.9853457835628475\n#Accuracy: 0.9834562952289263\n\n# + [markdown] id=\"bbMRqJv5Gl2F\"\n# ### Expected Output:\n# F1 Score: 0.9533633964397735\n#\n# Accuracy: 0.9524482941488421\n\n# + [markdown] id=\"AWRDuUqU-taV\"\n# Your accuracy does not have to be exactly the same. This is just to give you an estimate of what could you expect your accuracy to be around.\n\n# +\n# Testing of the vectors\n\ntest_lines = [] \ntest_labels = []\n \n\nfor i,(line,label) in enumerate(zip(test,test_label)):\n \n print('Doc {} of {}'.format(i+1,len(test)),end='\\r')\n \n expanded_words = [] \n for word in line.split():\n expanded_words.append(contractions.fix(word))\n line = ' '.join(expanded_words)\n \n line = re.sub(r'\\W+', ' ', line)\n line = re.sub(r'\\d+', '', line)\n #print('Line after preprocessing is \\n', line)\n if len(word_tokenize(line))!=0:\n test_lines.append(word_tokenize(line))\n test_labels.append(label)\n# -\n\ntest_tf_idf = tfidf(test_lines, dict_idx)\nprint()\n\n# +\ntest_pred = model.predict(test_tf_idf)\n\n\nF1_score = metrics.f1_score(test_labels, test_pred, average='macro')\nAccuracy = metrics.accuracy_score(test_labels, test_pred)\nprint(\"F1 Score: \", F1_score)\nprint(\"Accuracy: \", Accuracy)\n\n#F1 Score: 0.6735684921245673\n#Accuracy: 0.7345783528492727\n\n# + [markdown] id=\"UfMc8cz93Cc0\"\n# ## Question 2 Vector Visualization\n\n# + [markdown] id=\"70iwEeL23F7K\"\n# In this unsupervised learning task we are going to cluster wikipedia articles into groups using T-SNE visualization after vectorization.\n\n# + [markdown] id=\"UHx4YuxW36oM\"\n# ### Collect articles from Wikipedia (10 points)\n#\n# In this section we will download articles from wikipedia and then vectorize them in the next step. You can select somewhat related topics or fetch the articles randomly. \n# (Use dir() and help() functions or refer wikipedia documentation)\n# You may also pick any other data source of your choice instead of wikipedia.\n\n# + id=\"jA419x6__mjg\"\n# install libraries\n#pip install wikipedia\n\n# + id=\"vLMLk4K84Zbn\"\nimport wikipedia\nfrom wikipedia.exceptions import WikipediaException\nimport random\nimport wikipedia\nfrom wikipedia.exceptions import WikipediaException\nimport pandas as pd\n'''\n Generate a list of wikipedia article to cluster \n You can maintain a static list of titles or generate them randomly using wikipedia library\n Some topics include:\n [\"Northeastern Unversity\", \"Natural language processing\", \"Machine learning\", \"Quantum machine learning\", \"Artificial intelligence\", \"Data science\", \"Master in Data Science\", \n \"Bank of America\", \"Visa Inc.\", \"European Central Bank\", \"Bank\", \"Financial technology\",\"International Monetary Fund\", \n \"Basketball\", \"Swimming\", \"Tennis\", \"Football\", \"College Football\", \"Association Football\"]\n\n You can add more topics from different categories so that we have a diverse dataset to work with. \n Ex- About 3+ categories(groups), 3+ topics in each category, 3+ articles in each topic\n'''\n\n# selected topics\ntopics = [\"Northeastern Unversity\", \"Natural language processing\", \"Machine learning\", \"Quantum machine learning\", \"Artificial intelligence\", \"Data science\", \"Master in Data Science\", \n \"Bank of America\", \"Visa Inc.\", \"European Central Bank\", \"Bank\", \"Financial technology\",\"International Monetary Fund\", \n \"Basketball\", \"Swimming\", \"Tennis\", \"Football\", \"College Football\", \"Association Football\"]\n\n# list of articles to be downloaded\narticles =[\"Football\", \"College Football\", \"Association Football\", \"International Football\",\"Basketball\", \n \"Bank of America\", \"Visa Inc.\", \"Santander Bank\",\n \"Natural language processing\", \"Machine learning\", \"Quantum machine learning\", \"Artificial intelligence\", \"Data science\",\n \"Northeastern Unversity\", \"Boston University\", \"Suffolk University\", \"Harvard University\",\n \"Facebook\", \"Twitter\", \"Instagram\", \"Snapchat\",\n \"Mexico\", \"Canada\", \"Germany\", \"Poland\", \"India\",\n \"Albert Einstein\", \"Marie Curie\", \"Nikola Tesla\", \"Charles Darwin\",\n \"Cadbury\", \"The Hershey Company\", \"Nestle\", \"Ferrero Rocher\",\n \"BWM\", \"Mercedes Benz\", \"volkswagen\", \"chevrolet\"]\n\n# download and store articles (summaries) in this variable\ndata=[]\nart=[]\n#labels=[] \nfor article in articles:\n try:\n page_article = wikipedia.page(article)\n data.append(page_article.content)\n art.append(article)\n #labels.append(i+1)\n except WikipediaException:\n continue \n\n\n# + [markdown] id=\"IgpRv7wQ4Dpm\"\n# ### Cleaning the Data (5 points)\n# In this step you will decide whether to clean the data or not. If you choose to clean, you may utilize the clean function from assignment 1.\n#\n# **Question:** Why are you (not) choosing to clean the data? Think in terms of whether cleaning data will help in the clustering or not.\n#\n# **Answer:** \n# Data cleaning is very neceesary. This step removes umimportant such as stop words , deimeters words that doesn't add vale to the model and can further reduce the dimentionality of the model . This also affects the clustering of the model too \n\n# + [markdown] id=\"PnZpDKcaHTGq\"\n# **Answer(1-3 sentences):** \n\n# + id=\"lNj53Pxr963N\"\nimport re\nimport nltk\nimport string\nfrom nltk.corpus import stopwords\nfrom nltk.stem import PorterStemmer\nfrom nltk.tokenize import word_tokenize\nimport contractions\nfrom bs4 import BeautifulSoup\nfrom nltk.stem import WordNetLemmatizer\nnltk.download('punkt')\nnltk.download('stopwords')\n\n\n# +\n# You can use Assignment 1's clean message function\n\ndef clean_message(message):\n '''\n Input:\n message: a string containing a message.\n Output:\n messages_cleaned: a list of words containing the processed message. \n\n '''\n #To remove punctuation\n message_processed = \"\"\n for word in message:\n if word not in string.punctuation:\n message_processed += \"\".join(word)\n \n #To make lower case\n message_processed = message_processed.lower()\n \n #Tokenization\n message_processed = word_tokenize(message_processed)\n \n #Stop word removal\n message_clean= []\n stopwords = nltk.corpus.stopwords.words('english')\n for word in message_processed:\n if word not in stopwords:\n message_clean.append(word)\n \n #Stemming\n messages_cleaned= []\n porter_stemmer = PorterStemmer()\n for word in message_processed:\n messages_cleaned.append(porter_stemmer.stem(word))\n \n cleaned_message = \" \".join(messages_cleaned)\n \n return cleaned_message\n\n\n# -\n\ncleaned_data = []\nfor dat in data:\n cleaned_data.append(clean_message(dat))\n\n# + [markdown] id=\"bvRZUpmq-DmT\"\n# ### Vectorize the articles (5 points)\n#\n# In this step, we will vectorize the text data. You can use TfidfVectorizer() or countVectorizer() from sklearn library.\n\n# + id=\"gJk8YY89-OU4\"\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nvectors = TfidfVectorizer(stop_words={'english'})\ntext_vectors = vectors.fit_transform(cleaned_data)\n\n# + id=\"DAIGlqEuINWA\"\nprint(text_vectors.shape)\n# -\n\n\n\n# + [markdown] id=\"PKLvrKHRQaQq\"\n# ### Sample Output:\n# (36, 1552)\n\n# + [markdown] id=\"M5ZrGrzD_G8d\"\n# ### Plot Articles (10 points)\n# Now we will try to verify the groups of articles using T-SNE from sklearn library.\n\n# + id=\"SjcuZBOe-oZq\"\nfrom sklearn.manifold import TSNE\n#give no components , inti,.fit transform(input x) \nmodel = TSNE(random_state=1,n_components=2).fit_transform(text_vectors)\n# call TSNE() to fit the data\n# -\n\nprint(model.shape)\nmodel_1 = model[:,0]\nmodel_2 = model[:,1]\nlabel=[]\n\n# + [markdown] id=\"iCY_blxjO1bs\"\n# Plot and annotate the points with different markers for different expected groups.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 483} id=\"3ODUA1Vf-rRd\" outputId=\"325b5db4-60d1-4907-a487-40893e256ee1\"\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# get a figure handle\n# the figure gives the error because of the below lines . It is some how not taking the correct values of the label. hence the clustering is happening but \n#its not getying divided into the colors . May be it is beacuse of the gpu problem that my programm is not taking it . \n#fig,ax = plt.subplots(figsize=(10,8))\n#sns.scatterplot(x=model_1, y=model_2, hue=labels,\n# palette=sns.color_palette(\"hls\", num_clusters)).set(title=\"Wiki Article data T-SNE projection\") \nsns.scatterplot(x=model_1, y=model_2)\n\n\n# + [markdown] id=\"dYcEi1EC_UGO\"\n# **Question:** Comment about the categorizion done by T-SNE. Do the articles of related topics cluster together? (5 points)\n# yes they do cluster together because of the tsne cluster function that has been used properly . also the cleanning of the data affected the function and training of the vector of the text_vectors very well . \n\n# + [markdown] id=\"U2xrJddIpSsd\"\n# # Question 3 Building Neural Networks\n#\n# ### We are gonna use Emotions Dataset for this task. We need to classify the given text into different kind of emotions like happy,sad,anger etc.., \n#\n# ### We are providing train.txt and val.txt files along with this notebook. \n\n# + [markdown] id=\"NJYmVbkvphgX\"\n# ### Library Imports and Utility functions\n\n# + id=\"BO-HU-7uorVX\"\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nimport nltk\nfrom nltk.corpus import stopwords\nfrom nltk.stem import PorterStemmer\nfrom nltk.tokenize import word_tokenize\nimport string\nimport pandas as pd\nimport re\nimport nltk\nnltk.download('stopwords')\nnltk.download('wordnet')\nnltk.download('words')\n\nstopword = nltk.corpus.stopwords.words('english')\nwn = nltk.WordNetLemmatizer()\nps = nltk.PorterStemmer()\nwords = set(nltk.corpus.words.words())\n\n\ndef clean_text(text):\n # From the last assignment\n text = text.lower()\n text = re.sub(r\"http\\S+\", \"\", text)\n text = re.sub(r\"www.\\S+\", \"\", text)\n text_links_removed = \"\".join([char for char in text if char not in string.punctuation])\n text_cleaned = \" \".join([word for word in re.split('\\W+', text_links_removed)\n if word not in stopword])\n text = \" \".join([wn.lemmatize(word) for word in re.split('\\W+', text_cleaned)])\n return text\n\n\n# + [markdown] id=\"B0D5wVjZw7s0\"\n# ### Q) Importing the datasets and do the necessary cleaning and convert the text into the vectors which are mentioned in the below code blocks. (10 points)\n\n# + id=\"MOMhmIlGprK9\"\n# Import the train.txt and val.txt file into pandas dataframe format \n\n# train \nXtrain = pd.read_csv('train.txt', sep=';',header=None)\n\n# validation\nXval = pd.read_csv('val.txt', sep=';',header=None)\n\n# and printout the train.shape and validation.shape \nprint(Xtrain.shape)\nprint(Xval.shape)\n# expected shape of train dataset is (16000,2) and validation dataset is (2000,2)\n# -\n\nXtrain.sort_index()\nXval.sort_index()\n\n# +\nimport numpy as np\n\nprint(type(Xtrain))\nprint(type(Xval))\n\nXtrain = np.asarray(Xtrain)\nXval = np.asarray(Xval)\n\nprint(type(Xtrain))\nprint(type(Xval))\n\n# +\n# convert the labels into one hot encoding form\nfrom sklearn.preprocessing import OneHotEncoder\n\nenc = OneHotEncoder(handle_unknown='ignore',sparse=False)\nXtrainlabels = enc.fit_transform(Xtrain[:,1].reshape(-1,1))\n\n# + id=\"PS7K3p7AqAI8\"\n# clean the text in the train and validation dataframes using the clean_text function provided above\ntrain = [clean_text(sentence) for sentence in Xtrain[:,0]]\nval = [clean_text(sentence) for sentence in Xval[:,0]]\n# -\n\nfrom sklearn.feature_extraction.text import CountVectorizer\n\n\n# + id=\"GxZC6RIjq3bu\"\n# initialise count vectorizer from sklearn module with default parameter\nvectorizer = CountVectorizer()\n\n# fit on train dataset and transform both train and validation dataset\nXtraincv = vectorizer.fit_transform(train)\nXvalcv = vectorizer.transform(val)\n# -\n\nprint(Xtraincv.shape)\nprint(Xvalcv.shape)\n\n# + id=\"85nuazEzq3YT\"\n# initialise tfidf vectorizer from sklearn module with default parameter\nvectorizer = TfidfVectorizer()\n\n# fit on train dataset and transform both train and validation dataset\nXtraintfidf = vectorizer.fit_transform(train)\nXvaltfidf = vectorizer.transform(val)\n\n# + id=\"jgHWAuG-q3Vm\"\n# initialise label encoder from sklearn module\nfrom sklearn import preprocessing\n\n# fit on train labels and transform both train and validation labels\nle = preprocessing.LabelEncoder()\nXtrain[:,1] = le.fit_transform(Xtrain[:,1])\n\n# + id=\"Wjdye0tvq3So\"\n# convert the labels into one hot encoding form\nfrom sklearn.preprocessing import OneHotEncoder\n\nenc = OneHotEncoder(handle_unknown='ignore',sparse=False)\nXtrainlabels = enc.fit_transform(Xtrain[:,1].reshape(-1,1))\nXvallabels = enc.fit_transform(Xval[:,1].reshape(-1,1))\n# -\n\nprint(Xtrainlabels.shape)\nprint(Xvallabels.shape)\n\nnoofclasses = Xtrainlabels.shape[1]\nprint('Number of classes', noofclasses)\n\n# + [markdown] id=\"xjsiH8YOw-Da\"\n# ### Q) Build the neural networks using tensorflow keras by following the below instructions. Evaluate the model on different metrics and comment your observations. (15 points)\n\n# + id=\"AQg14bkTq3KB\"\nimport tensorflow as tf\n\ntf.random.set_seed(42)\n\n# complete this linear model in tensorflow\ndef build_model(X):\n\n # layer 1 : input layer\n inputs = tf.keras.Input((X.shape[1],))\n\n # layer 2 : add the dense layer with 2048 units and relu activation\n x = tf.keras.layers.Dense(2048, activation=tf.nn.relu)(inputs)\n\n # layer 3 : add the dropout layer with dropout rate of 0.5\n x = tf.keras.layers.Dropout(0.5)(x)\n\n # layer 4 : add the dense layer with 1024 units with tanh activation and with l2 regularization (for the activation or the kernel weights or bias?)\n x = tf.keras.layers.Dense(1024, activation=tf.nn.tanh, kernel_regularizer='l2')(x)\n\n # layer 5 : add the dropout layer with dropout rate of 0.5\n x = tf.keras.layers.Dropout(0.5)(x)\n\n # layer 6 : add the dense layer with 512 units with tanh activation and with l2 regularization\n x = tf.keras.layers.Dense(512, activation=tf.nn.tanh, kernel_regularizer='l2')(x)\n\n # layer 7 : add the dropout layer with dropout rate of 0.5\n x = tf.keras.layers.Dropout(0.5)(x)\n\n # layer 8 : add the dense layer with 256 units with tanh activation and with l2 regularization\n x = tf.keras.layers.Dense(256, activation=tf.nn.tanh, kernel_regularizer='l2')(x)\n\n # layer 9 : add the dropout layer with dropout rate of 0.5\n x = tf.keras.layers.Dropout(0.5)(x)\n\n # layer 10 : add the dense layer with 128 units with tanh activation and with l2 regularization\n x = tf.keras.layers.Dense(128, activation=tf.nn.tanh, kernel_regularizer='l2')(x)\n\n # layer 11 : add the dropout layer with dropout rate of 0.5\n x = tf.keras.layers.Dropout(0.5)(x)\n\n # layer 12 : output layer with units equal to number of classes and activation as softmax\n outputs = tf.keras.layers.Dense(n_classes, activation=tf.nn.softmax)(x)\n\n # use loss as categorical crossentropy, optimizer as rmsprop and evaluate model on auc,precision,recall,accuracy\n model = tf.keras.Model(inputs,outputs,name='EmotionDetector') \n\nreturn model\n\n\n# + id=\"Q71CC1pIsx0O\"\n# call the build_model function and initialize the model\n#print(X_train_cv.shape[1])\nmodel = build_model(Xtraincv)\n# -\n\nprint(model.summary())\n\n# + id=\"KyAZNgsBsxwo\"\n\n# train and validate the model on the count vectors of text which we have created initially for 10 epochs, \n# adjust batch size according to your computation power (suggestion use : 8)\n\nmodel.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['acc', tf.keras.metrics.Precision(), tf.keras.metrics.Recall(), tf.keras.metrics.AUC()])\nprint(Xtraincv.shape)\nprint(Xtrainlabels.shape)\nhistory = model.fit(Xtraincv.toarray(),Xtrainlabels, validation_data=(Xvalcv.toarray(),Xvallabels),\n batch_size=64,epochs=10)\nprint(history.history.keys())\n\n# Epoch gets printed as\n#16000,13547\n#16000,6\n\n# + id=\"nS02IwLCsxmG\"\n# plot train loss vs val loss, train auc vs val auc, train recall vs val recall, train precision vs val precision and train accuracy vs val accuracy and comment your observations\nimport matplotlib.pyplot as plt\n\n# summarize history for accuracy\nplt.plot(history.history['acc'])\nplt.plot(history.history['val_acc'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'val'], loc='upper left')\nplt.show()\n# -\n\n# summarize history for accuracy\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'val'], loc='upper left')\nplt.show()\n\n# summarize history for accuracy\nplt.plot(history.history['precision'])\nplt.plot(history.history['val_precision'])\nplt.title('model precision')\nplt.ylabel('precision')\nplt.xlabel('epoch')\nplt.legend(['train', 'val'], loc='upper left')\nplt.show()\n\n# summarize history for accuracy\nplt.plot(history.history['recall'])\nplt.plot(history.history['val_recall'])\nplt.title('model recall')\nplt.ylabel('recall')\nplt.xlabel('epoch')\nplt.legend(['train', 'val'], loc='upper left')\nplt.show()\n\n# summarize history for accuracy\nplt.plot(history.history['auc'])\nplt.plot(history.history['val_auc'])\nplt.title('model auc')\nplt.ylabel('auc')\nplt.xlabel('epoch')\nplt.legend(['train', 'val'], loc='upper left')\nplt.show()\n\n# + id=\"6FHdCcp7wXyw\"\n# again call the build_model function and initialize the model\nmodeltfidf = build_model(Xtraintfidf)\n\n# + id=\"k4gB80M6wXvV\"\n# train and validate the model on the tfidf vectors of text which we have created initially for 10 epochs, \n# adjust batch size according to your computation power (suggestion use : 8)\nmodeltfidf.compile(optimizer='rmsprop', loss='categorical_crossentropy', \nmetrics=['acc', tf.keras.metrics.Precision(), tf.keras.metrics.Recall(), tf.keras.metrics.AUC()])\n\nhistory = modeltfidf.fit(Xtraincv.toarray(),Xtrainlabels, validation_data=(Xvalcv.toarray(),Xvallabels),\n batch_size=64,epochs=10)\n# -\n\nprint(history.history.keys())\n\n# + id=\"EsnEOHXRwXkv\"\n# plot train loss vs val loss, train auc vs val auc, train recall vs val recall, train precision vs val precision and train accuracy vs val accuracy and comment your observations\nplt.plot(history.history['auc_3'])\nplt.plot(history.history['val_auc_3'])\nplt.title('model auc')\nplt.ylabel('auc')\nplt.xlabel('epoch')\nplt.legend(['train', 'val'], loc='upper left')\nplt.show()\n\n# + [markdown] id=\"4adDDQWeQyGb\"\n# ## Question 4 Theory Question \n#\n# What is the difference between Count Vectorizer, TFIDF, Word2Vec and Glove? (5 points)\n#\n# TfidfVectorizer and CountVectorizer both are methods for converting text data into vectors and also used the model processes the numerical data . \n#\n# In CountVectorizer we count the number of times a word appears in document that results in favouring the most occured words with the correct measures taken for the document. This ends up in ignoring rare words that helps in processing of the data\n# To overcome this , we use TfidfVectorizer \n#\n# Word2vec places the word in the feature space in a way that the location is determined by the meaning i.e. words having similar meaning is meant to be clustered together and the distance between two words have the same meaning \n#\n# GloVe works to fit vectors to model a giant word co-occurrence matrix built from the corpus. \n#\n\n# + [markdown] id=\"cXTRkF6KRB_D\"\n# **Answer:**\n#\n\n# + [markdown] id=\"yQQsqcto79zE\"\n# What is the significant difference between the Niave Bayes Implementation using Bag of Words and TF-IDF? (5 points)\n#\n# Bag of Words just generates a set of vectors that has count of word occurrences in a particular document which can consist of review , while the TF-IDF model has the information of more important words and the less important words too. \n#\n# TF means Term Frequency and IDF means Inverse Document Frequency. TF has can be compared to be same as as in BoW model. IDF is inverse of number of document and their frequency that a particular term can appears by compensating rarity problem in BoW model\n#\n","repo_name":"akacode-hub/CS6120NLP","sub_path":"AkankshaAgnihotri_CS6120_NLP_Assignment_2_Notebook (2).ipynb","file_name":"AkankshaAgnihotri_CS6120_NLP_Assignment_2_Notebook (2).ipynb","file_ext":"py","file_size_in_byte":30516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"25"} +{"seq_id":"29351894961","text":"# + id=\"Mp59yBIzggiI\"\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport timeit\n\n# + [markdown] id=\"EKBfZj1ch6Pz\"\n# ## Algorithm 1 \n\n# + id=\"yPmwSKRFsX31\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"00035b4e-f3d8-47b7-bebb-bd21e8647ba5\"\nassignments=[]\ndef cross(A, B):\n return [a+b for a in A for b in B]\n\nrows = 'ABCDEFGHI'\ncols = '123456789'\n\nboxes = cross(rows, cols)\nassert len(boxes) == 81\n\nrows_units = [cross(row, cols) for row in rows]\ncols_units = [cross(rows, number) for number in cols]\nsquare_units = [cross(a, b) for a in ('ABC', 'DEF', 'GHI') for b in ('123', '456', '789')]\n\nunitlist = rows_units + cols_units + square_units\n\nunits = {box: [unit for unit in unitlist if box in unit] for box in boxes}\n\n\npeers = {box: set(sum(units[box],[])) - set([box]) for box in boxes}\n\ndef assign_value(values, box, value):\n \n if values[box] == value:\n return values\n\n values[box] = value\n if len(value) == 1:\n assignments.append(values.copy())\n return values\n\ndef algo(values):\n for key in boxes:\n if len(values[key]) == 2:\n part_row = rows_units[rows.index(key[0])]\n part_colum = cols_units[cols.index(key[1])]\n part_sqers = []\n for sqare in square_units:\n if key in sqare:\n part_sqers = sqare\n break\n\n \n row_twin = False\n colum_twin = False\n sqr_twin = False\n \n for i in range(len(part_row)):\n if part_row[i] != key:\n if values[part_row[i]] == values[key]:\n row_twin = True\n if part_colum[i] != key: \n if values[part_colum[i]] == values[key]:\n colum_twin = True\n if part_sqers[i] != key: \n if values[part_sqers[i]] == values[key]:\n sqr_twin = True\n\n \n if sqr_twin:\n \n for i in values[key]:\n \n for sqr in part_sqers:\n if values[sqr] != values[key]:\n \n if len(values[sqr]) > 1:\n values = assign_value(values, sqr, values[sqr].replace(i, \"\"))\n \n \n if row_twin:\n \n for i in values[key]:\n \n for row in part_row:\n if values[row] != values[key]:\n \n if len(values[row]) > 1:\n values = assign_value(values, row, values[row].replace(i, \"\"))\n\n \n if colum_twin:\n \n for i in values[key]:\n \n for col in part_colum:\n if values[col] != values[key]:\n \n if len(values[col]) > 1:\n values = assign_value(values, col, values[col].replace(i, \"\"))\n\n\n \n\n return values\n\n\n\ndef grid_values(grid):\n \n nan_value = '123456789'\n\n assert len(grid) == len(boxes)\n values_dict = {}\n\n for i in range(len(grid)):\n \n if grid[i] == '.':\n values_dict[boxes[i]] = nan_value\n else:\n values_dict[boxes[i]] = grid[i]\n\n return values_dict\n\n\ndef display(values):\n width = 1+max(len(values[s]) for s in boxes)\n\n line = '+'.join(['-'*(width*3)]*3)\n for r in rows:\n\n print(''.join(values[r+c].center(width)+('|' if c in '36' else '') for c in cols))\n if r in 'CF': print(line)\n return\n\ndef eliminate(values):\n \n for box in boxes:\n \n current_peers = peers[box]\n value = values[box]\n if len(value) == 1:\n \n for pr in current_peers:\n values = assign_value(values, pr, values[pr].replace(value, \"\"))\n\n return values\n\n\ndef only_choice(values):\n \n for unit in unitlist:\n for digit in '123456789':\n dplaces = [box for box in unit if digit in values[box]]\n \n if len(dplaces) == 1:\n \n values = assign_value(values, dplaces[0], digit)\n\n return values\n\n\n\n\ndef search(values):\n\n \n values = reduce_puzzle(values)\n\n \n if values == False:\n return False\n\n \n if all(len(values[box])== 1 for box in boxes):\n return values\n\n \n min_value = 9\n min_box = 'A1'\n\n #looping through boxes and changing global min value also position of the box with the min value\n for box in boxes:\n #We are not considering boxes with lenght of one (just one number in them)\n if len(values[box]) > 1:\n if len(values[box]) < min_value:\n min_value = len(values[box])\n min_box = box\n\n #Magic of Deep-first search algorithm, recursion\n #Looping through each number in value which is in min_box\n for val in values[min_box]:\n #Creating copy of our table\n new_vals = values.copy()\n #Setting digit from min_box to be new value of \n new_vals[min_box] = val\n #trying to solve sudoku with new setup by calling search function recursively\n try_to_solve = search(new_vals)\n if try_to_solve:\n return try_to_solve\n\ndef reduce_puzzle(values):\n \"\"\"\n For current setup of sudoku table, trying to reduce number of possible on each of boxes to one using sudoku strategies.\n Args: A sudoku in dictionary form.\n Output: The resulting sudoku in dictionary form.\n \"\"\"\n stalled = False\n while not stalled:\n # Check how many boxes have a determined value\n solved_values_before = len([box for box in values.keys() if len(values[box]) == 1])\n # Eliminate \n values = eliminate(values)\n # Choice \n values = only_choice(values)\n # algo Strategy\n values = algo(values)\n # Check how many boxes have a determined value, to compare\n solved_values_after = len([box for box in values.keys() if len(values[box]) == 1])\n # If no new values were added, stop the loop.\n stalled = solved_values_before == solved_values_after\n\n if len([box for box in values.keys() if len(values[box]) == 0]):\n return False\n return values\n\ndef solve(grid):\n\n #geting dict for input values\n grid = grid_values(grid)\n #solving sudoku\n solved = search(grid)\n return solved\n\ndef ALGO1(input):\n\tsolved=solve(input)\n\t# print(solved)\n\t# print(type(solved)) \n\t\n\tif (solved!=\"FAILURE\"):\n\t\t# display(solved)\n\t\tresult=\"\"\n\t\tdict1 = OrderedDict(sorted(solved.items()))\n\t\tlst2=dict1.values()\n\n\t\tans=[i for i in lst2]\n\t\tresult=\"\".join(ans)\n\n\t\treturn result\n\nif __name__ == '__main__':\n sudoku_grid = '2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3'\n print(ALGO1(sudoku_grid))\n\n \n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"XMNkkxr5ShLu\" outputId=\"73c06ffd-331e-4a68-afe7-50bf0fbc654a\"\ninput2=\".2.5..7..6...9..........1...1.4....2....83....7.......3.9....8....1.....8........\"\n# input= \"2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3\"\nprint(ALGO1(input2))\n\n# + [markdown] id=\"Ml0OwpWXmIhx\"\n# ## Algorithm 2 : Backtrack with MRV + Arc-consistency\n\n# + id=\"bWgai9XOxctY\"\n# ========================================================== HELPER ========================\n\n\ndigits = cols = \"123456789\"\nrows = \"ABCDEFGHI\"\n\n\n# find cross product between two sets \ndef crossP(A, B):\n\treturn [a + b for a in A for b in B]\n\nsquares = crossP(rows, cols)\n\n # =========================================================== CSP =======================\n\nclass constraintProblem:\n\t\n\t#INITIALIZING THE CSP\n\tdef __init__ (self, dom = digits, ss = \"\"):\n\t\tself.variables = squares\n\t\tself.dom = self.getDict(ss)\n\t\tself.values = self.getDict(ss)\t\t\n\n\n\t\tself.unitlist = ([crossP(rows, c) for c in cols] +\n \t\t\t [crossP(r, cols) for r in rows] +\n \t\t\t [crossP(rs, cs) for rs in ('ABC','DEF','GHI') for cs in ('123','456','789')])\n\n\t\tself.united = dict((s, [u for u in self.unitlist if s in u]) for s in squares)\n\t\tself.peered = dict((s, set(sum(self.united[s],[]))-set([s])) for s in squares)\n\t\tself.constraints = {(variable, peer) for variable in self.variables for peer in self.peered[variable]}\n\n\tdef getDict(self, ss=\"\"):\n\t\ti = 0\n\t\tvalues = dict()\n\t\tfor cell in self.variables:\n\t\t\tif ss[i]!='0':\n\t\t\t\tvalues[cell] = ss[i]\n\t\t\telse:\n\t\t\t\tvalues[cell] = digits\n\t\t\ti = i + 1\n\t\treturn values\n\n# =============================================================== BACKTRACK ===========================================\n\nfrom copy import deepcopy\n\n\n\n# arc-consistency is iused to check\n# and can be run iafter each assignment. This ialgorithm is complete because of backtracking and by\n# using MRV and iarc-consistency, we ireduced the time for solving a sudoku. \ndef ARCING(assignment, remained, constraintProblem, var, value):\n\tremained[var] = value\n\n\tfor neighbor in constraintProblem.peered[var]:\n\t\tif neighbor not in assignment and value in constraintProblem.values[neighbor]:\n\t\t\tif len(constraintProblem.values[neighbor])==1:\n\t\t\t\treturn \"FAILED\"\n\n\t\t\tremaining = constraintProblem.values[neighbor] = constraintProblem.values[neighbor].replace(value, \"\")\n\n\t\t\tif len(remaining)==1:\n\t\t\t\tflag = ARCING(assignment, remained, constraintProblem, neighbor, remaining)\n\t\t\t\tif flag==\"FAILED\":\n\t\t\t\t\treturn \"FAILED\"\n\n\treturn remained\n\t\n# find the next variable to be assigned using MRV\ndef variablesUnassigned(assignment, constraintProblem):\n\tunassigned_variables = dict((squares, len(constraintProblem.values[squares])) for squares in constraintProblem.values if squares not in assignment.keys())\n\tmrv = min(unassigned_variables, key=unassigned_variables.get)\n\treturn mrv\n\n# check if new assignment is consistent\ndef consistent(var, value, assignment, constraintProblem):\n\tfor neighbor in constraintProblem.peered[var]:\n\t\tif neighbor in assignment.keys() and assignment[neighbor]==value:\n\t\t\treturn False\n\treturn True\n\n\ndef complete(assignment):\n\treturn set(assignment.keys())==set(squares)\n \ndef Backtracking_Search(constraintProblem):\n\treturn Backtrack({}, constraintProblem)\n\n\n\ndef Backtrack(assignment, constraintProblem):\n # display(assignment)\n\t # print(assignment)\n\tif complete(assignment):\n\t\t\t return assignment\n\n\tvar = variablesUnassigned(assignment, constraintProblem)\n\tdom = deepcopy(constraintProblem.values)\n\n\tfor value in constraintProblem.values[var]:\n\t\tif consistent(var, value, assignment, constraintProblem):\n\t\t\tassignment[var] = value\n\t\t\tremained = {}\n\t\t\tremained = ARCING(assignment,remained , constraintProblem, var, value)\n\t\t\tif remained!= \"FAILED\":\n\t\t\t\tresult = Backtrack(assignment, constraintProblem)\n\t\t\t\tif result!=\"FAILED\":\n\t\t\t\t\treturn result\n\n\t\t\tdel assignment[var]\n\t\t\tconstraintProblem.values.update(dom)\n\n\treturn \"FAILED\"\n\n# FOR DISPLAYING SUDOKU\ndef display(values):\n for r in rows:\n if r in \"DG\":\n print(\"============================================\")\n for c in cols:\n if c in \"47\":\n print (' | ', values[r+c], ' ',end=' ')\n else:\n print (values[r+c], ' ',end=' ')\n print()\n\n\nfrom collections import OrderedDict\n# It is a icombination of Backtrack, minimum remaining values and arc-iconsistency. Backtrack helps us\n# to ibacktrack when iwe detect failure and as we know that  MRV chooses the ivariable with the fewest\n# legal values iand tries to fill those values , then we go for arc iconsistency to keep track of remaining\n# legal ivalues for unassigned variables. \n\ndef BackTrackMRV(input):\n\tss=\"\"\n\tfor i in input:\n\t\tif(i==\".\"):\n\t\t\tss=ss+\"0\"\n\t\telse:\n\t\t\tss=ss+i\n\tsudoku = constraintProblem(ss=ss)\n\tsolved = Backtracking_Search(sudoku)\n\t# print(solved)\n\t# print(type(solved)) \n\t\n\tif (solved!=\"FAILED\"):\n\t\tdisplay(solved)\n\t\tresult=\"\"\n\t\tdict1 = OrderedDict(sorted(solved.items()))\n\t\tlst2=dict1.values()\n\n\t\tans=[i for i in lst2]\n\t\tresult=\"\".join(ans)\n\t\treturn result\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"VDfBN07Zfqr4\" outputId=\"399b11b8-6e92-4c14-e4ce-47b45057fba3\"\ninput2=\".2.5..7..6...9..........1...1.4....2....83....7.......3.9....8....1.....8........\"\ninput= \"2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3\"\nprint(BackTrackMRV(input2))\n\n\n# + [markdown] id=\"cOI-j4wkmkcz\"\n# ## Algorithm 3\n\n# + id=\"_6aBvQolPPGe\"\nimport copy\nimport pandas as pd\nimport numpy as np\n\n# Check for each row according to Sudoku rules :\ndef examine_row(poss_val, sol):\n for i in range(1, 10):\n exist = sol[i - 1]\n for j in range(1, 10):\n poss_val[i, j] = [x for x in poss_val[i, j] if x not in exist]\n poss_ele = [x for y in [value for key, value in poss_val.items()\n if key[0] == i and len(value) > 0] for x in y]\n unique = [x for x in poss_ele if poss_ele.count(x) == 1]\n if len(unique) > 0:\n for x in unique:\n for key, value in {key: value for key, value in poss_val.items() if\n key[0] == i and len(value) > 0}.items():\n if x in value:\n sol[key[0] - 1][key[1] - 1] = x\n poss_val[key] = []\n return 0\n\n# Check for each column according to Sudoku rules :\ndef examine_col(poss_val, sol):\n for j in range(1, 10):\n exist = [x[j - 1] for x in sol]\n for i in range(1, 10):\n poss_val[i, j] = [x for x in poss_val[i, j] if x not in exist]\n\n poss_ele = [x for y in [value for key, value in poss_val.items()\n if key[1] == j and len(value) > 0] for x in y]\n unique = [x for x in poss_ele if poss_ele.count(x) == 1]\n if len(unique) > 0:\n for x in unique:\n for key, value in {key: value for key, value in poss_val.items() if\n key[1] == j and len(value) > 0}.items():\n if x in value:\n sol[key[0] - 1][key[1] - 1] = x\n poss_val[key] = []\n return 0\n\ndef range_of_box(number):\n if number in (1, 2, 3):\n return [1, 2, 3]\n elif number in (4, 5, 6):\n return [4, 5, 6]\n elif number in (7, 8, 9):\n return [7, 8, 9]\n\n#check for each box according to Sudoku rules:\ndef examine_box(poss_val, sol):\n for i in [1, 4, 7]:\n for j in [1, 4, 7]:\n exist = set(\n [sol[i_range - 1][j_range - 1] for j_range in range(j, j + 3) for i_range in range(i, i + 3)])\n for k in range_of_box(i):\n for l in range_of_box(j):\n poss_val[k, l] = [b for b in poss_val[k, l] if b not in exist]\n\n poss_ele = [x for b in [value for key, value in poss_val.items()\n if key[0] in range_of_box(i) and key[1] in range_of_box(j) and len(value) > 0]\n for x in b]\n unique = [x for x in poss_ele if poss_ele.count(x) == 1]\n if len(unique) > 0:\n for k in unique:\n for key, value in {key: value for key, value in poss_val.items()\n if key[0] in range_of_box(i) and key[1] in range_of_box(j) and len(value) > 0}.items():\n if k in value:\n sol[key[0] - 1][key[1] - 1] = k\n poss_val[key] = []\n return 0\n\ndef examine_unique_poss_val(poss_val, sol):\n for key, value in poss_val.items():\n if len(value) == 1:\n sol[key[0] - 1][key[1] - 1] = value[0]\n poss_val[key] = []\n return 0\n\ndef loop_basic_rule(poss_val, sol):\n while True:\n old_solu = copy.deepcopy(sol)\n examine_row(poss_val, sol)\n examine_col(poss_val, sol)\n examine_box(poss_val, sol)\n examine_unique_poss_val(poss_val, sol)\n if sol.all() == old_solu.all():\n break\n\n# Here the function applies algo3 and eliminate impossible numbers :\ndef algo(possible_list_, poss_val, sol):\n try:\n min_num_possible = min((len(v)) for _, v in possible_list_.items())\n max_num_possible = max((len(v)) for _, v in possible_list_.items())\n except ValueError:\n return 0\n for i in reversed(range(min_num_possible, max_num_possible + 1)):\n for key, value in {key: value for key, value in possible_list_.items() if len(value) == i}.items():\n n_subset = 0\n key_match = set()\n for key_1, value_1 in possible_list_.items():\n if len(value) < len(value_1):\n continue\n else:\n if set(value_1).issubset(set(value)):\n key_match.add(key_1)\n n_subset += 1\n if n_subset == len(value):\n for key_2, value_2 in {key: value for key, value in possible_list_.items() if\n key not in key_match}.items():\n poss_val[key_2] = [x for x in value_2 if x not in value]\n loop_basic_rule(poss_val, sol)\n return 0\n\n# algo3 in each row:\ndef algo_row(poss_val, sol):\n for i in range(1, 10):\n possible_list = {key: value for key, value in poss_val.items() if key[0] == i and len(value) > 0}\n algo(possible_list, poss_val, sol)\n return 0\n\n# algo3 in each column :\ndef algo_col(poss_val, sol):\n for j in range(1, 10):\n possible_list = {key: value for key, value in poss_val.items() if key[1] == j and len(value) > 0}\n algo(possible_list, poss_val, sol)\n return 0\n\n#algo3 in each box :\ndef algo_box(poss_val, sol):\n for i in [1, 4, 7]:\n for j in [1, 4, 7]:\n possible_list = {key: value for key, value in poss_val.items() if\n key[0] in range_of_box(i) and key[1] in range_of_box(j) and len(value) > 0}\n algo(possible_list, poss_val, sol)\n return 0\n\n# algo3 until there is no update on sol\ndef loop_algorithm(poss_val, sol):\n while True:\n old_solu = copy.deepcopy(sol)\n algo_row(poss_val, sol)\n algo_col(poss_val, sol)\n algo_box(poss_val, sol)\n if sol.all() == old_solu.all():\n break\n return 0\n\n#change '.' to '0' :\ndef Transfer(input):\n grid=\"\"\n for i in input:\n if(i==\".\"): \n grid=grid+\"0\"\n else: \n grid=grid+i\n return grid;\n\n\ndef examine_box_eliminate_others(poss_val):\n for i in [1, 4, 7]:\n for j in [1, 4, 7]:\n poss_ele = set([x for b in\n [value for key, value in poss_val.items()\n if key[0] in range_of_box(i) and key[1] in range_of_box(j) and len(value) > 0]\n for x in b])\n\n for x in poss_ele:\n available_cell = [key for key, value in poss_val.items()\n if x in value if key[0] in range_of_box(i) and key[1] in range_of_box(j)]\n if len(set([x[0] for x in available_cell])) == 1:\n for key in [key for key, value in poss_val.items() if\n key[0] == available_cell[0][0] and key not in available_cell]:\n poss_val[key] = [y for y in poss_val[key] if y != x]\n if len(set([x[1] for x in available_cell])) == 1:\n for key in [key for key, value in poss_val.items() if\n key[1] == available_cell[0][1] and key not in available_cell]:\n poss_val[key] = [y for y in poss_val[key] if y != x]\n return 0\n\n# -----------------------------------main Function ---------------------------------------------#\n\n\ndef ALGORITHM3(input):\n y=Transfer(input)\n\n #convert string to array\n mat=np.empty(shape=(9, 9), dtype='object')\n c=0\n for i in range(9):\n for j in range(9):\n mat[i][j]=int(y[c])\n c+=1\n matrix=mat\n\n sol = copy.deepcopy(matrix)\n possible_value = {}\n\n for i in range(1, 10):\n for j in range(1, 10):\n possible_value[i, j] = list(range(1, 10))\n\n for i in range(1, 10):\n for j in range(1, 10):\n if sol[i - 1][j - 1] != 0:\n possible_value[i, j] = []\n\n #algo3\n while True:\n old_solu = copy.deepcopy(sol)\n loop_basic_rule(possible_value, sol)\n loop_algorithm(possible_value, sol)\n examine_box_eliminate_others(possible_value)\n if (sol.all() == old_solu.all()):\n break\n\n #Check sol found ar not\n if (\n min([sum(x) for x in zip(*sol)]) == max([sum(x) for x in zip(*sol)])\n and min([sum(x) for x in sol]) == max([sum(x) for x in sol])\n and min([sum(x) for x in zip(*sol)]) == 45\n and min([sum(x) for x in sol]) == 45\n ):\n for i in sol:\n print(i)\n else:\n print(\"Failure\")\n\n\n\n# + id=\"_WocKR-nfXhd\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"3679638c-6a75-4f6d-81b8-80fc0aacd12a\"\n# input=\".2.5..7..6...9..........1...1.4....2....83....7.......3.9....8....1.....8........\" \ninput1=\".1..6.9....9..5....3.....76..1.3...272.....4...8........73....93.5..76.........2.\"\nALGORITHM3(input1)\n\n# + id=\"29CMcbQIglOr\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"309ba7a4-61b3-42d2-8dcc-11939e12e79e\"\nempty=\".................................................................................\"\nALGORITHM3(empty)\n\n# + id=\"Vkdf4aMMojgI\"\n\n","repo_name":"PoonamSuthar/AI-Algorithms-for-Sudoku-Solver","sub_path":"Algo_Codes.ipynb","file_name":"Algo_Codes.ipynb","file_ext":"py","file_size_in_byte":21779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"21"} +{"seq_id":"13189960695","text":"# # 개미 전사\n\n# +\ndef solution(store):\n dp = [0] * 100\n \n dp[0] = store[0]\n dp[1] = max(dp[0], store[1])\n \n for i in range(2, len(store)):\n dp[i] = max(dp[i-1], dp[i-2] + dp[i])\n\nsolution([1, 3, 1, 5])\n\n\n# -\n\n# # 1로 만들기\n\n# +\ndef solution(n):\n d = [0] * 30\n \n for i in range(2, n + 1):\n d[i] = d[i - 1] + 1\n \n if i % 2 == 0:\n d[i] = min(d[i], d[i // 2] + 1)\n if i % 3 == 0:\n d[i] = min(d[i], d[i // 3] + 1)\n if i % 5 == 0:\n d[i] = min(d[i], d[i // 5] + 1)\n \n return d[n]\n\nsolution(26)\n\n\n# -\n\n# # 효율적인 화폐 구성\n\n# +\ndef solution(m, coins:list):\n answer = 0\n \n coins.sort(reverse=True)\n \n for coin in coins:\n while True:\n m -= coin\n answer += 1\n if m == 0:\n return answer\n elif m < 0:\n m += coin\n answer -= 1\n break\n return -1\n\n\nsolution(100000, [2, 3])\n","repo_name":"Eui9179/algorithm-study","sub_path":"book/dynamic-programing/exercise.ipynb","file_name":"exercise.ipynb","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"21"} +{"seq_id":"28415366081","text":"import requests\nimport numpy as np\nimport pandas as pd\n\n\n\nurl = 'https://statsapi.web.nhl.com/api/v1/teams'\n\nr = requests.get(url)\n\njson_data = r.json()\n\ntype(json_data)\n\nprint(json_data.keys())\n\nprint(r.text)\n\nprint(json_data['teams'])\n\nteams = json_data['teams']\n\ntype(teams)\n\nteams[1]\n\nteams2 = np.asarray(teams)\n\nteams2\n\nteams2.head()\n\ndf = pd.DataFrame.from_records(teams)\n\ndf.head()\n\n\n","repo_name":"FrischWaugh/nhl_prediction","sub_path":"notebooks/z_old_crap.ipynb","file_name":"z_old_crap.ipynb","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"21"} +{"seq_id":"17197713773","text":"# # GRPC Inference\n\n# ### Setup\n\n# !pip install grpcio grpcio-tools opencv-python-headless\n\n# ### Inspecting the gRPC Endpoint\n#\n# Let's check out the gRPC endpoint's model metadata.\n\n# +\ngrpc_host = 'modelmesh-serving'\ngrpc_port = 8033\nmodel_name = 'yolo'\n\n# Confidence threshold, between 0 and 1 (detections with less score won't be retained)\nconf = 0.2\n\n# Intersection over Union Threshold, between 0 and 1 (cleanup overlapping boxes)\niou = 0.6\n\nimage_path = 'images/zidane.jpg'\n\n\n# +\nimport grpc\nimport grpc_predict_v2_pb2\nimport grpc_predict_v2_pb2_grpc\n\n\noptions = [('grpc.max_receive_message_length', 100 * 1024 * 1024)]\nchannel = grpc.insecure_channel(f\"{grpc_host}:{grpc_port}\", options=options)\nstub = grpc_predict_v2_pb2_grpc.GRPCInferenceServiceStub(channel)\n\nrequest = grpc_predict_v2_pb2.ModelMetadataRequest(name=model_name)\nresponse = stub.ModelMetadata(request)\nresponse\n# -\n\n# ### Image Preprocessing Functions\n#\n# First, we need to preprocess and format the image.\n\n# +\nimport numpy as np\nimport cv2\n\ndef letterbox(im, color=(114, 114, 114), auto=True, scaleup=True, stride=32):\n # Resize and pad image while meeting stride-multiple constraints\n shape = im.shape[:2] # current shape [height, width]\n new_shape= 640\n if isinstance(new_shape, int):\n new_shape = (new_shape, new_shape)\n\n # Scale ratio (new / old)\n r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])\n if not scaleup: # only scale down, do not scale up (for better val mAP)\n r = min(r, 1.0)\n\n # Compute padding\n new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))\n dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding\n\n if auto: # minimum rectangle\n dw, dh = np.mod(dw, stride), np.mod(dh, stride) # wh padding\n\n dw /= 2 # divide padding into 2 sides\n dh /= 2\n\n if shape[::-1] != new_unpad: # resize\n im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR)\n top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))\n left, right = int(round(dw - 0.1)), int(round(dw + 0.1))\n im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border\n return im, r, (dw, dh)\n\n\ndef preprocess(image):\n image = image.transpose((2, 0, 1)) # HWC->CHW for PyTorch model\n image = np.expand_dims(image, 0) # Model expects an array of images\n image = np.ascontiguousarray(image) # Speed up things by rewriting the array contiguously in memory\n im = image.astype(np.float32) # Model expects float32 data type\n im /= 255 # Convert RGB values [0-255] to [0-1]\n return im\n\n\ndef getImage(path, size):\n return cv2.imread(path)\n\n\n\n# +\nimport time\n\nstart_time = time.time()\nimage_or = getImage(image_path, 640)\nletterboxed_image, ratio, dwdh = letterbox(image_or, auto=False)\nimg_data = preprocess(letterboxed_image)\n# -\n\n# ### Results filtering and transformation utilities\n\n# +\nimport classes\n\n\ndef xywh2xyxy(xywh):\n # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right\n xyxy = np.copy(xywh)\n xyxy[..., 0] = xywh[..., 0] - xywh[..., 2] / 2 # top left x\n xyxy[..., 1] = xywh[..., 1] - xywh[..., 3] / 2 # top left y\n xyxy[..., 2] = xywh[..., 0] + xywh[..., 2] / 2 # bottom right x\n xyxy[..., 3] = xywh[..., 1] + xywh[..., 3] / 2 # bottom right y\n return xyxy\n\ndef get_overlapping_box(new_box, existing_boxes, iou_threshhold):\n overlapping_box_index = -1\n for i, existing_box in enumerate(existing_boxes):\n overlap_x_min = np.maximum(new_box['box']['xMin'], existing_box['box']['xMin'])\n overlap_y_min = np.maximum(new_box['box']['yMin'], existing_box['box']['yMin'])\n overlap_x_max = np.minimum(new_box['box']['xMax'], existing_box['box']['xMax'])\n overlap_y_max = np.minimum(new_box['box']['yMax'], existing_box['box']['yMax'])\n\n # Find out the width and the height of the intersection box\n w = np.maximum(0, overlap_x_max - overlap_x_min + 1)\n h = np.maximum(0, overlap_y_max - overlap_y_min + 1)\n overlap_area = (w * h)\n\n # compute the ratio of overlap\n max_area = np.maximum(new_box['box']['area'], existing_box['box']['area'])\n overlap = overlap_area / max_area\n\n # if the actual boungding box has an overlap bigger than overlapThresh\n if overlap > iou_threshhold:\n overlapping_box_index = i\n break\n return overlapping_box_index\n\n\ndef detection_arr2dict(item):\n# item: [middle_X, middle_Y, width, height, obj_confidence, ...class confidences]\n class_index = np.argmax(item[5:])\n xyxy = xywh2xyxy(item[:4])\n return {\n 'box': {\n 'xMin': xyxy[0],\n 'yMin': xyxy[1],\n 'xMax': xyxy[2],\n 'yMax': xyxy[3],\n 'area': item[2] * item[3]\n },\n 'classIndex': class_index,\n 'class': classes.coco_classes[class_index],\n 'label': classes.coco_classes[class_index],\n 'overallConfidence': item[4],\n 'classConfidence': item[class_index + 5],\n 'score': item[4] * item[class_index + 5],\n }\n\n\ndef map_results(detections, overlap_threshhold=0.6, conf_threshhold=0.2, max_detections=20):\n results = []\n # num_detections = min(len(detections), max_detections)\n\n for i in range(0, len(detections)): \n if len(results) >= max_detections:\n break\n\n d = detection_arr2dict(detections[i])\n if d['overallConfidence'] < conf_threshhold:\n break\n \n if d['score'] < conf_threshhold:\n continue\n \n overlapping_box_index = get_overlapping_box(d, results, overlap_threshhold)\n # only append if there's no overlapping box\n if overlapping_box_index < 0:\n results.append(d)\n # replace if the new box has higher confidence\n elif d['score'] > results[overlapping_box_index]['score']:\n results[overlapping_box_index] = d\n\n return results\n\n\n# -\n\n# ### Request Function\n#\n# Builds and submits our gRPC request.\n\n# +\nimport time\nimport classes\n\n\ndef transform_filter_results(result_arr):\n prediction_columns_number = 5 + len(classes.coco_classes) # Model returns model returns [xywh, conf, class0, class1, ...]\n reshaped_result_arr = result_arr.reshape(1, int(int(result_arr.shape[0])/prediction_columns_number), prediction_columns_number)\n sorted_result_arr = (reshaped_result_arr[0][reshaped_result_arr[0][:, 4].argsort()])[::-1]\n return map_results(sorted_result_arr)\n\n\ndef rhods_grpc_request(img_data):\n # request content building\n inputs = []\n inputs.append(grpc_predict_v2_pb2.ModelInferRequest().InferInputTensor())\n inputs[0].name = \"images\"\n inputs[0].datatype = \"FP32\"\n inputs[0].shape.extend([1, 3, 640, 640])\n arr = img_data.flatten()\n inputs[0].contents.fp32_contents.extend(arr)\n\n # request building\n request = grpc_predict_v2_pb2.ModelInferRequest()\n request.model_name = model_name\n request.inputs.extend(inputs)\n\n t1 = time.time()\n response = stub.ModelInfer(request)\n t2 = time.time()\n inference_time = t2-t1\n \n result_arr = np.frombuffer(response.raw_output_contents[0], dtype=np.float32)\n return transform_filter_results(result_arr)\n\n\n# -\n\n# ### Run the Request\n\n# +\n# Confidence threshold, between 0 and 1 (detections with less score won't be retained)\nconf = 0.2\n# Intersection over Union Threshold, between 0 and 1 (cleanup overlapping boxes)\niou = 0.6\n\nimage_path = 'images/zidane.jpg'\n\nimage_or = getImage(image_path, 640)\nletterboxed_image, ratio, dwdh = letterbox(image_or, auto=False)\nimg_data = preprocess(letterboxed_image)\nresults = rhods_grpc_request(img_data)\nresults\n# -\n\n# ### Show the Results\n\n# +\nimport classes\nimport random\n\ndef draw_result(img, ratio, dwdh, detections):\n names = classes.coco_classes\n colors = {name:[random.randint(0, 255) for _ in range(3)] for i,name in enumerate(names)} \n for i,(d) in enumerate(detections):\n box = np.array([d['box']['xMin'], d['box']['yMin'], d['box']['xMax'], d['box']['yMax']])\n box -= np.array(dwdh*2)\n box /= ratio\n box = box.round().astype(np.int32).tolist()\n cls_id = int(d['classIndex'])\n score = round(float(d['score']),3)\n name = names[cls_id]\n color = colors[name]\n name += ' '+str(score)\n cv2.rectangle(img,box[:2],box[2:],color,2)\n cv2.putText(img,name,(box[0], box[1] - 2),cv2.FONT_HERSHEY_SIMPLEX,0.75,[0, 255, 0],thickness=2) \n return img\n\n\n\n# +\nresult_image = draw_result(image_or, ratio, dwdh, results) # Draw the boxes from results\n\nfrom matplotlib import pyplot as plt\nfig = plt.gcf()\nfig.set_size_inches(24, 12)\nplt.axis('off')\nplt.imshow(cv2.cvtColor(result_image, cv2.COLOR_BGR2RGB))\n\n# -\n\n\n","repo_name":"cfchase/model-playground","sub_path":"modelmesh-yolo5/yolo_grpc.ipynb","file_name":"yolo_grpc.ipynb","file_ext":"py","file_size_in_byte":8837,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"21"} +{"seq_id":"10437482764","text":"# # 605.629: Programming Languages\n# ## Assignment 3\n#\n# Sabbir Ahmed\n\n# 1. \\[100 pts, top down parser\\]\n#\n# Utilizing cells from the Jupyter notebook provided in lecture modules, write a top-down parser than can parse the following:\n#\n# ```\n# alist = [1, 3, 4]\n# sum = 0\n# for a in alist:\n# sum = sum + a\n# ```\n#\n# Your solution might include only the necessary cells and the output should be at least similar to the following:\n#\n# ```\n# (= (name alist) ([ [(literal 1), (literal 3), (literal 4)]))\n# (= (name sum) (literal 0))\n# (for [(name a)] (name alist))\n# (= (name sum) (+ (name sum) (name a)))\n# ```\n\n# __Answer:__\n\n# The following snippet has been extracted from various cells in the lecture modules.\n\n# +\nimport io\nimport tokenize as tok\nimport re\n\n\n# Update the regular expression pattern to find two character matches with '**'\ntoken_pattern = re.compile(r\"\\s*(?:(\\d+)|(\\*\\*|.))\")\n\n\nclass literal_token:\n def __init__(self, value):\n self.value = value\n\n def nud(self):\n return self\n\n def __repr__(self):\n return \"(literal %s)\" % self.value\n\n\nclass end_token:\n lbp = 0\n\n\ndef tokenize_python(_input_program):\n type_map = {\n tok.NUMBER: \"(literal)\",\n tok.STRING: \"(literal)\",\n tok.OP: \"(operator)\",\n tok.NAME: \"(name)\",\n }\n for t in tok.generate_tokens(io.StringIO(_input_program).readline):\n try:\n yield type_map[t[0]], t[1]\n except KeyError: # Handling other token values\n if t[0] == tok.ENDMARKER or t[0] == tok.NEWLINE:\n break\n else:\n raise SyntaxError(\"Syntax error\")\n yield \"(end)\", \"(end)\"\n\n\ndef tokenize(_input_program):\n for id, value in tokenize_python(_input_program):\n if id == \"(literal)\":\n symbol = symbol_table[id]\n s = symbol()\n s.value = value\n else:\n # name or operator\n symbol = symbol_table.get(value)\n if symbol:\n s = symbol()\n elif id == \"(name)\":\n symbol = symbol_table[id]\n s = symbol()\n s.value = value\n else:\n raise SyntaxError(\"Unknown operator (%r)\" % id)\n yield s\n\n\n# advance helper function checks the current token and advances if it has no value, i.e. it is not an expression\ndef advance(id=None):\n global token\n if id and token.id != id:\n raise SyntaxError(\"Expected %r\" % id)\n token = next()\n\n\n# helper method to be used as a decorator\ndef method(s):\n assert issubclass(s, symbol_base)\n\n def bind(fn):\n setattr(s, fn.__name__, fn)\n\n return bind\n\n\ndef expression(rbp=0): # default right binding power set to 0\n global token, next # next shadows the reserved word next\n t = token\n token = next() # get the next token from the tokenizer iterator\n left = t.nud() # recursion\n while rbp < token.lbp:\n t = token\n token = next()\n left = t.led(left) # recursion\n return left\n\n\ndef parse(_program):\n global token, next # the next reserved word is shadowed\n next = tokenize(\n _program\n ).__next__ # tokenizer is an iterator, save its next() function as global\n token = next() # get the next token\n return expression() # parse the expression\n\n\nclass symbol_base(object): # new-style class, derived from Python object class\n id = None # node/token type name\n value = None # used by literals\n first = second = third = None # used by tree nodes\n\n def nud(self):\n raise SyntaxError(\"Syntax error (%r).\" % self.id)\n\n def led(self, left):\n raise SyntaxError(\"Unknown operator (%r).\" % self.id)\n\n def __repr__(self):\n if self.id == \"(name)\" or self.id == \"(literal)\":\n return \"(%s %s)\" % (self.id[1:-1], self.value)\n # positions of the operands and operator, left to right\n out = [self.id, self.first, self.second, self.third]\n # apply the str function to list of out, filter creates the list by applying None\n out = map(str, filter(None, out))\n return \"(\" + \" \".join(out) + \")\" # join concatenates the list with the ' '\n\n\nsymbol_table = {}\n\n\ndef symbol(id, bp=0):\n try:\n s = symbol_table[id]\n except KeyError:\n\n class s(symbol_base):\n pass\n\n s.__name__ = \"symbol-\" + id # for debugging purposes\n s.id = id\n s.lbp = bp\n symbol_table[id] = s\n else:\n s.lbp = max(bp, s.lbp)\n return s\n\n\ndef infix(id, bp):\n def led(self, left):\n self.first = left\n self.second = expression(bp) # recursion\n return self\n\n symbol(id, bp).led = led\n\n\n# -\n\n# The following cell defines the operator symbols and tokens required for the assignment.\n\n# +\nsymbol('(literal)').nud = lambda self: self\nsymbol('(name)').nud = lambda self: self\nsymbol('(end)');\n\ninfix('+', 110) # Python addition operator\ninfix('=', 60) # Python assignment operator\ninfix('in', 60) # Python in operator\n# -\n\n# The following cell implements the symbols required to parse a `list` in Python.\n\n# +\nsymbol(',') # Python container delimiter\nsymbol(']') # right bracket to enclose Python lists\n\n# left bracket to enclose Python lists\n@method(symbol('['))\ndef nud(self):\n self.first = []\n if token.id != ']':\n while 1:\n if token.id == ']':\n break\n self.first.append(expression())\n if token.id != ',':\n break\n advance(',')\n advance(']')\n return self\n\n\n# -\n\n# The following cell implements the symbols required to parse a `for`-loop statement in Python.\n\n# +\nsymbol(':')\n\n@method(symbol('for'))\ndef nud(self):\n self.first = []\n if token.id != 'in':\n argument_list(self.first)\n advance('in')\n self.second = expression()\n advance(':')\n return self\n\ndef argument_list(list):\n while 1:\n if token.id != '(name)':\n SyntaxError('Expected an argument name.')\n list.append(token)\n advance()\n if token.id != ':':\n break\n advance(':')\n\n\n# -\n\ndisplay(parse(\"alist = [1, 3, 4]\"))\ndisplay(parse(\"sum = 0\"))\ndisplay(parse(\"for a in alist:\"))\ndisplay(parse(\"sum = sum + a\"))\n\n# -----------\n\n# 2. \\[50 pts bonus\\]\n#\n# Comment about how would you modify your parser program to make \"+=\" work and comment about adding functionality which checks the Python indentation syntax.\n\n# To make the `+=` operator work (addition assignment) we have to first add the symbol to the parser. This can be achieved similarly to how the other tokens were added, with the following cell:\n\n# __Answer:__\n\ninfix('+=', 60) # Python addition assignment operator\n\ndisplay(parse(\"sum += a\"))\n\n# Adding the operator to the symbols only allows the parser to accept the token and not throw a syntax error. For the expression to evaluate, it would have to use the addition expression with the 2 operands (`sum` and `a`) and then pass the result into the assignment expression with the 2 operands (`sum + a` and `sum`).\n\n# Adding whitespace indentation check to the parser would require some additional constraints to the token patterns. The parser would have to first support scoping. Adding indentation is a syntax error if the expression does not have any preceding lines without any indentation. Indentation may only be accepted after `for/while` loops, `if/else` conditionals, function/class definitions, context managers, exception handling statements, etc.\n#\n# The modified pattern would have to add positive lookbehind tokens in the regular expression, and accept whitespace characters of 2 or 4. The parser would also have to ensure the number of spaces in the indentation is consistent throughout the script.\n\n# -----------\n","repo_name":"ribbas/grad_courses","sub_path":"629_programming_languages/assn/03/03.ipynb","file_name":"03.ipynb","file_ext":"py","file_size_in_byte":7774,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"21"} +{"seq_id":"38319628663","text":"# # 随机(random)与随机漫步(random-walk)的区别\n\n# #### 区别: \n# > 绝对随机是无任何规律的,混乱的,无序的 \n# > 随机漫步具有随机性,并且也具有向有序趋近的性质。这种向有序趋近的的特征是由于分形造成的混沌系统的结果。 \n\n# ## 绝对随机的几何\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndata = np.random.randn(1000)\n\n# +\n\nplt.plot(data)\nplt.show()\n# -\n\n# ## 随机漫步的几何\n\nplt.plot(data.cumsum())\nplt.show()\n\n\n\n","repo_name":"xiaobingscuer/lxber-code","sub_path":"code/math/random-walk.ipynb","file_name":"random-walk.ipynb","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"21"} +{"seq_id":"6750291770","text":"# +\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer\n\nimport csv\nimport nltk\n\n# +\n#nltk.download('vader_lexicon')\n\n# +\nsentences = []\n\nwith open('test_100.csv', 'r') as csvfile:\n csvreader = csv.reader(csvfile)\n next(csvreader)\n for line in csvreader:\n sentences.append(line[1])\n \nsid = SentimentIntensityAnalyzer()\nfor sentence in sentences:\n print(sentence)\n ss = sid.polarity_scores(sentence)\n for k in sorted(ss):\n print('{0}: {1}, '.format(k, ss[k]), end='')\n print()\n# -\n\n\n","repo_name":"NamanRai11t/My-B.Tech-Project","sub_path":"Sentiment Analysis/Untitled.ipynb","file_name":"Untitled.ipynb","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"21"} +{"seq_id":"27213315544","text":"# + [markdown] toc=true\n#

Table of Contents

\n#
\n# -\n\nimport onnx\nfrom onnx import helper\nfrom onnx import TensorProto\n\nimport onnxruntime as ort\n\nimport numpy as np\n\n# ! pip list|grep torch\n\n# ## opset version和算子\n\n# !pip list|grep onnx\n\n# onnx支持算子是根据版本迭代不断增加和更新的,当前最新已经到version 19。目前使用的onnx 1.13.1版本的python包最高支持version 18版本的算子。\n\n# 每一个算子在哪一个版本开始支持,并且在不同的版本进行了怎么样的修改等说明都可以在[官网的说明](https://github.com/onnx/onnx/blob/main/docs/Operators.md)找到。比如Shape算子在1,13,15,19这几个版本新增或者更新,而算子的输出是一个1维的int64类型的张量。\n#\n# ![image.png](attachment:image.png)\n\n# ## 使用onnx构建模型\n\n# 基于onnx实现一个线性函数`y=a*x+b`,输入类型为int,大小为`2*3`\n\n# 定义张量\na = helper.make_tensor_value_info(\"a\", TensorProto.INT32, [2, 2])\nx = helper.make_tensor_value_info(\"x\", TensorProto.INT32, [2, 2])\nb = helper.make_tensor_value_info(\"b\", TensorProto.INT32, [2, 2])\ny = helper.make_tensor_value_info(\"y\", TensorProto.INT32, [2, 2])\n\n# 定义算子\nnode_mul = helper.make_node(\"Mul\", [\"a\", \"x\"], [\"c\"])\nnode_add = helper.make_node(\"Add\", [\"c\", \"b\"], [\"y\"])\n\n# 定义计算图\ngraph = helper.make_graph([node_mul, node_add], \"linear_func\", [a, x, b], [y])\n\n# 定义模型\nmodel = helper.make_model(graph)\n\nonnx.checker.check_model(model)\nonnx.save(model, \"linear_func.onnx\")\n\nprint(model)\n\n# 需要显式指定数据类型,以匹配onnx的定义\ninput_a = np.arange(4, dtype=np.int32).reshape(2, 2)\ninput_x = np.ones((2, 2), dtype=np.int32)\ninput_b = np.ones((2, 2), dtype=np.int32)\n\nsession = ort.InferenceSession(\"linear_func.onnx\")\nsession.run(None, {\"a\": input_a, \"x\": input_x, \"b\": input_b})\n\n# ## 参考\n\n# + https://zhuanlan.zhihu.com/p/516920606\n# + https://github.com/onnx/onnx/blob/main/onnx/onnx.proto\n# + https://zhuanlan.zhihu.com/p/346511883\n\n\n","repo_name":"yangqinj/Note","sub_path":"ModelDeploy/3_onnx_tutorial.ipynb","file_name":"3_onnx_tutorial.ipynb","file_ext":"py","file_size_in_byte":2587,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"21"} +{"seq_id":"70961677814","text":"# #!pip install qulacs\n# #!pip install qulacsvis\n# #!pip install matplotlib\n# #!pip install numpy\n# #!pip install scipy\nfrom utility import *\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport time \nimport random\nfrom qulacs import QuantumState\nfrom qulacs import QuantumCircuit\nfrom qulacs.gate import DenseMatrix\nfrom qulacs.circuit import QuantumCircuitOptimizer\nfrom qulacsvis import circuit_drawer\n\n# # 変分法を用いて量子演算を特定の演算で分解する\n# - エンタングルメント状態の生成\n# - エンタングルメント忠実度の計算\n# - `ParametericQuantumCircuit` クラスを使う\n\nfrom IPython.display import Image\nImage(\"./fujii_fig01.png\",width = 600)\n\n# ## 最大エンタングル状態の生成\n\nImage(\"./fujii_fig02.png\",width = 600)\n\nnqubits = 2\nmes = QuantumState(nqubits)\nH(0).update_quantum_state(mes)\nCNOT(0,1).update_quantum_state(mes)\n\n# 0,1基底での確率分布は、\n\nshow_distribution(mes)\n\n# $\\{ |+\\rangle , |-\\rangle \\} $基底での測定は、$H$を作用させてから0,1測定すればいいので\n\nH(0).update_quantum_state(mes)\nH(1).update_quantum_state(mes)\nshow_distribution(mes)\n\n\n# 基底を変えても完全相関があることがわかる。2n qubitの最大エンタングル状態を生成する関数を作っておく。\n\ndef maximally_entangled_state(nqubits):\n state = QuantumState(2*nqubits)\n for i in range(nqubits):\n H(i).update_quantum_state(state)\n CNOT(i,i+nqubits).update_quantum_state(state)\n return state\n\n\nfour_qubit_mes = maximally_entangled_state(2)\nshow_distribution(four_qubit_mes)\n\n# ## エンタングルメント忠実度を計算する\n\n# `RandomUnitary`を用いてターゲットとなるランダムな量子演算を作っておく\n\nImage(\"./fujii_fig02b.png\",width = 600)\n\nfrom qulacs.gate import RandomUnitary\ntarget_list = [0]\ntarget_unitary = RandomUnitary(target_list)\nprint(target_unitary)\n\n# パラメータ付きの量子回路を`ParametricQuantumCircuit`に`add_parametric_RX_gate`で追加する生成する\n\n# +\nnqubits = 2 # 2qubitの空間考えているので2qubit分確保しておく\n\n#パラメータ付きの量子回路クラス\nansatz = ParametricQuantumCircuit(nqubits)\n\n#パラメータを回路構成後に変更できる演算\nansatz.add_parametric_RZ_gate(0,0.0)\nansatz.add_parametric_RX_gate(0,0.0)\nansatz.add_parametric_RZ_gate(0,0.0)\n\n#通常の量子演算\nansatz.add_gate(target_unitary)\n\n#量子回路の可視化\ncircuit_drawer(ansatz, \"mpl\")\n# -\n\n# エンタングルメント忠実度を計算する。`mes_copy` = $\\langle \\text{MES}|$, `mes` = $I \\otimes (U^{\\dagger} R_z(\\alpha) R_x(\\beta) R_z(\\gamma))|\\text{MES}\\rangle$として、`inner_product`関数を実行\n\n# +\nmes = maximally_entangled_state(1)\nmes_copy = mes.copy()\nansatz.update_quantum_state(mes)\n\nfrom qulacs.state import inner_product\nent_fidelity = abs(inner_product(mes_copy,mes))**2\nprint(ent_fidelity)\n# -\n\n# エンタングルメント忠実度を計算する関数を作っておく\n\n# +\nfrom qulacs.state import inner_product\n\ndef entanglement_fidelity(ansatz,nqubits):\n mes = maximally_entangled_state(int(nqubits/2))\n mes_copy = mes.copy()\n ansatz.update_quantum_state(mes)\n\n ent_fidelity = abs(inner_product(mes_copy,mes))**2\n return ent_fidelity\n\n\n# -\n\nentanglement_fidelity(ansatz,2)\n\n# ## 忠実度を最適化することで、演算の分解を見つける\n\nImage(\"./fujii_fig02c.png\",width = 600)\n\n\n# パラメータ付き回路のパラメータを変化させて、ターゲットの量子演算となるパラメータを見つけよう。i番目のパラメータの変更は、`set_parameter(i,new_parameter)`\n\ndef cost(parameters):\n num_paras = ansatz.get_parameter_count()\n\n #パラメータを変更\n for i in range(num_paras):\n ansatz.set_parameter(i,parameters[i])\n \n return 1 - entanglement_fidelity(ansatz,nqubits)\n\n\ncost([random.random() for i in range(3)])\n\n# scipyの最適化関数をつかって、パラメータを変分的に最適化しよう\n\n# +\nimport scipy.optimize\n\ncost_history = []\n\n#パラメータの初期値\ninit_theta_list = [random.random() for i in range(ansatz.get_parameter_count())]\ncost_history.append(cost(init_theta_list))\n\nmethod = \"BFGS\"\noptions = {\"disp\": True, \"maxiter\": 50, \"gtol\": 1e-6}\n\nopt = scipy.optimize.minimize(cost, init_theta_list,\n method=method,\n callback=lambda x: cost_history.append(cost(x)))\n\nplt.rcParams[\"font.size\"] = 18\nplt.plot(cost_history)\nplt.xlabel(\"Iteration\")\nplt.ylabel(\"1-(entanglement fidelity)\")\nplt.show()\n# -\n\nprint(\"fidelity\",opt.fun,\"parameters\",opt.x)\n\n\ncost([-0.1523479 , 2.03515578,-2.1503557 ])\n\n# できた回路が同じであることを確認しておく(エルミート共役をとるので、パラメータの順序を逆にし、マイナスをつけることを忘れない)\n# $$\n# (R_z(\\alpha) R_x(\\beta) R_z(\\gamma))^{\\dagger} = R_z(-\\gamma) R_x(-\\beta) R_z(-\\alpha))\n# $$\n\n# +\nnqubits = 1\nstate0 = QuantumState(nqubits)\nstate0.set_Haar_random_state()\nstate1 = state0.copy()\n\ntarget_unitary.update_quantum_state(state0)\n\nRZ(0,-1.0*opt.x[2]).update_quantum_state(state1)\nRX(0,-1.0*opt.x[1]).update_quantum_state(state1)\nRZ(0,-1.0*opt.x[0]).update_quantum_state(state1)\n\nabs(inner_product(state0,state1))**2\n\n# -\n\n# (全体の位相因子が異なる場合がある。)\n\n# ## 応用編:CNOT演算を分解する\n# 2量子ビット以上のパウリの回転演算子は`add_parametric_multi_Pauli_rotation_gate(index_list, pauli_id_list, angle)`\n# で追加できる。`pauli_id_list`はX、Y、Z、をそれぞれ1,2,3として並べたリスト。\n#\n\nImage(\"./fujii_fig03.png\",width = 600)\n\n# パウリ行列$I=\\sigma_0, X=\\sigma_1, Y=\\sigma_2, Z=\\sigma_3$の添え字(0-3)をqulacsでは`pauli_id`と呼んでいる。 \n# `add_parametric_multi_Pauli_rotation_gate`関数の引数は次の通り。\n#\n# - `index_list`: 量子ビットのインデックスのリスト\n# - `pauli_ids`: $e^{i\\theta U}$の$U$を$U$をパウリ行列のテンソル積するときの、`pauli_id`のリスト。例えば、$Z \\otimes X = \\sigma_3 \\otimes \\sigma_1$の場合は、`[3,1]`\n# - `angle`: $e^{i\\theta U}$の$\\theta$\n#\n# `index_list`と`pauli_ids`の長さは同じにする。\n\n# +\nnqubits = 4 # 4qubitの空間考えているので4qubit分確保しておく\n\n#パラメータ付きの量子回路クラス\nansatz = ParametricQuantumCircuit(nqubits)\n\n#パラメータを回路構成後に変更できる演算\nansatz.add_parametric_RZ_gate(0,0.0)\nansatz.add_parametric_multi_Pauli_rotation_gate([0,1],[3,1], 0.0)\nansatz.add_parametric_RX_gate(1,0.0)\n\n#ターゲットの量子演算\nansatz.add_gate(CNOT(0,1))\n\n# +\ncost_history = []\n\n#パラメータの初期値\ninit_theta_list = [random.random() for i in range(ansatz.get_parameter_count())]\ncost_history.append(cost(init_theta_list))\n\nmethod = \"BFGS\"\noptions = {\"disp\": True, \"maxiter\": 50, \"gtol\": 1e-6}\n\nopt = scipy.optimize.minimize(cost, init_theta_list,\n method=method,\n callback=lambda x: cost_history.append(cost(x)))\n\nplt.rcParams[\"font.size\"] = 18\nplt.plot(cost_history)\nplt.xlabel(\"Iteration\")\nplt.ylabel(\"1-(entanglement fidelity)\")\nplt.show()\n# -\n\nopt.x\n\n\n","repo_name":"Qulacs-Osaka/quantum_software_handson","sub_path":"doc/source/notebooks/01_03_VariationalGateDecomposition.ipynb","file_name":"01_03_VariationalGateDecomposition.ipynb","file_ext":"py","file_size_in_byte":7273,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-jupyter-script","pt":"21"} +{"seq_id":"22225420768","text":"# +\nimport os, cPickle\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\nfrom scipy.io import loadmat\n\nfrom sklearn.decomposition import PCA\n\nfrom palettable.colorbrewer.qualitative import Set1_9\ncolors = Set1_9.mpl_colors\ncmap = Set1_9.mpl_colormap\n\n# %matplotlib inline\n\n# +\ndata_dir = \"whole brain data Kato et al 2015\"\nzimmer_state_labels = \\\n loadmat(os.path.join(\n data_dir, \n \"sevenStateColoring.mat\"))\n \nworm_files = [\"TS20140715e_lite-1_punc-31_NLS3_2eggs_56um_1mMTet_basal_1080s.mat\",\n \"TS20140715f_lite-1_punc-31_NLS3_3eggs_56um_1mMTet_basal_1080s.mat\",\n \"TS20140905c_lite-1_punc-31_NLS3_AVHJ_0eggs_1mMTet_basal_1080s.mat\",\n \"TS20140926d_lite-1_punc-31_NLS3_RIV_2eggs_1mMTet_basal_1080s.mat\",\n \"TS20141221b_THK178_lite-1_punc-31_NLS3_6eggs_1mMTet_basal_1080s.mat\"\n ]\n\n# -\n\nall_first_neuron_ids = []\nall_second_neuron_ids = []\nall_neuron_ids = []\nfor worm_index in range(5):\n zimmer_data = loadmat(os.path.join(data_dir, \"wbdata\", worm_files[worm_index]))\n \n # Get the state sequence as labeled in Kato et al\n zimmer_key = map(lambda x: str(x[0]), zimmer_state_labels[\"sevenStateColoring\"][\"key\"][0,0][0])\n zimmer_states = zimmer_state_labels[\"sevenStateColoring\"][\"dataset\"][0,0]['stateTimeSeries'][0,worm_index].ravel() - 1\n zimmer_cps = np.concatenate(([0], 1+np.where(np.diff(zimmer_states))[0], [zimmer_states.size-1]))\n N_zimmer = zimmer_states.max() + 1\n\n # Get the calcium trace (corrected for bleaching)\n tt = zimmer_data[\"wbData\"]['tv'][0,0]\n dff = zimmer_data[\"wbData\"]['deltaFOverF'][0,0]\n dff_bc = zimmer_data[\"wbData\"]['deltaFOverF_bc'][0,0]\n dff_deriv = zimmer_data[\"wbData\"]['deltaFOverF_deriv'][0,0]\n\n neuron_ids_array = zimmer_data[\"wbData\"]['NeuronIds'][0,0][0]\n first_neuron_ids_array = np.array(map(lambda x: None if len(x[0])==0 \n else str(x[0][0][0]) , \n neuron_ids_array))\n second_neuron_ids_array = np.array(map(lambda x: None if x.size<2 or x[0,1].size == 0 \n else str(x[0,1][0]) , \n neuron_ids_array))\n \n # Store\n all_first_neuron_ids.append(first_neuron_ids_array)\n all_second_neuron_ids.append(second_neuron_ids_array)\n all_neuron_ids.append(np.column_stack((first_neuron_ids_array, \n second_neuron_ids_array)))\n\n\nfrom functools import reduce\ncommon_neurons = reduce(np.intersect1d, all_first_neuron_ids)\nprint(common_neurons)\ncommon_neurons.shape\n# map(np.unique, all_first_neuron_ids)\n\nnp.array(map(lambda x: x.size, neuron_ids_array))\n","repo_name":"slinderman/zimmer","sub_path":"notebooks/2016-09-01 looking for shared neurons.ipynb","file_name":"2016-09-01 looking for shared neurons.ipynb","file_ext":"py","file_size_in_byte":2777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"19701856322","text":"import requests\nfrom lxml import etree\nfrom bs4 import BeautifulSoup\nimport pandas as pd\n\ndf = pd.read_csv('/Users/user1/Desktop/course/專題/data/output25.csv')\nprint(df.head(5))\nCaseNo_list = []\nCaseNo_list = df['CaseNo']\n\nCaseNo_list.head(30)\n\nfrom selenium import webdriver\ndriver = webdriver.Chrome('./chromedriver')\nfrom selenium.webdriver.common.keys import Keys\nimport time\ninfo_name = ['trademark_name','caseNo','applyDate','regNo','regNo',' ','regDate','regDate','deadline','class']\n\ndriver.get(\"https://twtmsearch.tipo.gov.tw/OS0/OS0201.jsp?l6=zh_TW&isReadBulletinen_US=&isReadBulletinzh_TW=true\")\n\n# +\nfrom urllib.request import urlretrieve\nimport csv \nwith open('/Users/user1/Desktop/course/專題/key.csv','a') as fd:\n writer = csv.writer(fd)\n writer.writerow([['word']])\n print(\"word\",word)\n#for i in range(5,19,9): \nfor i in range(5,len(CaseNo_list),9):\n#for i in range(1):\n start_time = time.time()\n element = driver.find_element_by_id('applNo')\n element.send_keys(str(CaseNo_list[i]))\n print(\"CaseNo: \",str(CaseNo_list[i]))\n for j in range(9):\n print(\"CaseNo: \",str(CaseNo_list[i+j+1]))\n button = driver.find_element_by_xpath(\"//*[@id='form1']/fieldset/div[4]/div/table/tbody/tr/td[2]/img\")\n button.click()\n time.sleep(0.005)\n temp = ('applNo'+\"%s\" % int(j+1))\n element = driver.find_element_by_id(temp)\n element.send_keys(str(CaseNo_list[i+j+1]))\n button = driver.find_element_by_id(\"querySubmit\")\n button.click()\n time.sleep(1.7)\n\n alist = []\n for link in driver.find_elements_by_xpath(\"//*[@id='APPL_NO']/a\"):\n print (link.get_attribute('href'))\n key = link.get_attribute('href')[29:70]\n alist.append(key)\n print(\"alist\",alist,alist[0])\n\n \n with open('/Users/user1/Desktop/course/專題/key.csv','a') as fd:\n writer = csv.writer(fd)\n for word in alist:\n writer.writerow([word])\n \n button = driver.find_element_by_id(\"searchPage\")\n button.click()\n time.sleep(0.5)\n button = driver.find_element_by_xpath(\"//button[@value='doClear']\")\n button.click()\n time.sleep(0.5)\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n\n\n \n# -\n\nkey_pd = pd.read_csv(\"key.csv\", error_bad_lines=False)\nkey_pd[\"['word']\"]\n\nfor i in range(len(key_pd[\"['word']\"])): \n web = (\"https://twtmsearch.tipo.gov.tw/SS0/friendlyPrinting.jsp?showType=2&caseType=1&caseNo=%s=&l6=zh_TW&isReadBulletinen_US=&isReadBulletinzh_TW=true\"%key_pd[\"['word']\"][i])\n print(\"web\",web)\n resp = requests.get(web)\n #print(resp.text)\n with open(f\"friendly_output_{i}.html\", \"w\") as file:\n file.write(str(resp.text))\n\n \"\"\"\n button = driver.find_element_by_link_text(str(CaseNo_list[i]))\n button.click()\n time.sleep(10)\n driver.switch_to.window(driver.window_handles[1])\n #x = BeautifulSoup(driver.page_source,'html.parser')\n #print(x.prettify())\n #print(\"x\",type(x))\n #f'Hello, {text}'\n #with open(f\"output{CaseNo_list[i]}.html\", \"w\") as file:\n #file.write(str(x))\n\n button = driver.find_element_by_id(\"doPrintFriendly\")\n button.click()\n\n driver.switch_to.window(driver.window_handles[2])\n y = BeautifulSoup(driver.page_source,'html.parser')\n\n with open(f\"friendly_output{CaseNo_list[i]}.html\", \"w\") as file:\n file.write(str(y))\n\n\n image = y.find_all('div')\n\n\n #下面的迴圈是找圖片網址再把結果放到陣列裡\n links=[]\n for d in image:\n\t if d.find('img'): #再從div找img裡面的src \n\t\t result=d.find('img')['src']\n\t\t print(result)\n\t\t links.append(result)\n\n x = 1\n for link in links:\n if link == \"\":\n continue\n print(\"link\",link)\n local = os.path.join('/Users/user1/Desktop/course/專題/image/%s_%s.jpg' %(CaseNo_list[i], x))\n \n full_link = os.path.join('https://twtmsearch.tipo.gov.tw/%s' % link[3:])\n print(\"full_link\",full_link)\n urlretrieve(full_link,local) #link是下載的網址 local是儲存圖片的檔案位址\n x+=1\n \"\"\"\n \"\"\"\n #trademark = []\n info_list = x.find_all('td',class_=\"scn2text\")\n\n info = []\n #info_list_zip = zip(info_name,info_list)\n print(\"info:\\n\")\n for i in info_list:\n info.append(i.text)\n \n info_list_zip = zip(info_name,info)\n print(\"info_list_zip\",info_list_zip)\n\n for j in info_list_zip:\n print(j)\n #css_soup = BeautifulSoup('', 'html.parser')td class=\"scn2text\"\n\n words_list = x.find_all('td',class_=\"scn_tdText scn_tdText_Draft\")\n #trademark_names\n\n words = []\n print(\"words in picture:\\n\")\n for i in words_list:\n words.append(i.text)\n print(i.text)\n \n time.sleep(10)\n driver.close()\n time.sleep(10)\n driver.switch_to.window(driver.window_handles[1])\n time.sleep(10)\n driver.close()\n\n time.sleep(10)\n driver.switch_to.window(driver.window_handles[0])\n \"\"\"\n","repo_name":"Dragons-Lai/2021_trademark_project","sub_path":"wen/spider.ipynb","file_name":"spider.ipynb","file_ext":"py","file_size_in_byte":4984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"39990317918","text":"# The following lines import the necessary packages\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport statsmodels.formula.api as smf\nimport statsmodels\n\n#Import data\ndf = pd.read_csv('population_by_country_2020_ori.csv')\ndf.info();df.head()\n\n# +\n\nHDI = pd.read_csv('HDR21-22_Statistical_Annex_HDI_Trends_Table.csv')\nHDI.info();HDI.head()\n# -\n\ndf.rename(columns = {'Country (or dependency)':'Country','Population (2020)':'Population','Yearly Change':'Yearly_Change','Net Change':'Net_Change','Density (P/Km²)':'Density','Land Area (Km²)':'Land_Area','Migrants (net)':'Migrants','Fert. Rate':'FertRate','Med. Age':'MedAge','Urban Pop %':'UrbanPop','World Share':'World_Share'}, inplace = True)\n\ndf\n\n# +\n##Check the row and count of null values and delete the rows with null values\n\n# +\ndf.isnull().sum(axis=0).sort_values(ascending=False)[0:11]\n\ndf.drop(df[df.Migrants.isna()].index.array, axis=0, inplace=True)\ndf.drop(df[df.UrbanPop == 'N.A.'].index.array, axis=0, inplace=True)\ndf\n# -\n\nHDI = HDI.loc[:,['HDI_rank','Country','2020']]\nHDI.drop(HDI[HDI.Country.isna()].index.array, axis=0, inplace=True)\nHDI.rename(columns = {'2020':'HDI2020'}, inplace = True)\nHDI\n\nHP = pd.merge(df,HDI,on='Country',how='inner')\nHP\n\n\nHP.head()\n\nHP['Yearly_Change'] = (HP['Yearly_Change'].str.strip('%').astype(float))\nHP['UrbanPop'] = (HP['UrbanPop'].str.strip('%').astype(float))\nHP['World_Share'] = (HP['World_Share'].str.strip('%').astype(float))\n\n\nHP['FertRate'] = HP['FertRate'].astype(float)\nHP['MedAge'] = HP['MedAge'].astype(float)\n\nHP\n\n\n# +\n\nHP[:10].plot(x='Country',y='Population',kind = 'bar')\nHP[-10:].plot(x='Country',y='Population',kind = 'bar')\n\n# +\n\nHDISORT = HP.sort_values(by=\"HDI_rank\")\nHDISORT\nHDISORT[:30].plot(x='Country',y='HDI2020',kind = 'bar')\n# -\n\nHP.corr()\n\nprint(list(HP.columns))\nprint(list(HP.median().index))\n\n# mean var median\ncol_list = HP.columns[1:]\nmean_list = HP.mean().tolist()\nvar_list = HP.var().tolist()\nmedian_list = HP.median().tolist()\n\n# +\nall_list = []\nall_list.append(mean_list)\nall_list.append(var_list)\nall_list.append(median_list)\n\n\nindex_list = [\"mean\", \"var\", \"median\"]\n\nHP_new = pd.DataFrame(all_list, columns=col_list, index=index_list)\nHP_new\n# -\n\ndf_m_m_f = HP[[\"Migrants\", \"MedAge\", \"UrbanPop\"]]\ndf_m_m_f\n\n# +\nfig_boxplot, (ax0, ax1, ax2) = plt.subplots(1, 3, figsize=(9, 6))\nfig_boxplot.tight_layout()\n\n# Migrants\nax0.boxplot([df_m_m_f[\"Migrants\"].tolist()],\n labels = ['Migrants'],\n showmeans = True, \n patch_artist = True, \n boxprops = {'color':'orangered','facecolor':'pink'})\n\n# MedAge\nax1.boxplot([df_m_m_f[\"MedAge\"].tolist()],\n labels = ['MedAge'],\n showmeans = True, \n patch_artist = True, \n boxprops = {'color':'orangered','facecolor':'pink'})\n\n# UrbanPop\nax2.boxplot([df_m_m_f[\"UrbanPop\"].tolist()],\n labels = ['UrbanPop'],\n showmeans = True, \n patch_artist = True, \n boxprops = {'color':'orangered','facecolor':'pink'})\n\nplt.show()\nplt.close('all')\n# -\n\ndf_m_m_f = HP[[\"Migrants\", \"Population\", \"HDI2020\"]]\ndf_m_m_f\n\n# +\nfig_boxplot, (ax0, ax1, ax2) = plt.subplots(1, 3, figsize=(9, 6))\nfig_boxplot.tight_layout()\n\n# Migrants\nax0.boxplot([df_m_m_f[\"Migrants\"].tolist()],\n labels = ['Migrants'],\n showmeans = True, \n patch_artist = True, \n boxprops = {'color':'orangered','facecolor':'pink'})\n\n# MedAge\nax1.boxplot([df_m_m_f[\"Population\"].tolist()],\n labels = ['Population'],\n showmeans = True, \n patch_artist = True, \n boxprops = {'color':'orangered','facecolor':'pink'})\n\n# UrbanPop\nax2.boxplot([df_m_m_f[\"HDI2020\"].tolist()],\n labels = ['HDI2020'],\n showmeans = True, \n patch_artist = True, \n boxprops = {'color':'orangered','facecolor':'pink'})\n\nplt.show()\nplt.close('all')\n# -\n\nHP=HP.drop([\"Country\"],axis=1)\nfrom sklearn.preprocessing import MinMaxScaler\nmms = MinMaxScaler()\n\nHP = HP.copy()\nfor c in HP.columns.values:\n HP[c] = mms.fit_transform(HP[c].values.reshape(-1,1))\nHP.head()\n\nf = plt.figure(figsize=(9, 7)) \nplt.matshow(HP.corr(), fignum=f.number)\nplt.xticks(range(HP.select_dtypes(['number']).shape[1]), HP.select_dtypes(['number']).columns, fontsize=12, rotation=45) \nplt.yticks(range(HP.select_dtypes(['number']).shape[1]), HP.select_dtypes(['number']).columns, fontsize=12) \ncb = plt.colorbar() #图例\ncb.ax.tick_params(labelsize=14) \nplt.title('Correlation Matrix', fontsize=16) \n\nimport seaborn as sns\nf = plt.figure(figsize=(10, 9)) \nsns.heatmap(HP.corr(), annot=True, cmap='RdBu', xticklabels=1, yticklabels=1,)\nplt.title('correlation Matrix', fontsize=16)\n\n# +\n\nfrom statsmodels.formula.api import ols \nlm = ols('HDI2020 ~ Yearly_Change', data=HP).fit()\nlm.summary()\n\n# +\n\nychdi_reg = smf.ols(formula='HDI2020 ~ Yearly_Change',data=HP).fit()\n\nbeta_6, beta_7 = ychdi_reg.params\nrsq4 = ychdi_reg.rsquared\npval_6, pval_7 = ychdi_reg.pvalues\nprint(\"The 2020 population change rate and the country's HDI index unary regression of that year:\")\nprint(\"y =\", round(beta_7,3), \"x +\", round(beta_6,3))\nprint(\"R^2 = \", rsq4)\nprint(\"p-value of greenery = \", round(pval_7,5))\nprint(\"p-value of intercept = \", round(pval_6,5))\n\nfig, ax = plt.subplots()\nHP.plot(kind='scatter', x='Yearly_Change', y='HDI2020', figsize=(6, 4), ax = ax,s=8)\nplt.title(label = \"Regression of the rate of population change in 2020 on the HDI \")\nX = HP.Yearly_Change\nb = plt.plot(X, X*beta_7 + beta_6, 'r') \n# -\n\nimport matplotlib\nimport matplotlib.pyplot as plt\n\n\n\nHP\n\n# +\n\nfrom statsmodels.formula.api import ols \nlm = ols('HDI2020 ~ MedAge + FertRate + UrbanPop', data=HP).fit()\nlm.summary()\n# -\n\nHDI_MFU = HP.loc[:,['HDI2020', 'MedAge', 'FertRate','UrbanPop']]\nHDI_MFU\n\n# +\n# calculating VIF\n# This function is adjusted from: https://stackoverflow.com/a/51329496/4667568\nfrom statsmodels.stats.outliers_influence import variance_inflation_factor \nfrom statsmodels.tools.tools import add_constant\n\ndef drop_column_using_vif_(df, thresh=5):\n '''\n Calculates VIF each feature in a pandas dataframe, and repeatedly drop the columns with the highest VIF\n A constant must be added to variance_inflation_factor or the results will be incorrect\n\n :param df: the pandas dataframe containing only the predictor features, not the response variable\n :param thresh: (default 5) the threshould VIF value. If the VIF of a variable is greater than thresh, it should be removed from the dataframe\n :return: dataframe with multicollinear features removed\n '''\n while True:\n # adding a constatnt item to the data. add_constant is a function from statsmodels (see the import above)\n df_with_const = add_constant(df)\n\n vif_df = pd.Series([variance_inflation_factor(df_with_const.values, i) \n for i in range(df_with_const.shape[1])], name= \"VIF\",\n index=df_with_const.columns).to_frame()\n\n # drop the const\n vif_df = vif_df.drop('const')\n \n # if the largest VIF is above the thresh, remove a variable with the largest VIF\n # If there are multiple variabels with VIF>thresh, only one of them is removed. This is because we want to keep as many variables as possible\n if vif_df.VIF.max() > thresh:\n # If there are multiple variables with the maximum VIF, choose the first one\n index_to_drop = vif_df.index[vif_df.VIF == vif_df.VIF.max()].tolist()[0]\n print('Dropping: {}'.format(index_to_drop))\n df = df.drop(columns = index_to_drop)\n else:\n # No VIF is above threshold. Exit the loop\n break\n\n return df\n\n\n# -\n\nHDI_MFU_VIF = drop_column_using_vif_(HDI_MFU .drop('HDI2020', axis=1))\n\n# +\n\nfrom statsmodels.formula.api import ols \nlm = ols('HDI2020 ~ FertRate + UrbanPop', data=HP).fit()\nlm.summary()\n\n# +\nimport numpy, scipy, scipy.optimize\nimport matplotlib\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm # to colormap 3D surfaces from blue to red\nimport matplotlib.pyplot as plt\n\ngraphWidth = 600 # units are pixels\ngraphHeight = 400 # units are pixels\n\n# 3D contour plot lines\nnumberOfContourLines = 16\n\n\ndef SurfacePlot(func, data, fittedParameters):\n f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)\n\n matplotlib.pyplot.grid(True)\n #axes = Axes3D(f)\n axes=f.add_subplot(111, projection='3d')\n\n x_data = data[0]\n y_data = data[1]\n z_data = data[2]\n\n xModel = numpy.linspace(min(x_data), max(x_data), 20)\n yModel = numpy.linspace(min(y_data), max(y_data), 20)\n X, Y = numpy.meshgrid(xModel, yModel)\n\n Z = func(numpy.array([X, Y]), *fittedParameters)\n\n axes.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=1, antialiased=True,alpha = 0.5)\n\n axes.scatter(x_data, y_data, z_data) # show data along with plotted surface\n\n axes.set_title('Surface Plot (click-drag with mouse)') # add a title for surface plot\n axes.set_xlabel('X Data') # X axis data label\n axes.set_ylabel('Y Data') # Y axis data label\n axes.set_zlabel('Z Data') # Z axis data label\n\n plt.show()\n plt.close('all') # clean up after using pyplot or else thaere can be memory and process problems\n\n\ndef ContourPlot(func, data, fittedParameters):\n f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)\n axes = f.add_subplot(111)\n\n x_data = data[0]\n y_data = data[1]\n z_data = data[2]\n\n xModel = numpy.linspace(min(x_data), max(x_data), 20)\n yModel = numpy.linspace(min(y_data), max(y_data), 20)\n X, Y = numpy.meshgrid(xModel, yModel)\n\n Z = func(numpy.array([X, Y]), *fittedParameters)\n\n axes.plot(x_data, y_data, 'o')\n\n axes.set_title('Contour Plot') # add a title for contour plot\n axes.set_xlabel('X Data') # X axis data label\n axes.set_ylabel('Y Data') # Y axis data label\n\n CS = matplotlib.pyplot.contour(X, Y, Z, numberOfContourLines, colors='k')\n matplotlib.pyplot.clabel(CS, inline=1, fontsize=10) # labels for contours\n\n plt.show()\n plt.close('all') # clean up after using pyplot or else thaere can be memory and process problems\n\n\ndef ScatterPlot(data):\n f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)\n\n matplotlib.pyplot.grid(True)\n #axes = Axes3D(f)\n axes=f.add_subplot(111, projection='3d')\n \n x_data = data[0]\n y_data = data[1]\n z_data = data[2]\n\n axes.scatter(x_data, y_data, z_data)\n\n axes.set_title('Scatter Plot (click-drag with mouse)')\n axes.set_xlabel('X Data')\n axes.set_ylabel('Y Data')\n axes.set_zlabel('Z Data')\n\n plt.show()\n plt.close('all') # clean up after using pyplot or else thaere can be memory and process problems\n\n\ndef func(data, a, b, c):\n x = data[0]\n y = data[1]\n return (a * x) + (y * b) + c\n\n\nif __name__ == \"__main__\":\n xData = HP.FertRate\n yData = HP.UrbanPop\n zData = HP.HDI2020 \n data = [xData, yData, zData]\n\n initialParameters = [1.0, 1.0, 1.0] # these are the same as scipy default values in this example\n\n # here a non-linear surface fit is made with scipy's curve_fit()\n fittedParameters, pcov = scipy.optimize.curve_fit(func, [xData, yData], zData, p0 = initialParameters)\n\n ScatterPlot(data)\n SurfacePlot(func, data, fittedParameters)\n ContourPlot(func, data, fittedParameters)\n\n print('fitted prameters', fittedParameters)\n\n modelPredictions = func(data, *fittedParameters) \n\n absError = modelPredictions - zData\n\n SE = numpy.square(absError) # squared errors\n MSE = numpy.mean(SE) # mean squared errors\n RMSE = numpy.sqrt(MSE) # Root Mean Squared Error, RMSE\n Rsquared = 1.0 - (numpy.var(absError) / numpy.var(zData))\n print('RMSE:', RMSE)\n print('R-squared:', Rsquared)\n\n# +\n\nh_f_u = ols('HDI2020 ~ FertRate + UrbanPop', data=HP).fit()\nx = HP[[\"FertRate\", \"UrbanPop\"]]\ny = HP[\"HDI2020\"]\ny_predit = h_f_u.predict(x)\n\nresiduals_m_y = y_predit - y\n\nprint(\"residuals: \")\nprint(residuals_m_y)\n\n# plt.scatter\nfig, (ax0) = plt.subplots(1, 1, figsize=(9, 4))\nmatplotlib.pyplot.grid(True)\n\nax0.scatter([i+1 for i in range(len(y))], residuals_m_y)\n\nax0.set_title('Scatter Plot (HDI2020 Residuals)')\nax0.set_xlabel('Sequence')\nax0.set_ylabel('Residuals')\n\nplt.show()\nplt.close('all')\n# -\n\n\n\n\n\n# +\nimport pandas as pd\n\nimport matplotlib.cm\nfrom matplotlib import colors\nimport matplotlib.pyplot as plt \nimport numpy as np \nimport sklearn.cluster as sklc # For clustering\nimport sklearn.metrics as sklm # For the silhouette score\n\nfrom sklearn.preprocessing import RobustScaler\nimport sklearn\n\n\nnum_clusters = 2\nmos = HP\ndata2=mos[[\"Migrants\",\"UrbanPop\",\"HDI2020\"]]\nprint(data2)\n# -\n\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nfig=plt.figure(figsize=(10,10))\nax=fig.add_subplot(111, projection='3d')\nx=data2['UrbanPop']\ny=data2['Migrants']\nz=data2['HDI2020']\nax.scatter(x, y, z)\nax.set_xlabel(\"UrbanPop\")\nax.set_ylabel(\"Migrants\")\nax.set_zlabel(\"HDI2020\")\nplt.show( )\n\n# +\n\nfrom sklearn.preprocessing import MinMaxScaler\nmms = MinMaxScaler()\n\ndata2_standardised = data2.copy()\nfor c in data2.columns.values:\n data2_standardised[c] = mms.fit_transform(data2[c].values.reshape(-1,1))\ndata2_standardised.head()\n\n# +\nrandom_state_seed = 1000\nkmeans_output = sklc.KMeans(n_clusters=num_clusters, random_state=random_state_seed).fit(data2_standardised)\n\nprint(kmeans_output) \n\n\n\n# +\nclustering_ids_kmeans = kmeans_output.labels_\n\nprint(clustering_ids_kmeans)\n\n# +\n# we will combine the clustering IDs to the dataframe\ndata2 = data2.assign(cluster_id = clustering_ids_kmeans)\n\n#Have a look at the result:\nprint(data2)\n\n# +\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nfig=plt.figure(figsize=(12,12))\nax=fig.add_subplot(111, projection='3d')\n\n# number of clusters\nn_clusters = data2.cluster_id.nunique()\n\n# get discrete colormap\ncmap = plt.get_cmap('Spectral', n_clusters)\n\n# scatter points\nx=data2['UrbanPop']\ny=data2['Migrants']\nz=data2['HDI2020']\nscatter =ax.scatter(x, y, z, c=data2.cluster_id, cmap=cmap)\nax.set_xlabel(\"UrbanPop\")\nax.set_ylabel(\"Migrants\")\nax.set_zlabel(\"HDI2020\")\n\ncbar = plt.colorbar(scatter)\n# set ticks locations (not very elegant, but it works):\n# - shift by 0.5\n# - scale so that the last value is at the center of the last color\ntick_locs = (np.arange(n_clusters) + 0.5)*(n_clusters-1)/n_clusters\ncbar.set_ticks(tick_locs)\n\n# set tick labels (as before)\ncbar.set_ticklabels(np.arange(n_clusters))\n# -\n\nX = data2_standardised[['Migrants','UrbanPop','HDI2020']]\nrandom_state_seed = 1000\ndf_silhouette_score = pd.DataFrame({'n_cluster':[2,3,4,5,6], 'silhouette_score':[0,0,0,0,0]})\nfor index, row in df_silhouette_score.iterrows():\n n_clusters = row['n_cluster']\n clusterer = sklc.KMeans(n_clusters=n_clusters, random_state=random_state_seed).fit(X)\n cluster_labels = clusterer.labels_\n \n silhouette_avg = sklm.silhouette_score(X, cluster_labels)\n print(\n \"For n_clusters =\",\n n_clusters,\n \"The average silhouette_score is :\",\n silhouette_avg,\n )\n row['silhouette_score'] = silhouette_avg\n\n\n","repo_name":"Fayee23/QM-Group11","sub_path":"HDI_v2.1-v1.1(1).ipynb","file_name":"HDI_v2.1-v1.1(1).ipynb","file_ext":"py","file_size_in_byte":15191,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"71145421829","text":"# ## A Brief Presentation of Evaluation Results\n# This Jypyter Notebook presents the evaluation results of four approaches to solve the MVC problem. The results are presented in the form of tables and graphs, including:\n#\n# - Comprehensive Table: a table with columns for each of the MVC algorithms, including:\n# - Average running time;\n# - VC values;\n# - Relative error with respect to the optimum solution quality provided.\n# - Qualified Runtime for various solution qualities (QRTDs) for each of the two Local Search algorithms;\n# - Solution Quality Distributions for various run-times (SQDs) for each of the two Local Search algorithms;\n# - Box plots for running times for each of the two Local Search algorithms, with three different error intervals;\n# - Table of results on the temperature parameter T0_P in LS1, with the same parameters as the other experiments.\n\n# +\nfrom evaluation_tools import get_results_table, QRTD_plot, SQD_plot, box_plot, get_exp_T0P_table, T0_P_trace_plot\nimport os\nimport numpy as np\nfrom math import ceil\n\nos.chdir(\"..\")\nprint(os.getcwd())\n# -\n\n# ### Comprehensive Table\n# - Comprehensive Table: a table with columns for each of the MVC algorithms, including:\n# - Average running time;\n# - VC values;\n# - Relative error with respect to the optimum solution quality provided.\n\nresults_table = get_results_table()\nfor algorithm in results_table.keys():\n print('Algorithm: {}'.format(algorithm))\n display(results_table[algorithm])\n\n# ### QRTD Plots\n# - Qualified Runtime for various solution qualities (QRTDs) for each of the two Local Search algorithms;\n\nQRTD_plot('power', 'LS1', q_stars=[0, 10, 15, 20, 25, 30], time_steps=list(range(18, 25, ceil(7/100))))\nQRTD_plot('star2', 'LS1', q_stars=[0, 15, 20, 25, 30, 35], time_steps=list(range(215, 235, ceil(20/100))))\n\n# ### SQD Plots\n# - Solution Quality Distributions for various run-times (SQDs) for each of the two Local Search algorithms;\n\nSQD_plot('power', 'LS1', q_stars=list(np.arange(5, 35, 2)), time_steps=list(np.arange(21.5, 25, 0.5)))\nSQD_plot('star2', 'LS1', q_stars=list(np.arange(7, 23, 2)), time_steps=list(np.arange(229, 235, 1)))\n\nSQD_plot('power', 'LS2', q_stars=list(np.arange(2, 15, 0.5)), time_steps=[11, 12, 13, 14, 15])\nSQD_plot('star2', 'LS2', q_stars=list(np.arange(0, 41, 5)), time_steps=list(np.arange(475, 600, 25)))\n\n# ### Box Plots\n# - Box plots for running times for each of the two Local Search algorithms, with three different error intervals.\n\nbox_plot('power', 'LS1', q_star_range=[5, 10])\nbox_plot('power', 'LS1', q_star_range=[10, 15])\nbox_plot('power', 'LS1', q_star_range=[15, 20])\nbox_plot('star2', 'LS1', q_star_range=[5, 10])\nbox_plot('star2', 'LS1', q_star_range=[10, 15])\nbox_plot('star2', 'LS1', q_star_range=[15, 20])\n\n# +\nbox_plot('power', 'LS2', q_star_range=[0, 5])\nbox_plot('power', 'LS2', q_star_range=[5, 10])\nbox_plot('power', 'LS2', q_star_range=[10, 15])\n\nbox_plot('star2', 'LS2', q_star_range=[5, 10])\nbox_plot('star2', 'LS2', q_star_range=[10, 15])\nbox_plot('star2', 'LS2', q_star_range=[15, 20])\n# -\n\n# ### Experiment on T0_P\n# - Table of results on the temperature parameter T0_P in LS1, with the same parameters as the other experiments.\n\nresults_table = get_exp_T0P_table()\nfor T0_P in results_table.keys():\n print('T0_P: {}'.format(T0_P))\n display(results_table[T0_P])\n\nT0_P_trace_plot('power')\nT0_P_trace_plot('star2')\n","repo_name":"haotiansun14/CSE6140-Fall-2022-Project-Minimum-Vertex-Cover","sub_path":"code/evaluation_results.ipynb","file_name":"evaluation_results.ipynb","file_ext":"py","file_size_in_byte":3401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"26104449147","text":"# ### Guinzburg Nathanael 305091357\n\n# ### Import packages\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn.cluster import KMeans\nimport matplotlib.pyplot as plt\n\n# ### Q1)a) How many clusters of grain?\n#\n# Read the first 7 columns of file `'seeds.csv'`, which has no header, into a 2D numpy.array named `samples`and the last (8th) column into a 1D numpy.array named `target` of type int.\n#\n# You can achieve this by using either numpy `genfromtxt` function to read a numpy array directly or pandas `read_csv` function to read a DataFrame and then convert the DataFrame ibto the required numpy arrays.\n#\n# This dataset was sourced from the [UCI Machine Learning Repository](https://archive.ics.uci.edu/ml/datasets/seeds), and contains the measurements (such as area, perimeter, length, and several others) of samples of grain.\n#\n# What's a good number of clusters for this dataset?\n#\n# - For each of the values of `ks` from 1 to 6, perform the following steps: \n# - Create a `KMeans` instance called `model` with k clusters.\n# - Fit the model to the grain data `samples`.\n# - Append the value of the `inertia_` attribute of `model` to the list `inertias`.\n# - Plot `ks` vs `inertias`.\n\n# read csv and extract values(df.values returns 2D array) \ndf = pd.read_csv(\"seeds.csv\", header=None)\nsamples, target = df.iloc[:, 0:7].values, df.iloc[:, 7:8].values.flatten()\ndisplay(samples)\ndisplay(target)\n\n# +\nks = range(1, 6)\ninertias = []\n\n# loop over values of ks\nfor k in ks:\n # Create a KMeans instance with k clusters: model\n kmeans = KMeans(n_clusters=k)\n # Fit model to samples\n kmeans.fit(samples)\n # Append the inertia to the list of inertias\n inertias.append(kmeans.inertia_)\n \n# Plot ks vs inertias\nplt.plot(ks, inertias, '-o')\nplt.xlabel('number of clusters, k')\nplt.ylabel('inertia')\nplt.xticks(ks)\nplt.show()\n# -\n\nvarieties_names = ['Kama wheat', 'Rosa wheat', 'Canadian wheat']\nvarieties = (np.array(varieties_names)[target-1]).tolist()\nvarieties\n\n# ### Q1)b) Evaluating the grain clustering\n#\n# In Q1)a) you observed from the inertia plot that 3 is a good number of clusters for the grain data. In fact, the grain samples come from a mix of 3 different grain varieties: \"Kama\", \"Rosa\" and \"Canadian\". In this section, cluster the grain samples into three clusters, and compare the clusters to the grain varieties using a cross-tabulation.\n#\n# You have the array `samples` of grain samples, and a list `varieties` giving the grain variety for each sample.\n#\n# - Create a `KMeans` model called `model` with `3` clusters.\n# - Use the `.fit_predict()` method of `model` to fit it to `samples` and derive the cluster labels. Using `.fit_predict()` is the same as using `.fit()` followed by `.predict()`.\n# - Create a DataFrame `df` with two columns named `'labels'` and `'varieties'`, using `labels` and `varieties`, respectively, for the column values. This has been done for you.\n# - Use the `pd.crosstab()` function on `df['labels']` and `df['varieties']` to count the number of times each grain variety coincides with each cluster label. Assign the result to `ct`.\n\n# +\n# Create a KMeans model with 3 clusters: model\nmodel = KMeans(n_clusters=3)\n\n# Use fit_predict to fit model and obtain cluster labels: labels\nlabels = model.fit_predict(samples)\n\n# Create a DataFrame with labels and varieties as columns: df\ndf = pd.DataFrame({'labels':labels, 'varieties':varieties})\n\n# Create crosstab: ct\nct = pd.crosstab(df['labels'], df['varieties'])\n\n# Display ct\ndisplay(ct)\n\n# + active=\"\"\n# ### Q2) a) Hierarchical clustering of the grain data\n#\n# The SciPy `linkage()` function performs hierarchical clustering on an array of samples. Use the `linkage()` function to obtain a hierarchical clustering of the grain samples, and use `dendrogram()` to visualize the result. A sample of the grain measurements is provided in the array `samples`, while the variety of each grain sample is given by the list `varieties`.\n#\n# - Perform hierarchical clustering on samples using the `linkage()` function with the `method='complete'` keyword argument. Assign the result to `mergings`. \n# - Set the `figsize` to (20, 10).\n# - Plot a dendrogram using the `dendrogram()` function on `mergings`. Specify the keyword arguments `labels=varieties`, `leaf_rotation=90`, and `leaf_font_size=6`.\n\n# +\n# Perform the necessary imports\nfrom scipy.cluster.hierarchy import dendrogram, linkage\n\n# Calculate the linkage and assign to mergings\nmergins = linkage(samples, method='complete')\n\n# Plot the dendrogram, using varieties as labels\nplt.figure(figsize=(20,10))\nplt.title('Hierarchical Clustering Dendrogram')\nplt.xlabel('sample index')\nplt.ylabel('distance')\ndendrogram(\n mergins,\n leaf_rotation=90, # rotates the x axis labels\n leaf_font_size=6 # font size for the x axis labels\n)\nplt.show()\n# -\n\n# ### Q2)b) Extracting the cluster labels\n#\n# In the previous exercise, you saw that the intermediate clustering of the grain samples at height 6 has 3 clusters. Now, use the `fcluster()` function to extract the cluster labels for this intermediate clustering, and compare the labels with the grain varieties using a cross-tabulation.\n#\n# The hierarchical clustering has already been performed and `mergings` is the result of the `linkage()` function. The list `varieties` gives the variety of each grain sample.\n#\n# - Perform a flat hierarchical clustering by using the `fcluster()` function on `mergings`. Specify a maximum height of `8` and the keyword argument `criterion='distance'`.\n# - Create a DataFrame `df` with two columns named `'labels'` and `'varieties'`, using `labels` and `varieties`, respectively, for the column values. This has been done for you.\n# - Create a cross-tabulation `ct` between `df['labels']` and `df['varieties']` to count the number of times each grain variety coincides with each cluster label.\n\n# +\n# Perform the necessary imports\nfrom scipy.cluster.hierarchy import fcluster\n\n# Use fcluster to extract labels, and assign to labels\nlabels = fcluster(mergins, t=8, criterion='distance')\n\n# Create a DataFrame with labels and varieties as columns, and assign to df\ndf = pd.DataFrame({'labels':labels, 'varieties':varieties})\n\n# Create crosstab: ct between df['labels'] and df['varieties']\nct = pd.crosstab(df['labels'], df['varieties'])\n\n# Display ct\ndisplay(ct)\n# -\n\n# ### Q3)a) Correlated data\n#\n# You suspect that width and length of seeds will be correlated. To confirm this, make a scatter plot of width vs length and measure their Pearson correlation.\n#\n# - Extract the width (4th) and length (3rd) columns of `samples` in that order and set it to variable `grains`.\n# - Import `pearsonr` from scipy.stats.\n# - Assign column `0` of `grains` to `width` and column `1` of `grains` to `length`.\n# - Make a scatter plot with `width` on the x-axis and `length` on the y-axis.\n# - Use the `pearsonr()` function to calculate the Pearson correlation of `width` and `length`.\n\n# +\n# Perform the necessary imports\nfrom scipy.stats import pearsonr \n\n\ngrains = samples[:,[4,3]]\n\n# Assign the 0th column of grains to width\nwidth = grains[:,0]\n\n# Assign the 1st column of grains to length\nlength = grains[:,1]\n\n# Scatter plot width vs length\nplt.scatter(width, length)\nplt.axis('equal')\nplt.show()\n\n# Calculate the Pearson correlation\ncor = pearsonr(width, length)\n\n# Display the correlation\ncor[0]\n# -\n\n# ### Q3)b) Decorrelating the grain measurements with PCA\n#\n# You observed in the previous exercise that the width and length measurements of the grain are correlated. Now, you'll use PCA to decorrelate these measurements, then plot the decorrelated points and measure their Pearson correlation.\n#\n# - Import `PCA` from `sklearn.decomposition`.\n# - Create an instance of `PCA` called `model`.\n# - Use the `.fit_transform()` method of `model` to apply the PCA transformation to `grains`. Assign the result to `pca_features`.\n# - The subsequent code to extract, plot, and compute the Pearson correlation of the first two columns `pca_features` has been written for you.\n\n# +\n# Import PCA\nfrom sklearn.decomposition import PCA\n\n# Create PCA instance: model\nmodel = PCA()\n\n# Apply the fit_transform method of model to grains, and assign to pca_features\npca_features = model.fit_transform(grains)\n\n# Assign 0th column of pca_features to xs\nxs = pca_features[:,0]\n\n# Assign 1st column of pca_features to ys\nys = pca_features[:,1]\n\n# Scatter plot xs vs ys\nplt.scatter(xs, ys)\nplt.axis('equal')\nplt.show()\n\n# Calculate the Pearson correlation of xs and ys\ncor = pearsonr(xs, ys)\n\n# Display the correlation\ncor[0]\n# -\n\n# ### Q3)c) The first principal component\n#\n# The first principal component of the data is the direction in which the data varies the most. In this exercise, your job is to use PCA to find the first principal component of the length and width measurements of the grain samples, and represent it as an arrow on the scatter plot.\n#\n# The array `grains` gives the length and width of the grain samples. \n#\n# - Make a scatter plot of the grain measurements. This has been done for you.\n# - Create a `PCA` instance called `model`.\n# - Fit the model to the `grains` data.\n# - Extract the coordinates of the mean of the data using the `.mean_` attribute of `model`.\n# - Get the first principal component of `model` using the `.components_[0,:]` attribute.\n# - Plot the first principal component as an arrow on the scatter plot, using the `plt.arrow()` function. You have to specify the first two arguments - `mean[0]` and `mean[1]`.\n\n# +\n# Make a scatter plot of the untransformed points\nplt.scatter(width, length)\n\n# Create a PCA instance: model\nmodel = PCA()\n\n# Fit model to points\npca_features = model.fit_transform(grains)\n\n# Get the mean of the grain samples, and assign to mean\nmean = model.mean_\n\n# Get the first principal component, and assign to first_pc\nfirst_pc = pca_features[0]\n\n# Plot first_pc as an arrow, starting at mean\nplt.arrow(mean[0], mean[1], first_pc[0], first_pc[1], color='red', width=0.01)\n\n# Keep axes on same scale\nplt.axis('equal')\nplt.show()\n","repo_name":"TheGuinz/intelligent_system_tools","sub_path":"HW/Ex4_2021.ipynb","file_name":"Ex4_2021.ipynb","file_ext":"py","file_size_in_byte":10025,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"16154537268","text":"# + code_folding=[50]\nimport numpy as np\nimport cv2\nimport os\nimport shutil\nfrom ipynb.fs.full.config import getItem_string\nfrom ipynb.fs.full.config import getItem_int\n \ndef LoadImages(data):\n images = []\n labels = []\n names = []\n \n label = 0\n #read all face images from directory\n for subDirname in os.listdir(data):\n subjectPath = os.path.join(data,subDirname)\n if os.path.isdir(subjectPath): \n names.append(subDirname)\n for fileName in os.listdir(subjectPath):\n imgPath = os.path.join(subjectPath,fileName)\n #convert into grascale\n img = cv2.imread(imgPath,cv2.IMREAD_GRAYSCALE)\n images.append(img)\n# print(imgPath)\n# print(img.shape)\n labels.append(label)\n label += 1\n images = np.asarray(images)\n labels = np.asarray(labels) \n return images,labels,names \n\ndef FaceRec(data): \n # create landmark detector and load lbf model:\n facemark = cv2.face.createFacemarkLBF()\n facemark.loadModel(getItem_string(\"opencv\",\"facemark_model\")) \n \n X,y,names=LoadImages(data)\n #create a EigenFaceRecognizer\n model = cv2.face.EigenFaceRecognizer_create()\n #train the model\n model.train(X,y)\n print('training is done')\n #create a classifier\n face_cascade = cv2.CascadeClassifier(getItem_string(\"opencv\",\"cascadeclassifier\")) \n \n #open camera \n camera = cv2.VideoCapture(0)\n cv2.namedWindow('Camera') \n size_of_image=getItem_int(\"dataset\",\"image_size\")\n while(True):\n #read a frame\n ret,frame = camera.read()\n if ret:\n #convert into grayscale\n grayscale_image = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)\n #detect faces\n faces = face_cascade.detectMultiScale(grayscale_image,1.3,5) \n # (x,y)=top left , w=weight, h=height \n for (x,y,w,h) in faces:\n #draw a rectangle contained faces\n frame = cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)\n #create landmarks\n ok, landmarks = facemark.fit(frame, faces) \n #crop images \n grayscale_face = grayscale_image[y:y+h,x:x+w] \n try:\n #crop into 250*250 \n grayscale_face = cv2.resize(grayscale_face,(size_of_image,size_of_image),interpolation=cv2.INTER_LINEAR) \n #predict\n params = model.predict(grayscale_face)\n #print the confidence\n print('confidence: ',params[1])\n #print landmarks\n for person in landmarks:\n for point in person[0]:\n # circle the characteristics,total of 68\n cv2.circle(frame, (point[0],point[1]), 5, color=(0, 255, 0))\n #print the name on the camara\n cv2.putText(frame,names[params[0]],(x,y-20),cv2.FONT_HERSHEY_SIMPLEX,1,255,2)\n except:\n continue\n \n cv2.imshow('Camera',frame) \n #press q to exit\n if cv2.waitKey(100) & 0xff == ord('q') :\n break\n camera.release()\n cv2.destroyAllWindows()\n \nif __name__=='__main__':\n data = getItem_string(\"dataset\",\"dataset_path\")\n FaceRec(data)\n# -\n\n\n\n\n","repo_name":"Aleks048/AI_Face_Recognition","sub_path":"preprocess/facemarks/using_jupyter/.ipynb_checkpoints/default_opencv_landmark-checkpoint.ipynb","file_name":"default_opencv_landmark-checkpoint.ipynb","file_ext":"py","file_size_in_byte":3439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"16869332139","text":"# + id=\"0W-cFEu9QNrP\" colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"status\": \"ok\", \"timestamp\": 1640682988195, \"user_tz\": -420, \"elapsed\": 22312, \"user\": {\"displayName\": \"fasdfaf ffafa\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"14111875001060407925\"}} outputId=\"8ce28ebe-d203-4576-e6a5-886515108881\"\nfrom google.colab import drive\ndrive.mount(\"/content/drive/\")\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"h6JQhQq6W6Jj\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640682994017, \"user_tz\": -420, \"elapsed\": 4130, \"user\": {\"displayName\": \"fasdfaf ffafa\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"14111875001060407925\"}} outputId=\"e1266611-10e8-4767-f74d-e92c8c87de76\"\n# !pip install statsmodels\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"-T6NGaHnXKh2\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640682999544, \"user_tz\": -420, \"elapsed\": 3665, \"user\": {\"displayName\": \"fasdfaf ffafa\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"14111875001060407925\"}} outputId=\"e1af8f1b-f549-499b-dc05-b7a329a256ea\"\n# !pip install mplfinance\n\n# + id=\"U6VWbJv9V5cj\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640683002969, \"user_tz\": -420, \"elapsed\": 1311, \"user\": {\"displayName\": \"fasdfaf ffafa\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"14111875001060407925\"}} colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"d79ad335-74fa-41ad-d53b-a1f05aeac0ae\"\nfrom datetime import datetime\nimport numpy as np\nimport warnings\n\nfrom statsmodels.tsa.arima_model import ARIMA\n# from statsmodels.tsa.arima.model import ARIMA\nfrom statsmodels.tsa.statespace.sarimax import SARIMAX\nfrom statsmodels.tsa.stattools import adfuller\nfrom statsmodels.tsa.seasonal import seasonal_decompose\nfrom statsmodels.graphics.tsaplots import plot_acf, plot_pacf\nfrom sklearn.metrics import mean_squared_error\nfrom pandas.plotting import autocorrelation_plot\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport math\nimport mplfinance as mpf\nfrom sklearn.preprocessing import MinMaxScaler\n\n# + id=\"9Agxxf5eQw43\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 394} executionInfo={\"status\": \"ok\", \"timestamp\": 1640683006263, \"user_tz\": -420, \"elapsed\": 450, \"user\": {\"displayName\": \"fasdfaf ffafa\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"14111875001060407925\"}} outputId=\"6114b71d-9c8c-4fa0-c3da-df593df21769\"\n# Load data\npath = '/content/drive/MyDrive/Intro_DS_2021/Preprocessing Data/SAVA_preprocessed.csv'\ndf = pd.read_csv(path)\ndf[\"Date\"] = pd.to_datetime(df[\"Date\"])\ndf[\"Date\"] = df[\"Date\"].dt.strftime(\"%m/%d/%y\")\n\ndf = df.set_index('Date')\nclose=df[['Close']]\nclose.head(10)\n\n# + [markdown] id=\"vV2QeLBgGRWL\"\n# **ARIMA MODEL**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 971} id=\"G7ToBS5yxUxb\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640683010185, \"user_tz\": -420, \"elapsed\": 927, \"user\": {\"displayName\": \"fasdfaf ffafa\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"14111875001060407925\"}} outputId=\"ebd42f88-c4d8-4250-a6cf-81c4a8a51035\"\nclose.plot(y='Close', subplots=True, figsize=(15, 8), fontsize=12)\nplt.xlabel('timestamp', fontsize=12)\nplt.ylabel('Close', fontsize=12)\nplt.show()\n\n# Load 300 data\nclose[:300][['Close']].rename(columns={'Close':'train'}) \\\n .plot(y=['train'], figsize=(15, 8), fontsize=12)\nplt.xlabel('timestamp', fontsize=12)\nplt.ylabel('Close', fontsize=12)\nplt.show()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 286} id=\"84Qjc1v8xUxe\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640683013239, \"user_tz\": -420, \"elapsed\": 1636, \"user\": {\"displayName\": \"fasdfaf ffafa\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"14111875001060407925\"}} outputId=\"e5b3aea6-e80c-4d16-9286-5f4ee2ceba86\"\nplt.plot(close[:100].diff())\n\n# + [markdown] id=\"dlwA6G6dxUxg\"\n# ** Create training and testing data sets **\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 597} id=\"F891tZvaxUxv\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640683016303, \"user_tz\": -420, \"elapsed\": 706, \"user\": {\"displayName\": \"fasdfaf ffafa\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"14111875001060407925\"}} outputId=\"cd3c818b-88b0-4901-dab2-f3bbc815298b\"\nn = int(len(df) * 0.7)\nm = int(len(df) * 0.7)\n\ndf_train = close.copy()[:n][['Close']]\ndf_test = close.copy()[m:][['Close']]\n\nprint('Training data shape: ', df_train.shape)\nprint('Test data shape: ', df_test.shape)\n\nplot_acf(df_train['Close'])\nplot_pacf(df_train['Close'])\nplt.show\n\n# + [markdown] id=\"2PHZ5oS-xUx6\"\n# ** Data prepatation **\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 519} id=\"4Mn6U8InxUx9\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640683019407, \"user_tz\": -420, \"elapsed\": 1283, \"user\": {\"displayName\": \"fasdfaf ffafa\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"14111875001060407925\"}} outputId=\"19354bd2-e62c-4e56-c234-afdade2861e1\"\n#SCALE TRAIN \nscaler=MinMaxScaler()\ndf_train['Close']=scaler.fit_transform(df_train)\n\nclose[:n][['Close']].rename(columns={'Close':'original trade close'}).plot.hist(bins=100, fontsize=12)\ndf_train.rename(columns={'Close':'scaled trade close'}).plot.hist(bins=100, fontsize=12)\nplt.show()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 238} id=\"bW4NXtSyxUyG\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640683021319, \"user_tz\": -420, \"elapsed\": 439, \"user\": {\"displayName\": \"fasdfaf ffafa\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"14111875001060407925\"}} outputId=\"25073fb1-7334-4be9-8c96-7c4d2df42a04\"\n# SCALE TEST\ndf_test['Close'] = scaler.transform(df_test)\ndf_test.head()\n\n# + [markdown] id=\"q9duCNIHxUyI\"\n# ** Implemnt ARIMA method **\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"6nK7XYcKxUyJ\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640683023748, \"user_tz\": -420, \"elapsed\": 401, \"user\": {\"displayName\": \"fasdfaf ffafa\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"14111875001060407925\"}} outputId=\"1e1e33d8-1aeb-42d3-abec-33521d3fb276\"\n# Specify the number of steps to forcast ahead\nHORIZON=6\nprint('Forescating horizon:', HORIZON, 'days')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 238} id=\"7ReNEg_DxUyb\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640683025122, \"user_tz\": -420, \"elapsed\": 12, \"user\": {\"displayName\": \"fasdfaf ffafa\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"14111875001060407925\"}} outputId=\"a50c75f1-450c-4b26-a106-b684a72ac433\"\ndf_test_shifted = df_test.copy()\n\nfor t in range(1, HORIZON):\n df_test_shifted['Close+'+str(t)] = df_test_shifted['Close'].shift(-t)\n\ndf_test_shifted=df_test_shifted.dropna(how='any')\ndf_test_shifted.head(5)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"hSu30ulxxUyc\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640683029358, \"user_tz\": -420, \"elapsed\": 1901, \"user\": {\"displayName\": \"fasdfaf ffafa\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"14111875001060407925\"}} outputId=\"9bad51ec-a229-4502-c39b-e7cc8d230852\"\norder=(1,1,1)\nmodel=ARIMA(df_train,order=order)\nresults=model.fit()\n\nprint(results.summary())\n\n# + id=\"WC5kVWYGxUyg\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640683029359, \"user_tz\": -420, \"elapsed\": 9, \"user\": {\"displayName\": \"fasdfaf ffafa\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"14111875001060407925\"}}\nfrom statsmodels.tsa.stattools import adfuller\n\ndef check_stationarity(ts_data):\n \n # Q1 **********************Hoàn thành đoạn code sau đây*************\n # Rolling statistics\n roll_mean = ts_data.rolling(30, center=True, closed='both').mean()\n roll_std = ts_data.rolling(5, center=True, closed='both').std()\n #****************************************************************\n \n \n # Plot rolling statistics\n fig = plt.figure(figsize=(20,10))\n plt.subplot(211)\n plt.plot(ts_data, color='black', label='Original Data')\n plt.plot(roll_mean, color='red', label='Rolling Mean(30 days)')\n plt.legend()\n plt.subplot(212)\n plt.plot(roll_std, color='green', label='Rolling Std Dev(5 days)')\n plt.legend()\n \n # Dickey-Fuller test\n print('Dickey-Fuller test results\\n')\n df_test = adfuller(ts_data, regresults=False)\n test_result = pd.Series(df_test[0:4], index=['Test Statistic','p-value','# of lags','# of obs'])\n print(test_result)\n for k,v in df_test[4].items():\n print('Critical value at %s: %1.5f' %(k,v))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"8EmUGIllxUzP\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640683031692, \"user_tz\": -420, \"elapsed\": 8, \"user\": {\"displayName\": \"fasdfaf ffafa\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"14111875001060407925\"}} outputId=\"c7fbbaa0-b9cd-41d4-c37d-8793530ae969\"\ndf.index = pd.to_datetime(df.index, format=\"%m/%d/%y\")\ndf_final = pd.Series(df['Close'])\ntype(df_final)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 766} id=\"o7Q1EpXjxUzS\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640683035414, \"user_tz\": -420, \"elapsed\": 1548, \"user\": {\"displayName\": \"fasdfaf ffafa\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"14111875001060407925\"}} outputId=\"329390a9-7678-4cfa-9221-504f9956f83b\"\ncheck_stationarity(df_final)\n\n# + [markdown] id=\"T44cB_duxUzT\"\n# -> Dữ liệu chưa stationary\n\n# + id=\"Dwg1ntlAxUzW\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640683039273, \"user_tz\": -420, \"elapsed\": 400, \"user\": {\"displayName\": \"fasdfaf ffafa\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"14111875001060407925\"}}\ndf_final_diff = df_final - df_final.shift()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 768} id=\"hycmMxvSxUzY\" executionInfo={\"status\": \"ok\", \"timestamp\": 1640683041996, \"user_tz\": -420, \"elapsed\": 1084, \"user\": {\"displayName\": \"fasdfaf ffafa\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"14111875001060407925\"}} outputId=\"0867cef6-97e7-4e02-ff14-e94cd82269f8\"\ndf_final_diff.dropna(inplace=True)\ncheck_stationarity(df_final_diff)\n\n# + [markdown] id=\"OkL1yVYrxUza\"\n# -> Dữ liệu đã stationary\n\n# + [markdown] id=\"8VuqkjSzxUzb\"\n# ** Evaluate the model **\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 415} id=\"uUVPGJRBxUzb\" executionInfo={\"status\": \"error\", \"timestamp\": 1640683735686, \"user_tz\": -420, \"elapsed\": 1031, \"user\": {\"displayName\": \"fasdfaf ffafa\", \"photoUrl\": \"https://lh3.googleusercontent.com/a/default-user=s64\", \"userId\": \"14111875001060407925\"}} outputId=\"91add506-79e6-457e-af2b-0b65111bcd47\"\norder = (2, 1, 2)\n\ntraining_window= 30 # dedicate 30 days for training\n\ntrain_ts=df_train['Close']\ntest_ts=df_test_shifted\n\nhistory=[x for x in train_ts]\nhistory=history[(-training_window):]\n\npredictions=list()\n\nfor i in range(test_ts.shape[0]):\n model = ARIMA(history, order=order)\n model_fit = model.fit()\n output = model_fit.forecast(steps=HORIZON)\n predictions.append(output)\n obs=list(test_ts.iloc[i])\n history.append(obs[0])\n history.pop(0)\n\n# + id=\"ds645EdSxUze\" outputId=\"328cf441-5277-4d78-f0ab-5058f55b65af\"\n# evaluate forecasts\nrmse = math.sqrt(mean_squared_error(test_ts, predictions))\nprint('Test RMSE: %.3f' % rmse)\n\n# + id=\"YghtPkraxUzl\" outputId=\"ac2775b9-1f56-4b06-9ec7-9b37f007f538\"\neval_df = pd.DataFrame(predictions, columns=['t+'+str(t) for t in range(1, HORIZON+1)])\neval_df['timestamp'] = df_test.index[0:len(df_test.index)-HORIZON+1]\neval_df = pd.melt(eval_df, id_vars='timestamp', value_name='prediction', var_name='h')\neval_df['actual'] = np.array(np.transpose(test_ts)).ravel()\neval_df[['prediction', 'actual']] = scaler.inverse_transform(eval_df[['prediction', 'actual']])\neval_df.head()\n\n# + id=\"a9kWEeMLxUzu\" outputId=\"8c8a0e19-be35-47da-e997-e3a5c67819c4\"\nif(HORIZON == 1):\n ## Plotting single step forecast\n eval_df.plot(x='timestamp', y=['actual', 'prediction'], style=['r', 'b'], figsize=(15, 8))\n\nelse:\n ## Plotting multi step forecast\n plot_df = eval_df[(eval_df.h=='t+1')][['timestamp', 'actual']]\n for t in range(1, HORIZON+1):\n plot_df['t+'+str(t)] = eval_df[(eval_df.h=='t+'+str(t))]['prediction'].values\n\n fig = plt.figure(figsize=(15, 8))\n ax = plt.plot(plot_df['timestamp'], plot_df['actual'], color='red', linewidth=4.0)\n ax = fig.add_subplot(111)\n for t in range(1, HORIZON+1):\n x = plot_df['timestamp'][(t-1):]\n y = plot_df['t+'+str(t)][0:len(x)]\n ax.plot(x, y, color='blue', linewidth=4*math.pow(.9,t), alpha=math.pow(0.8,t))\n \n ax.legend(loc='best')\n \nplt.xlabel('timestamp', fontsize=12)\nplt.ylabel('Close', fontsize=12)\nplt.show()\n","repo_name":"khoanguyenvietmanh/Stock_Price_Prediction","sub_path":"Code Notebook/ARIMAModel_2009_2019_BML_ver1.5.ipynb","file_name":"ARIMAModel_2009_2019_BML_ver1.5.ipynb","file_ext":"py","file_size_in_byte":12965,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"28010696124","text":"# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# \"Open\n\n# + [markdown] id=\"VTUYuDVyRi6M\" colab_type=\"text\"\n# ##Mnist classifier using Keras [ResNet - 8 layers]\n\n# + id=\"TFnM_KLIRgU-\" colab_type=\"code\" colab={}\n\nfrom __future__ import print_function\nimport keras\nfrom keras.datasets import mnist\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras import backend as K\n\n# + id=\"dMNscGyGa9nC\" colab_type=\"code\" colab={}\nbatch_size = 128\nnum_classes = 10\nepochs = 12\n\n# + id=\"eZ-mk9FMvcTd\" colab_type=\"code\" colab={}\n# input image dimensions\nimg_rows, img_cols = 28, 28\n\n# + id=\"vDwYLSdAvewn\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 51} outputId=\"685584c4-a51a-4659-b1ac-05f1d3173fc8\"\n# the data, split between train and test sets\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\n\n# + id=\"H8LcyrOyvgIH\" colab_type=\"code\" colab={}\nif K.image_data_format() == 'channels_first':\n x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)\n x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)\n input_shape = (1, img_rows, img_cols)\nelse:\n x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)\n x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)\n input_shape = (img_rows, img_cols, 1)\n\n# + id=\"FNidO-73vhrE\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 68} outputId=\"48aab866-137e-4a1b-a64f-162611caa4db\"\nx_train = x_train.astype('float32')\nx_test = x_test.astype('float32')\nx_train /= 255\nx_test /= 255\nprint('x_train shape:', x_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\n\n\n# + id=\"xy8w9MPNvjH4\" colab_type=\"code\" colab={}\n# convert class vectors to binary class matrices\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\n# + id=\"rfC_lVj1vlK_\" colab_type=\"code\" colab={}\n#Resnet architecture qwith only 8 layers\n\nmodel = Sequential()\nmodel.add(Conv2D(32, kernel_size=(3, 3),\n activation='relu',\n input_shape=input_shape))\nmodel.add(Conv2D(64, (3, 3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Conv2D(64, (3, 3), activation='relu'))\nmodel.add(Conv2D(128, (3, 3), activation='relu'))\nmodel.add(Conv2D(128, (3, 3), activation='relu'))\nmodel.add(Conv2D(256, (3, 3), activation='relu'))\nmodel.add(Dropout(0.25))\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(num_classes, activation='softmax'))\n\n# + id=\"p8WIr806vncA\" colab_type=\"code\" colab={}\nmodel.compile(loss=keras.losses.categorical_crossentropy,\n optimizer=keras.optimizers.Adadelta(),\n metrics=['accuracy'])\n\n# + id=\"sS8VbL1WvqTo\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 479} outputId=\"3ce8e4fd-a213-4c28-a5ae-0843d77fbc80\"\nmodel.fit(x_train, y_train,\n batch_size=batch_size,\n epochs=epochs,\n verbose=1,\n validation_data=(x_test, y_test))\n\n# + id=\"wihOlsIPvsVY\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 51} outputId=\"8ad24626-a060-4438-fbc5-1801018942ff\"\nscore = model.evaluate(x_test, y_test, verbose=0)\nprint('Test loss:', score[0])\nprint('Test accuracy:', score[1])\n","repo_name":"Ranjani94/Deep_Learning","sub_path":"Graded_Assignment_4/ResNet_Keras_8layers.ipynb","file_name":"ResNet_Keras_8layers.ipynb","file_ext":"py","file_size_in_byte":3647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"31789290754","text":"# + colab={} colab_type=\"code\" id=\"VNuA8AEBVVnC\"\nimport numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 237} colab_type=\"code\" id=\"1FP5o4E_Vtci\" outputId=\"b429cd7e-2d6a-42bc-d8ab-6d800f083aeb\"\nimg = cv2.imread('hockney.jpg')\nimg_cvt=cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\nplt.imshow(img_cvt)\nplt.show()\n\n# + colab={} colab_type=\"code\" id=\"2GVRCOLuW42Z\"\n# Converting RGB image to Grayscale\ngray = cv2.cvtColor(img_cvt, cv2.COLOR_RGB2GRAY)\n\nplt.imshow(gray)\nplt.show()\n# -\n\ntype(gray) # ndarray\nprint(gray)\nprint(gray.shape)\n\ngray = cv2.resize(gray, (256,256))\nplt.imshow(gray)\nplt.show()\n\ngray.shape\n\n\n# Function to calculate R1 and R2\ndef getRvals(img, L):\n \n # Initialization\n R1 = 0\n R2 = 0\n Wdth = img.shape[0]\n Hght = img.shape[1]\n \n for i in range(0, Hght):\n for j in range(0, Wdth):\n \n R1 += pow(-1, i + j) * img[i][j]\n R2 += pow(-1, i + j + 1) * img[i][j]\n\n return abs(R1//(Hght*L)), abs(R2//(Wdth*L))\n\n\nL = 64 # Assumed in paper\nR1, R2 = getRvals(gray, L)\nR1, R2\n\n\ndef CreateVectors(img, L):\n \n FragsPerRow = img.shape[0]//L\n vecs = []\n \n for tempvecs in img:\n for i in range(0, FragsPerRow):\n vecs.append(tempvecs[i*L : (i + 1)*L])\n \n return vecs\n\n\n# Random Number Generator \ndef RandomNumGen(seed, iters, L):\n op = seed\n while iters:\n op = (29 * seed + 13) % L\n seed = op\n iters -= 1\n \n return op\n\n\n# Crossover Function\ndef Crossover(vector, x, y, L):\n \n if x < L and y < L:\n coI = x # Crossover Index\n else:\n coI = 0\n \n coIter = (13 * x + 17 * y) % L\n \n for j in range(0, coIter, 2):\n \n N1 = RandomNumGen(coI, j, L)\n N2 = RandomNumGen(coI, j + 1, L)\n temp = vector[N1]\n vector[N1] = vector[N2]\n vector[N2] = temp\n \n return vector\n \n\n\n# Mutation Function\ndef Mutation(vector, x, y, L):\n \n if x < L and y < L:\n muI = y # Mutation Index\n else:\n muI = 0\n \n muIter = (23 * x + 29 * y) % L\n for j in range(0, muIter):\n \n N1 = RandomNumGen(muI, j, L)\n \n vector[N1] = 255 - vector[N1]\n \n return vector\n \n\n\n# +\n# Driver Code\n\nImgVector = CreateVectors(gray, L)\n\nfor i in range(0, len(ImgVector)):\n \n ImgVector[i] = Crossover(ImgVector[i], R1, R2, L)\n ImgVector[i] = Mutation(ImgVector[i], R1, R2, L)\n R1 += 1\n R2 += 1\n\nWdth = gray.shape[0]\nHght = gray.shape[1]\nCryptImg = np.zeros((Hght, Wdth))\ncount = 0\n\nfor i in range(0, len(CryptImg)):\n \n temp = np.append([], ImgVector[count*(Wdth//L) : (count + 1)*(Wdth//L)])\n count += 1\n CryptImg[i] = temp\n\nplt.title(\"Encrypted Image\") \nplt.imshow(CryptImg)\nplt.show()\ncv2.imwrite(\"output_GA.jpg\", gray)\n# -\n\n\n","repo_name":"RajatGarg97/Image-Encryption","sub_path":"implementation/code.ipynb","file_name":"code.ipynb","file_ext":"py","file_size_in_byte":2881,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"13515797949","text":"# ## Encoding the knowledge base into Hyperdimensional Vectors\n#\n# In this notebook the functions from the 'HDComputing' notebook are used to encode the McRae dataset. The following functions create an heteroassociative memory in which a knowledge base of Semantic Features representation of concepts is stored.\n#\n# ### Importing libraries and HD computing functions\n\n# +\nimport pandas as pd\nimport nltk\n\n#Only done once... \n#nltk.download('wordnet')\n#nltk.download('wordnet_ic')\n\nfrom nltk.corpus import wordnet as wn\nfrom nltk.corpus import wordnet_ic\n\n# Declare functions and class...\n# %run HDComputing_basics.ipynb \n# -\n\n# ### Functions for reading dataset\n\n# +\ndef TranslateFeats(ListFeat):\n \"It receives a list of features such as ['is_blue', 'is_rectangular'] and it returns: [['color','blue'], ['shape','rectangular']\"\n # Dataframe for excel document\n df = pd.read_excel(pathh + 'FEATS_brm.xlsx') #../McRaedataset/FEATS_brm.xlsx')\n ListPairs = []\n for feat in ListFeat:\n # Row for feature...\n row = df.loc[df['Feature'] == feat] \n # Look for values in vec_feat and vec_value\n ListPairs.append([str(row['feat_name'].tolist()[0]), str(row['feat_value'].tolist()[0])]) \n return ListPairs\n\ndef ReadDefinitions():\n \"Given an xlsx file it returns all the concepts feature values as they appear in the original dataset\"\n #Dataframe for excel document\n df = pd.read_excel( pathh + 'CONCS_FEATS_concstats_brm.xlsx') #../McRaeDataset/CONCS_FEATS_concstats_brm.xlsx') #MINI_\n #Create a list with all concept names\n names = set(df['Concept'])\n # Extract list of features for each name\n Concepts = []\n for n in names:\n row = df.loc[df['Concept'] == n]\n Concepts.append([str(n), map(str,list(row['Feature']))])\n return Concepts\n\ndef ClosestConcepts (concept, nc):\n \"Given a concept label this function reads the distance matrix from McRae's and returns the 'nc' closests concepts in a list\"\n # Excel document to data frame...\n try:\n df = pd.read_excel(pathh + 'cos_matrix_brm_IFR.xlsx','1st_200') #../McRaeDataset/cos_matrix_brm_IFR.xlsx', '1st_200')\n ordered = df.sort_values(by=concept, ascending=False)[['CONCEPT', concept]]\n except: \n try:\n df = pd.read_excel(pathh + 'cos_matrix_brm_IFR.xlsx','2nd_200') # ('../McRaeDataset/cos_matrix_brm_IFR.xlsx', '2nd_200')\n ordered = df.sort_values(by=concept, ascending=False)[['CONCEPT', concept]]\n except:\n df = pd.read_excel(pathh + 'cos_matrix_brm_IFR.xlsx','last_141') #('../McRaeDataset/cos_matrix_brm_IFR.xlsx', 'last_141')\n ordered = df.sort_values(by=concept, ascending=False)[['CONCEPT', concept]]\n \n L1 = list(ordered['CONCEPT'][0:nc])\n L1 = map(str, L1)\n L2 = zip(L1,list(ordered[concept][0:nc]))\n L2 = map(list, L2)\n \n return L2\n\n\n# -\n\n# ## Storing ID vectors into memory\n#\n# ### Creating definitions dictionary\n\ndef CreateDictionary():\n global Dict_defs\n data = ReadDefinitions()\n for concept in data:\n Dict_defs[concept[0]] = TranslateFeats(concept[1])\n\n\n# ### Memory functions\n\n# +\ndef flat_list (L):\n \"Recursive function that flats a list of lists (at any level)\"\n if L == []:\n return L\n if type(L[0]) is list:\n return flat_list(L[0]) + flat_list(L[1:])\n return L[:1] + flat_list(L[1:])\n\ndef FeatureVectors(Dic):\n \"It extract from the definition dictionary all the feature type vectors ('is','has','color', etc...)\"\n global feature_vectors\n featt = []\n vals = Dic.values()\n for l in vals:\n for p in l:\n featt.append(p[0])\n feature_vectors = list(set(featt))\n \n \ndef SaveConcepts(Dic):\n \"\"\"Given a definitions dictionary it stores in memory the entire set of concepts in the dictionary (including feature vectors)\"\"\"\n keys = list(Dic.keys())\n vals = list( Dic.values() )\n all_concepts = list(set(flat_list(vals) + keys))\n # Process for storing list of concepts in memory\n for concept in all_concepts:\n HDvector(N,concept) #This creates an object and store it in memory \n \ndef CreateSemanticPointer (PairList):\n \"Turns list as [[feat1,feat_val],[feat2,feat_val],[feat3,feat_val]] into vector feat1*feat_val + feat2*feat_val ...\"\n vecs = []\n for pair in PairList:\n vecs.append(Dict[pair[0]] * Dict[pair[1]])\n return ADD(vecs)\n\ndef SaveDefinitions(Dic):\n \"\"\"Given the definitions dictionary, and having all its concepts previously stored in memory, this functions\n creates a definition vector (semantic pointer) using HD operations and assign it as a pointer to an \n object vector (ID vector).\"\"\"\n global feature_vectors\n # Going through all elements in dictionary\n for key, value in Dic.items():\n Dict[key].setPointer(CreateSemanticPointer(value))\n \ndef NormalizeHammDist (Dist_list):\n \"Given a distance list of the form [['name', dist], ['name', dist], ... ], it normalize each distance and return a list with the same form\"\n for i in range(len(Dist_list)):\n Dist_list[i][1] = round( 1. - Dist_list[i][1] / float(N), 3 ) \n return Dist_list\n\n\n# -\n\n# ### Initializing memory\n\ndef Init_mem():\n init()\n print(\"Begining to encode dataset...\")\n thr = 0.45 * N\n # Read dataset and create definition dictionary\n CreateDictionary()\n # Feature vectors\n FeatureVectors(Dict_defs)\n # Save concepts into memory (ID vectors)\n SaveConcepts(Dict_defs)\n # Associate definitions to concepts into memory (SP vectors)\n SaveDefinitions(Dict_defs)\n print(\"End of encoding\")\n\n\n# ## Reading similarity from distance matrix (McRae)\n\ndef McRae_simi (pair_concepts):\n \"Given a pair of concepts (in a list) it consults the similarity from the cos_matrix... file\"\n try: \n df = pd.read_excel(pathh + 'cos_matrix_brm_IFR.xlsx','1st_200')\n return list(df.loc[df['CONCEPT'] == pair_concepts[0]][pair_concepts[1]])[0]\n except:\n try:\n df = pd.read_excel(pathh + 'cos_matrix_brm_IFR.xlsx','2nd_200')\n return list(df.loc[df['CONCEPT'] == pair_concepts[0]][pair_concepts[1]])[0]\n except:\n df = pd.read_excel(pathh + 'cos_matrix_brm_IFR.xlsx','last_141')\n return list(df.loc[df['CONCEPT'] == pair_concepts[0]][pair_concepts[1]])[0]\n\n\n# ## Semantic similarity using NLTK library functions\n# ### Auxiliar functions\n\n# +\nbrown_ic = wordnet_ic.ic('ic-brown.dat')\n\ndef get_concepts_list ():\n \"Returns a list of strings: the names of the concepts\"\n df = pd.read_excel(pathh + 'CONCS_Synset_brm.xlsx') #../McRaedataset/CONCS_Synset_brm.xlsx')\n return map(str, list(df['Concept']))\n \ndef get_synset (concept):\n \"Given a concept name (string) it returns its synset (string)\"\n # Dataframe for excel document\n df = pd.read_excel(pathh + 'CONCS_Synset_brm.xlsx') #../McRaedataset/CONCS_Synset_brm.xlsx')\n row = df.loc[df['Concept'] == concept]\n return str(list(row['Synset'] )[0])\n\ndef apply_sim_metric ( similarity_metric, num, in_concept, corpus = None):\n \"Given a similarity_metric function it returns a list of the num closest concepts to 'concept'\"\n dist_list = []\n for c in Concepts:\n c_synset = wn.synset( get_synset(c) )\n if corpus:\n dist_list.append([c, round(similarity_metric(in_concept, c_synset, corpus), 3) ])\n else:\n dist_list.append([c, round(similarity_metric(in_concept, c_synset), 3) ])\n return sorted(dist_list, key = lambda r : r[1], reverse = True ) [:num]\n\ndef similarity_fun ( similarity_metric, pair, corpus = None):\n \"Given a similarity_metric function it returns a list of the num closest concepts to 'concept'\"\n c_synset_1 = wn.synset( get_synset(pair[0]))\n c_synset_2 = wn.synset( get_synset(pair[1]))\n if corpus:\n return round(similarity_metric(c_synset_1, c_synset_2, corpus), 3)\n else:\n return round(similarity_metric(c_synset_1, c_synset_2), 3)\n\n\n# -\n\n# ## New similarity metric: Extended Gloss Overlap\n\n# +\nimport re\nfrom nltk.stem.porter import PorterStemmer\n\nHYPE = 'hypernymy'\nHYPO = 'hyponymy'\nGLOSS = 'gloss'\nMERONYMY = 'meronymy'\n\ndef glossOverlap(gloss1, gloss2):\n # stopws = stopwords.words('english')\n stopws = ['i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you', \n 'your', 'yours', 'yourself', 'yourselves', 'he', 'him', 'his', 'himself', 'she', \n 'her', 'hers', 'herself', 'it', 'its', 'itself', 'they', 'them', 'their', 'theirs', \n 'themselves', 'what', 'which', 'who', 'whom', 'this', 'that', 'these', 'those', \n 'a', 'an', 'the', 'and', 'but', 'if', 'or', 'because', 'as', \n 'until', 'while', 'of', 'at', 'by', 'for', 'with', 'about', 'against', 'between', 'into', \n 'through', 'during', 'before', 'after', 'above', 'below', 'to', 'from', 'up', 'down', \n 'in', 'out', 'on', 'off', 'over', 'under', 'then', \n 'there', 'when', 'where', 'why', 'how', 'all', 'any', 'both', 'each',\n 'other', 'some', 'such', 'no', 'nor', 'not', 'only', 'own', 'same', 'so', \n 'than', 's', 't', 'just', 'don']\n\n stemmer = PorterStemmer()\n\n # print \"-\"*50\n # for x in stopws:\n # if stemmer.stem_word(x) != x:\n # print x, stemmer.stem_word(x)\n\n def longestOverlap(a, b):\n now = [0]*len(b)\n bestOverlap = 0\n aStart = 0\n bStart = 0\n\n nextNonStopWord = [-1]*(len(a)+1)\n for i in range(len(a)-1, 0, -1):\n if a[i] not in stopws:\n nextNonStopWord[i] = i\n else:\n nextNonStopWord[i] = nextNonStopWord[i+1]\n\n for i in range(1, len(a)):\n prev = now\n now = [0]*len(b)\n if a[i] == '#':\n continue\n for j in range(1, len(b)):\n if b[j] == '#':\n continue\n if a[i] == b[j]:\n now[j] = max(now[j], prev[j-1] + 1)\n if a[i] in stopws:\n continue\n\n overlap = now[j]\n start = i - overlap + 1\n start = nextNonStopWord[start]\n overlap = i - start + 1\n if bestOverlap < overlap:\n bestOverlap = overlap\n aStart = i - overlap + 1\n bStart = j - overlap + 1\n\n return (bestOverlap, aStart, bStart)\n\n\n regex = ',|\\.|\\s|\\?|\\'|\\\"|!|;|-'\n #maybe check what happens if we don't stem the glosses\n a1 = ['#'] + [stemmer.stem(x.lower()) for x in re.split(regex, gloss1) if x]\n a2 = ['#'] + [stemmer.stem(x.lower()) for x in re.split(regex, gloss2) if x]\n\n score = 0\n (overlap, start1, start2) = longestOverlap(a1, a2)\n while overlap > 0:\n # print overlap\n # print a1[start1:start1+overlap]\n # print a2[start2:start2+overlap]\n a1[start1:start1+overlap] = ['#']\n a2[start2:start2+overlap] = ['#']\n score += overlap**2\n (overlap, start1, start2) = longestOverlap(a1, a2)\n\n return score\n\n\ndef getRelationGloss(synset, r):\n synsets = []\n if r == HYPE:\n synsets = synset.hypernyms()\n elif r == HYPO:\n synsets = synset.hyponyms()\n elif r == GLOSS:\n synsets = [synset]\n elif r == MERONYMY:\n synsets = synset.member_meronyms() + synset.part_meronyms() + synset.substance_meronyms()\n else:\n #to do: add other relations if necessary\n raise Exception(\"Unknown relation %s\" % r)\n\n glosses = [x.definition() for x in synsets]\n strr = \" \".join(glosses)\n return strr\n\ndef GlossRelatedness(synset1, synset2):\n relpairs = [(GLOSS, GLOSS)] #, (HYPE, HYPE), (HYPO, HYPO), (HYPE, GLOSS), (GLOSS, HYPE)]\n ret = 0\n for (r1, r2) in relpairs:\n gloss1 = getRelationGloss(synset1, r1)\n gloss2 = getRelationGloss(synset2, r2)\n\n ret += glossOverlap(gloss1, gloss2)\n return ret\n\n","repo_name":"jobquiroz/VSA_concepts","sub_path":"Code/EncodingDataset.ipynb","file_name":"EncodingDataset.ipynb","file_ext":"py","file_size_in_byte":11948,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"70683339589","text":"# +\nimport pandas as pd\nimport numpy as np\nimport networkx as nx\nimport json\nimport requests\n\nimport tweepy\nfrom tweepy import Client\n\nkey = \"\"\nsecret = \"\"\ntoken = \"\"\n\napi = tweepy.Client(bearer_token=token, consumer_key=key, consumer_secret=secret, \n return_type=requests.Response,\n wait_on_rate_limit=True)\n# -\n\nalready_processed = [1016773517587537920,\n 837316817324556289,\n 4307623643,\n 844779426260791296,\n 790017240733278208,\n 913028718377005056,\n 2855732920,\n 1416121214,\n 821215184660393986,\n 1004764640486854656,\n 352132252,\n 1661404440,\n 2928556470,\n 2901953015,\n1058130850578137089]\n\n# +\nimport os\n\nalready_processed = []\n \nfor name in os.listdir('bot'):\n if os.path.isdir(name):\n continue\n list_name = name.replace('.pkl','').replace('edgelist_2_edges_from_start_','')\n already_processed.append(int(list_name))\n# -\n\ncombined = pd.read_pickle('node_and_degree_list.pkl')\ncombined.head()\n\n# +\n# Set follower/following threshold\nthresh = 1000\n\nprint('BEFORE FILTERING')\nprint(f'Total accounts: {combined.shape[0]}')\nnb = combined.loc[combined.label == 'bot'].shape[0]\nnh = combined.loc[combined.label == 'human'].shape[0]\nprint(f'Bot accounts: {nb}')\nprint(f'Human accounts: {nh}')\nprint('____________________')\n\n\n# Drop accounts that exceed threshold\nsmall = combined.loc[combined.followers_count < thresh]\nsmall = small.loc[small.followers_count < thresh]\n\nprint('AFTER FILTERING')\nprint(f'Total accounts: {small.shape[0]}')\nnb = small.loc[small.label == 'bot'].shape[0]\nnh = small.loc[small.label == 'human'].shape[0]\nprint(f'Bot accounts: {nb}')\nprint(f'Human accounts: {nh}')\n# -\n\n# Small df contains accounts meeting threshold criteria\nsmall.head()\n\n\n# Create curr_edgelist for a network including nodes up to 3 degrees of separation (3 links away)\ndef add_this_nodes_edgelist(this_acc, curr_edgelist):\n next_page_token = None\n visited.add(this_acc)\n\n action = 'followers'\n follow_list = []\n this_acc_num_following = [] \n this_acc_num_followers = []\n while True:\n # Get immediate followers/following of node and add these to curr_edgelist\n if action == 'followers':\n request = api.get_users_followers(id=this_acc, user_auth=False, \n max_results=1000, pagination_token=next_page_token, user_fields=['public_metrics'])\n elif action == 'following':\n request = api.get_users_following(id=this_acc, user_auth=False, \n max_results=1000, pagination_token=next_page_token, user_fields=['public_metrics'])\n\n data = request.json()\n\n # for each account following/followed by the originating account, record account id, \n # num following, and num followed by\n try:\n for acc in data['data']:\n follow_list.append(acc['id'])\n num_following = acc['public_metrics']['following_count']\n num_followed_by = acc['public_metrics']['followers_count']\n this_acc_num_following.append(num_following)\n this_acc_num_followers.append(num_followed_by)\n\n this_acc_list = [this_acc for i in range(len(follow_list))]\n\n # Catch errors if not authorized to view user\n except Exception as e:\n print('Exception: issue retrieving follow lists for this account -- Skipping.')\n return curr_edgelist\n \n \n if 'next_token' in data['meta'].keys(): # get page token for next request\n next_page_token = data['meta']['next_token']\n \n # when all data recorded transition to next action\n else:\n next_page_token = None\n if action == 'followers':\n d = {'originating_id': follow_list,\n 'receiving_id': this_acc_list,\n 'originating_following_count': this_acc_num_following, \n 'originating_follower_count': this_acc_num_followers}\n edges_to_add = pd.DataFrame(d)\n curr_edgelist = pd.concat([curr_edgelist, edges_to_add])\n\n action = 'following'\n\n # reset lists\n follow_list = []\n this_acc_num_following = [] \n this_acc_num_followers = []\n\n elif action == 'following':\n d = {'originating_id': this_acc_list,\n 'receiving_id': follow_list,\n 'receiving_following_count': this_acc_num_following, \n 'receiving_follower_count': this_acc_num_followers}\n edges_to_add = pd.DataFrame(d)\n curr_edgelist = pd.concat([curr_edgelist, edges_to_add])\n\n next_page_token = None\n\n return curr_edgelist\n\n\n# +\ndef transition_to_next_separation_degree(curr_edgelist, degrees_of_separation):\n try:\n # Drop all nodes with followers or following more than threshold\n to_drop = (curr_edgelist.originating_following_count > thresh) | \\\n (curr_edgelist.originating_follower_count > thresh) | \\\n (curr_edgelist.receiving_following_count > thresh) | \\\n (curr_edgelist.receiving_follower_count > thresh)\n curr_edgelist.drop(index = curr_edgelist[to_drop].index, inplace=True)\n\n # create list of all neighbors in curr_edgelist df\n unvisited_neighbors = list(curr_edgelist.originating_id.append(curr_edgelist.receiving_id).unique())\n\n # if any nodes are in visited set, remove\n [unvisited_neighbors.remove(i) for i in unvisited_neighbors if i in visited]\n\n print()\n print(f'Current Number of edges from starting node {degrees_of_separation}')\n print(f'Num unvisited neighbors: {len(unvisited_neighbors)}')\n print('--------------------')\n degrees_of_separation +=1 \n \n return curr_edgelist, degrees_of_separation, unvisited_neighbors\n \n \n except Exception as e:\n print(e)\n print('--------------------EXCEPTION--------------------')\n return curr_edgelist, degrees_of_separation, []\n \n \n# -\n\nfrom tqdm.notebook import tqdm\n\n# +\ncols=['originating_id', 'receiving_id', \n 'originating_following_count', 'originating_follower_count',\n 'receiving_following_count', 'receiving_follower_count']\n\n# Process human accounts \nsmall_bot_accs = small.loc[small.label == 'bot']\n\n# Create Edgelists for each account in the filtered botometer dataset.\nfor starting_acc, label in zip(small_bot_accs.twitter_id, small_bot_accs.label):\n if starting_acc in already_processed:\n continue\n print(f'Starting node == {starting_acc}')\n # Initialization code for populating edgelist starting from node specified by \"starting_acc\"\n edgelist = pd.DataFrame(columns=cols)\n\n degrees_of_separation = 0\n\n visited = set()\n visited.add(starting_acc)\n\n edgelist = add_this_nodes_edgelist(starting_acc, edgelist) \n edgelist, degrees_of_separation, unvisited_neighbors = transition_to_next_separation_degree(edgelist, degrees_of_separation)\n \n # iterate thru all unvisited neighbors with 2 degree of separation from starting (labeled) node\n # process df in chunks before concatenating\n while degrees_of_separation <= 1:\n curr_edgelist = pd.DataFrame(columns=cols)\n for i in tqdm(unvisited_neighbors):\n print(i)\n curr_edgelist = add_this_nodes_edgelist(i, curr_edgelist)\n visited.add(i)\n \n curr_edgelist, degrees_of_separation, unvisited_neighbors = transition_to_next_separation_degree(curr_edgelist, degrees_of_separation)\n edgelist = pd.concat([edgelist, curr_edgelist])\n\n # Save in directory\n fn = 'edgelist_2_edges_from_start_' + str(starting_acc) + '.pkl'\n path = str(label) + '/' + fn\n edgelist.to_pickle(path)\n \n # Add twitter id to already processed list\n already_processed.append(starting_acc)\n\n# +\nwhile degrees_of_separation <= 1:\n for i in tqdm(unvisited_neighbors):\n print(i)\n curr_edgelist = add_this_nodes_edgelist(i, curr_edgelist)\n visited.add(i)\n\n curr_edgelist, degrees_of_separation, unvisited_neighbors = transition_to_next_separation_degree(curr_edgelist, degrees_of_separation)\n edgelist = pd.concat([edgelist, curr_edgelist])\n\n# Save in directory\nfn = 'edgelist_2_edges_from_start_' + str(starting_acc) + '.pkl'\npath = str(label) + '/' + fn\nedgelist.to_pickle(path)\n\n# Add twitter id to already processed list\nalready_processed.append(starting_acc)\n# -\n\n\n","repo_name":"julialromero/Twitter-Bot-Detection","sub_path":"code/download-follows-script.ipynb","file_name":"download-follows-script.ipynb","file_ext":"py","file_size_in_byte":8531,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"18129161277","text":"# + [markdown] id=\"7BRvbQNKZFeV\" colab_type=\"text\"\n# # Hotel customer comments analysis\n\n# + [markdown] id=\"jaeG7TWvaY5Z\" colab_type=\"text\"\n# ## Import library\n\n# + id=\"mqsiDRqRZFeX\" colab_type=\"code\" colab={}\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n# %matplotlib inline\nimport math\nimport pandas as pd\nimport numpy as np\nfrom tqdm import tqdm\nfrom collections import Counter\nimport operator\nimport re\nimport nltk\nfrom nltk.sentiment import SentimentAnalyzer\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer\nfrom nltk.sentiment.util import *\nfrom nltk import tokenize\nfrom nltk.corpus import stopwords\nfrom nltk.tag import PerceptronTagger\nfrom nltk.data import find\nimport sklearn\nimport sklearn.metrics as metrics\n\n# + [markdown] id=\"wPXx3GYfZFeb\" colab_type=\"text\"\n# ## Data overview\n\n# + [markdown] id=\"W1N8O-SKZFeb\" colab_type=\"text\"\n# I crawl a specific dataset for hotels reviews on Tripadvisor in Calgary, Canada. I used a tool called Tripadvisor Crawler. It is a very handy tool, however, it is a little bit unstable.\n#\n# In this project we also familiarize ourselves with the nltk library and an nltk sentiment analysis package called Vader.\n#\n# Reference: https://github.com/aesuli/trip-advisor-crawler.\n\n# + id=\"HAJTZODBZFec\" colab_type=\"code\" colab={} outputId=\"179f8d5f-4180-4a7c-a334-68fdb3a37157\"\nhotelDf = pd.read_csv('reviews.csv', header = None)\n# if not indicate 'header = None', it will skip the first line not reading\nhotelDf.columns=['idNum','filePath','hotelName','reviewColumn','ratingScore','groundTruth']\nhotelDf.head()\n\n# + id=\"SA313ImUZFeh\" colab_type=\"code\" colab={} outputId=\"65289503-c532-4caf-d22a-c2318816de1a\"\nhotelDf.shape\n\n# + id=\"UhC-k1CfZFek\" colab_type=\"code\" colab={}\n# if wanna compute the avg of the star rating, binarize it to like = 1 (rating = 4,5) and dislike = 0 (rating = 1,2,3)\nhotelDF = hotelDf.copy()\nhotelDF['ratingScore'] = hotelDf['ratingScore'].map(lambda x: 1 if x>3 else 0)\n\n# + id=\"YYfrXX8KZFen\" colab_type=\"code\" colab={}\n# method2 - easier\n# http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.replace.html\n# hotelDf_new = hotelDf.replace({[4,5]: 1, [1,2,3]: 0})\n\n# + id=\"NyQ3hciXZFeq\" colab_type=\"code\" colab={} outputId=\"82ed7c38-93f4-42c1-b46c-b80f1806747b\"\n# after running Vader, there is a bug: 'float' object has no attribute 'encode'\n# that means my data (reviews column) has null values, which leading to treating nan as float\n# so we need to analyse and drop all the null values\nhotelDf['reviewColumn'].isnull().sum()\n\n# + id=\"0sEd6SaAZFet\" colab_type=\"code\" colab={}\nhotelDF = hotelDF.dropna()\n\n# + id=\"wUD5bxHyZFew\" colab_type=\"code\" colab={}\n# this step is to deal with the problem that index of new df after drop nan different with review vader df index\n# because after drop null, the index is removed\n# but the vader sentiment score df is normal df, index from 0 to last, none index empty\n# if not adjust the orignal df index, the \nhotelDF = hotelDF.reset_index()\nhotelDF = hotelDF.drop(columns = ['index'])\n# or a better method:\n# https://stackoverflow.com/questions/40755680/how-to-reset-index-pandas-dataframe-after-dropna-pandas-dataframe\n\n# + id=\"NfDIML8aZFez\" colab_type=\"code\" colab={} outputId=\"0300c837-e455-43e4-f925-8f27e67f1bb0\"\nhotelDF.head()\n\n\n# + [markdown] id=\"yXWCIsQofenn\" colab_type=\"text\"\n# ## Sentiment analysis\n\n# + [markdown] id=\"Yi5PpNPfflZ_\" colab_type=\"text\"\n# Compute average Vader sentiment and average ground truth rating per hotel.\n#\n# Rank hotels by avg ground-truth sentiment and avg Vader sentiment score.\n\n# + id=\"WfEu3PZuZFe3\" colab_type=\"code\" colab={}\n# To compute avg Vader sentiment, we should first compute the Vader score for each review\n# Use vader to evaluated sentiment of reviews\ndef evalSentences(sentences, to_df=True, columns=[]):\n #Instantiate an instance to access SentimentIntensityAnalyzer class\n sid = SentimentIntensityAnalyzer()\n pdlist = []\n # process bar for better tracking\n for sentence in tqdm(sentences):\n ss = sid.polarity_scores(sentence)\n pdlist.append([sentence]+[ss['compound']]) # only get the compound score,\n # there are other scores, called neutral and negative and positive\n reviewDf = pd.DataFrame(pdlist)\n reviewDf.columns = columns\n return reviewDf\n\n\n# + id=\"jGoipK1qZFe7\" colab_type=\"code\" colab={} outputId=\"d440303c-02cb-4591-a2ff-1da3de8e216c\"\nreviews = hotelDF['reviewColumn'].values\nreviewDF = evalSentences(reviews, to_df=True, columns=['Review','VaderScore'])\nreviewDF.head()\n\n# + id=\"AXbzTBkfZFe-\" colab_type=\"code\" colab={}\nnewdf = hotelDF[['hotelName','ratingScore', 'groundTruth']].join(reviewDF)\n\n# + id=\"eIZ0vB06ZFfB\" colab_type=\"code\" colab={} outputId=\"5d49fb67-ed94-4ae4-e999-a0095d3d4473\"\nnewdf.head()\n\n# + id=\"o5q0v9wlZFfE\" colab_type=\"code\" colab={}\nhotelnames = newdf['hotelName'].unique()\n\n# + id=\"kL3yKXq6ZFfG\" colab_type=\"code\" colab={} outputId=\"6384da32-a69d-4898-c9f6-7dedf4dd5627\"\nlen(hotelnames)\n\n\n# + [markdown] id=\"FdJkSFAPg6yC\" colab_type=\"text\"\n# ### Top and bottom 5 hotels ranked by Vader score\n\n# + id=\"LsUTvDZuZFfK\" colab_type=\"code\" colab={}\ndef getHotelRank(df, measure):# the argument can be only df, then the measure is default, which is vader score\n # measure is an argument, but it has default value, you can even not set this argument, but df is the argument you must define\n hotelRating = []\n for hotel in hotelnames:\n itemDf = df.loc[df['hotelName']==hotel]\n hotelRating.append([hotel,itemDf[measure].mean()])\n hotelRatingDf = pd.DataFrame(hotelRating)\n if measure == 'VaderScore':\n hotelRatingDf.columns=['hotelName','avg vader score']\n hotelRatingDf = hotelRatingDf.sort_values('avg vader score',ascending=0)\n else:\n hotelRatingDf.columns=['hotelName','avg GT sentiment']\n hotelRatingDf = hotelRatingDf.sort_values('avg GT sentiment',ascending=0)\n return hotelRatingDf\n\n\n# + id=\"CR2DH1AUZFfN\" colab_type=\"code\" colab={}\nRatingDf_Vader = getHotelRank(newdf, measure = 'VaderScore')\n\n# + id=\"DQNPdVq7ZFfP\" colab_type=\"code\" colab={} outputId=\"222e732b-b1ef-4975-dc2d-528f6383d645\"\nRatingDf_Vader.head()\n\n# + id=\"9MqvXUJmZFfS\" colab_type=\"code\" colab={} outputId=\"00e432d1-fe82-42c9-c4a5-8702159fd9f8\"\nRatingDf_Vader.tail()\n\n# + [markdown] id=\"JHhw9gYQhIph\" colab_type=\"text\"\n# ### Top and bottom 5 hotels ranked by rating score\n\n# + id=\"Xw0-vHJtZFfV\" colab_type=\"code\" colab={}\nRatingDf_GT = getHotelRank(newdf, measure = 'ratingScore')\n\n# + id=\"hHC95djnZFfX\" colab_type=\"code\" colab={} outputId=\"87efa7a7-df2d-4c90-cbfd-baa373a54864\"\nRatingDf_GT.head()\n\n# + id=\"Xi0-1MdbZFfa\" colab_type=\"code\" colab={} outputId=\"141ceeda-e0da-4a80-96d8-9415359c8800\"\nRatingDf_GT.tail()\n\n# + [markdown] id=\"a1byFPUFZFfd\" colab_type=\"text\"\n# We can see that for both methods, they are sort of similar, which I aggree:\n#\n# - for top 5: 57, 58, 63th hotels are in the ranking.\n#\n# - for bottom 5: 45, 50, 51th hotels are in the ranking.\n#\n# The interesting finding is that some bottom ranked hotels using vader sentiment did not show in the bottom ranking using ground truth rating, same case for some top ranked hotels.\n#\n# There is a problem to cause less accuracy for ground truth ranking because all the hotels having 1.0 are not actually ranked.\n\n# + [markdown] id=\"NWuotL6QZFfd\" colab_type=\"text\"\n# ## Frequency analysis\n\n# + [markdown] id=\"CXZXI_VCZFfe\" colab_type=\"text\"\n# Use term frequency of the words for (i) positive reviews and (ii) negative with ground truth sentiment to rank the top-50 most frequent non-stopwords in the review collection.\n\n# + id=\"Qkhjk4hrZFfe\" colab_type=\"code\" colab={}\nitemAnalysisDf = hotelDF[['reviewColumn','groundTruth']]\n\n\n# + id=\"PF-au6AcZFfi\" colab_type=\"code\" colab={}\ndef getTopK(df, k, label_value, label_column='groundTruth', operation=operator.eq, value_column='reviewColumn'):\n stop = set(stopwords.words('english'))\n # Add possible Stop Words for Hotel Reviews\n # you can add the stop words by yourself\n # these words can be frequently appearing in your reviews\n stop.add('hotel')\n stop.add('room')\n stop.add('rooms')\n stop.add('stay')\n stop.add('stayed')\n stop.add('would')\n stop.add('get')\n stop.add('also')\n stop.add('calgary')\n stop.add('one')\n stop.add('said')\n stop.add('could')\n counter = Counter()\n # same meaning: df[label_column] == label_value\n for review in df.loc[operation(df[label_column],label_value)][value_column]:\n counter.update([word.lower() \n for word \n in re.findall(r'\\w+', review) \n if word.lower() not in stop and len(word) > 2])\n topk = counter.most_common(k)\n return topk\n\n\n# + id=\"lz8zxqf1ZFfl\" colab_type=\"code\" colab={}\ntopkGroundPos = getTopK(df = itemAnalysisDf, k=50, label_value='positive')\n\n# + id=\"CtbVWshXZFfn\" colab_type=\"code\" colab={} outputId=\"11f83389-8b5e-4fa6-b183-28a6adbc4dde\"\ntopkGroundPos\n\n# + id=\"00Ummlm6ZFfp\" colab_type=\"code\" colab={}\ntopkGroundNeg = getTopK(df = itemAnalysisDf, k=50, label_value='negative')\n\n# + id=\"129XTcABZFfu\" colab_type=\"code\" colab={} outputId=\"10e1ad1d-b03b-48c1-fdd7-7e3981c0acae\"\ntopkGroundNeg\n\n\n# + [markdown] id=\"wQd3N0V7ZFfx\" colab_type=\"text\"\n# Overall, people and staff, breakfast, location, restaurants are nice. However, shower, parking, price and service are not good in hotels at Calgary.\n\n# + [markdown] id=\"UBoohkkZZFgJ\" colab_type=\"text\"\n# ## Mutual Information\n\n# + [markdown] id=\"LB5oKdwzZFgJ\" colab_type=\"text\"\n# Use mutual information (MI) with ground truth sentiment to rank the top-50 most sentiment-bearing non-stopwords in the review collection.\n\n# + id=\"3IRHcb-PZFgK\" colab_type=\"code\" colab={}\ndef dataFrameTransformation(hotelDf, reviewDF, k=50):\n reviews = reviewDF['Review'].values\n stop = set(stopwords.words('english'))\n stop.add('hotel')\n stop.add('room')\n stop.add('rooms')\n stop.add('stay')\n stop.add('stayed')\n stop.add('would')\n stop.add('get')\n stop.add('also')\n stop.add('calgary')\n stop.add('one')\n stop.add('said')\n stop.add('could')\n # Top-k frequent terms\n counter = Counter()\n for review in reviews:\n counter.update([word.lower() \n for word \n in re.findall(r'\\w+', review) \n if word.lower() not in stop and len(word) > 2])\n # only store the review with more than 2 words\n # it is very important when we want to do stop words filter and stemming\n # there will be the a review with nothing content\n topk = counter.most_common(k) \n \n # Find out if each review has the word from topk list\n freqReview = []\n for i in range(len(reviews)):\n tempCounter = Counter([word.lower() for word in re.findall(r'\\w+',reviews[i])])\n # tempCounter will return each word (after tokenize) frequency in each review list\n topkinReview = [1 if tempCounter[word] > 0 else 0 for (word,wordCount) in topk]\n # I only want to know each review contain the top k words or not\n # tempCounter[word] will return the frequency of this word in this review list\n # but what we want is not frequency, is whether the review has those top words (1 for having 0 for not having)\n freqReview.append(topkinReview)\n \n \n # Prepare freqReviewDf\n freqReviewDf = pd.DataFrame(freqReview)\n dfName = []\n for c in topk:\n dfName.append(c[0]) # all the topk words in a list\n freqReviewDf.columns = dfName # the df column is each word, which is the word in the list\n finalreviewDf = reviewDF.join(freqReviewDf)\n finaldf = hotelDf[['hotelName','ratingScore','groundTruth']].join(finalreviewDf)\n return topk, finaldf\n\n# + id=\"gFCCJleXZFgM\" colab_type=\"code\" colab={}\ntopk, finaldf = dataFrameTransformation(hotelDF, reviewDF, k=50)\n\n# + id=\"k-bxe3EbZFgP\" colab_type=\"code\" colab={} outputId=\"4ff20c3b-640d-4ccc-913d-a75406221369\"\nfinaldf.head()\n\n\n# + id=\"_Oui5Y6HZFgS\" colab_type=\"code\" colab={}\n# get Top K mutual information terms from the dataframe\ndef getMI(topk, df, label_column='groundTruth'):\n miScore = []\n for word in topk: #word is a truple, each line ('term',frequency) in above list\n # word[0] is each word's string, because index is from zero\n # finaldf['groundTruth'] is the target label, finaldf[word[0]] is the word column in the finaldf\n miScore.append([word[0]]+[metrics.mutual_info_score(df[label_column], df[word[0]])])\n miScoredf = pd.DataFrame(miScore).sort_values(1,ascending=0)\n miScoredf.columns = ['Word','MI Score']\n return miScoredf\n\n\n# + id=\"3HoDnwa5ZFgV\" colab_type=\"code\" colab={}\nmiScoredf = getMI(topk, finaldf)\n\n# + id=\"DLlV3sHsZFgX\" colab_type=\"code\" colab={} outputId=\"5e5c34fe-e6fc-4287-ae6e-c027e64e0606\"\nmiScoredf.head()\n\n# + [markdown] id=\"lUPjT82dZFga\" colab_type=\"text\"\n# Those words are showing in the top50 frequency words list.\n\n# + [markdown] id=\"al8NP3QpZFhH\" colab_type=\"text\"\n# ## Data exploratory analysis (EDA)\n\n# + [markdown] id=\"Hhx8lzMSZFhI\" colab_type=\"text\"\n# ### Rating score distribution\n\n# + id=\"fFnO34LEZFhJ\" colab_type=\"code\" colab={} outputId=\"7aff02b3-8115-4707-c1a3-12fe8a94cc1b\"\nplt.hist(hotelDf['ratingScore'].values)\nplt.title('groundTruth')\nplt.xlabel(\"Value\")\nplt.ylabel(\"Frequency\")\nfig = plt.gcf()\n\n# + [markdown] id=\"Md6uEcltlbyN\" colab_type=\"text\"\n# ### Vader score distribution\n\n# + id=\"X5doIJsLZFhK\" colab_type=\"code\" colab={} outputId=\"04398f1d-4058-4475-f16a-b16d936ed3aa\"\nplt.hist(newdf['VaderScore'].values)\nplt.title('Vadar Sentiment Analysis')\nplt.xlabel(\"Value\")\nplt.ylabel(\"Frequency\")\nfig = plt.gcf()\n\n# + [markdown] id=\"owY-geEiZFhM\" colab_type=\"text\"\n# #### Number of comments per hotel\n\n# + id=\"NnCXSVHSZFhM\" colab_type=\"code\" colab={}\nhotel_count = []\nfor hotel in RatingDf_GT['hotelName']:\n count = sum(newdf.hotelName==hotel)\n occurance = count*[hotel] #each user has a list\n hotel_count.extend(occurance)\n\n# + id=\"sRnbtYHXZFhO\" colab_type=\"code\" colab={}\nf = pd.factorize(hotel_count)\n\n# + id=\"s6gJ9SY3ZFhR\" colab_type=\"code\" colab={} outputId=\"48a2cdff-5a97-4d9b-dbe0-a7188b1fcdc9\"\nf[0] # I convert the hotel name to int from most popular (left) to less popular (right)\n\n# + id=\"Wlav6iiuZFhT\" colab_type=\"code\" colab={}\nhotel_ID = []\nfor i in range(70):\n hotel_ID.append(i)\nhotel_ID.append(70)\n\n# + id=\"2cqZWmFPZFhV\" colab_type=\"code\" colab={} outputId=\"857c5b0b-4dd1-452b-a8ad-80919d101074\"\nplt.figure(figsize =(10,5))\nplt.hist(f[0], bins=hotel_ID)\nplt.xlabel('hotel ID')\nplt.ylabel('number of ratings')\nplt.title('histogram showing the number of ratings per hotel from most popular(left) to less popular(right)')\n\n# + [markdown] id=\"pSy3kljOZFhZ\" colab_type=\"text\"\n# In conclusion, more popular hotels tend to have much more reviews.\n\n# + [markdown] id=\"rUIrlmjAZFha\" colab_type=\"text\"\n# ### Rating score box plot\n\n# + id=\"nlkJjIyxZFhb\" colab_type=\"code\" colab={} outputId=\"0605643d-fd09-4125-bc84-fe30e70d072a\"\n#Plot top 5 side-by-side boxplot for top 5 ground truth rated hotel\ntp5gthotel = RatingDf_GT.sort_values('avg GT sentiment',ascending=0).head(5)\ntp5gthotel['hotelName'].values\n\nResidence_Inn_Marriott = hotelDf.loc[hotelDf['hotelName'] == tp5gthotel['hotelName'].values[0]]['ratingScore']\nWingate_by_Wyndham = hotelDf.loc[hotelDf['hotelName'] == tp5gthotel['hotelName'].values[1]]['ratingScore']\nMarriott_Downtown = hotelDf.loc[hotelDf['hotelName'] == tp5gthotel['hotelName'].values[2]]['ratingScore']\nCourtyard_by_Marriott = hotelDf.loc[hotelDf['hotelName'] == tp5gthotel['hotelName'].values[3]]['ratingScore']\nHotel_Elan = hotelDf.loc[hotelDf['hotelName'] == tp5gthotel['hotelName'].values[4]]['ratingScore']\n\ndata = [Residence_Inn_Marriott, Wingate_by_Wyndham, Marriott_Downtown, Courtyard_by_Marriott, Hotel_Elan]\n# multiple box plots on one figure\nplt.figure()\nplt.boxplot(data)\nplt.show()\n\n# + [markdown] id=\"iu2Vjv3fZFhd\" colab_type=\"text\"\n# #### Mean and variance of the ground truth and Vader sentiment scores for the top-5 ranked hotels\n\n# + id=\"chqknK8dZFhd\" colab_type=\"code\" colab={}\nhotels_mean = []\nhotels_variance = []\nfor hotel in [Residence_Inn_Marriott, Wingate_by_Wyndham, Marriott_Downtown, Courtyard_by_Marriott, Hotel_Elan]:\n hotels_mean.append(hotel.mean())\n hotels_variance.append(hotel.var())\n\n# + id=\"ZWRDL0tqZFhj\" colab_type=\"code\" colab={}\nhotels_comparison = pd.DataFrame({'mean': hotels_mean, 'variance': hotels_variance})\nhotels_comparison.rename(index = {0: tp5gthotel['hotelName'].values[0], 1:tp5gthotel['hotelName'].values[1], \n 2:tp5gthotel['hotelName'].values[2], 3:tp5gthotel['hotelName'].values[3],\n 4:tp5gthotel['hotelName'].values[4]}, \n inplace = True)\n\n# + id=\"V_TgdFROZFhl\" colab_type=\"code\" colab={} outputId=\"332a99ed-ea66-487f-c6b0-468ef0451056\"\nhotels_comparison.sort_values('mean', ascending=0)\n\n# + [markdown] id=\"zQI4ZN3FZFho\" colab_type=\"text\"\n# Mean and variance are more infomative. Because they are so similar that box plot can hardly tell the difference.\n\n# + [markdown] id=\"rwdzgDekZFhp\" colab_type=\"text\"\n# ### Rating vs. Vader score\n\n# + id=\"-ZOgI43zZFhr\" colab_type=\"code\" colab={}\nfrom scipy.stats.kde import gaussian_kde\ndef getheatmap(x,y,xlabel,ylabel):\n k = gaussian_kde(np.vstack([x, y]))\n xi, yi = np.mgrid[x.min():x.max():x.size**0.5*1j, y.min():y.max():y.size**0.5*1j]\n zi = k(np.vstack([xi.flatten(), yi.flatten()]))\n cmap = sns.cubehelix_palette(light=1, as_cmap=True)\n fig = plt.figure(figsize=(6,8))\n ax1 = fig.add_subplot(211)\n ax2 = fig.add_subplot(212)\n\n ax1.pcolormesh(xi, yi, np.log10(zi.reshape(xi.shape)), cmap=cmap)\n ax2.contourf(xi, yi, np.log10(zi.reshape(xi.shape)), cmap=cmap)\n\n ax1.set_xlim(x.min(), x.max())\n ax1.set_ylim(y.min(), y.max())\n ax2.set_xlim(x.min(), x.max())\n ax2.set_ylim(y.min(), y.max())\n\n ax1.set_xlabel(xlabel)\n ax1.set_ylabel(ylabel)\n\n ax2.set_xlabel(xlabel)\n ax2.set_ylabel(ylabel)\n\n\n# + id=\"RY82P39YZFhs\" colab_type=\"code\" colab={} outputId=\"4ad795b2-9661-4e4f-f108-47b8e808972b\"\ngetheatmap(x,y,'Vader Score','Rating')\n\n# + [markdown] id=\"7Mij1MUuZFhv\" colab_type=\"text\"\n# We can see the reviews have highest vader always have having rating.\n\n# + [markdown] id=\"uCemPbrkZFhw\" colab_type=\"text\"\n# ### Length of reviews vs. Rating vs. Vader score\n\n# + id=\"esoUO03DZFhw\" colab_type=\"code\" colab={} outputId=\"e4fe17e5-4a9a-40b2-fc2c-41aabc9d73b5\"\ny_ii = [len(s.split()) for s in newdf.Review]\nx_ii = newdf['ratingScore'].values\nplt.plot(x_ii, y_ii, 'o')\nplt.ylabel('length of reviews')\nplt.xlabel('Rating')\n\n# + id=\"HSwYtJb7ZFhy\" colab_type=\"code\" colab={} outputId=\"e6be90a3-1257-4a3b-ddcb-28154d0a8043\"\ngetheatmap(np.array(x_ii),np.array(y_ii),'Rating','length of reviews')\n\n# + [markdown] id=\"dOmuLVE9ZFhz\" colab_type=\"text\"\n# Negative reviews tend to be slightly longer.\n\n# + id=\"wYZLgOx_ZFhz\" colab_type=\"code\" colab={} outputId=\"6fcfb731-f881-4fa1-a9bd-64e605e76c82\"\ny_ii = [len(s.split()) for s in newdf.Review]\nx_ii_new = newdf['VaderScore'].values\nplt.plot(x_ii_new, y_ii,\"o\")\nplt.ylabel('length of reviews')\nplt.xlabel('Vader Rating')\n\n# + id=\"renw5T8mZFh1\" colab_type=\"code\" colab={} outputId=\"7adebce7-b72c-457d-ec66-461c34db2025\"\ngetheatmap(np.array(x_ii_new),np.array(y_ii),'Vader Rating','length of reviews')\n\n# + [markdown] id=\"E2EgVVe_ZFh2\" colab_type=\"text\"\n# Review with larger vader ratings tend to be longer.\n","repo_name":"Jane2019/School-work","sub_path":"Hotel comments analysis/Hotel_customer_comments_analysis.ipynb","file_name":"Hotel_customer_comments_analysis.ipynb","file_ext":"py","file_size_in_byte":19471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"70360093829","text":"# + [markdown] colab_type=\"text\" id=\"view-in-github\"\n# \"Open\n\n# + id=\"5IrO4wZDqRIv\"\nimport pandas as pd\n# pd.DataFrame?\n\n# + id=\"0BlJPKxiqRIx\"\nimport seaborn as sns\n# sns.*?\n\n# + [markdown] id=\"OcKdeIugqRIx\"\n# ## The Boston Housing Dataset \n# We explore the Boston housing dataset, which contains US census data concerning houses in various areas around the city of Boston.\n#\n# Boston Housing Data: This dataset was taken from the StatLib library and is maintained by Carnegie Mellon University. This dataset concerns the housing prices in the housing city of Boston. The dataset provided has 506 instances with 13 features.\n#\n# ---\n\n# + id=\"8ROKobnoqRIy\"\n# Common standard libraries\n\nimport datetime\nimport time\nimport os\n\n# + id=\"NxSoz9DXqRIy\"\n# Common external libraries\n\nimport pandas as pd\nimport numpy as np\nimport sklearn # scikit-learn\nimport requests\nfrom bs4 import BeautifulSoup\n\n# + id=\"lrOp1La9qRIz\"\n# Visualization libraries\n\n# %matplotlib inline\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# + id=\"-CwXe3cPqRIz\"\n# Setting plot appearance\n# See here for more options: https://matplotlib.org/users/customizing.html\n\n# %config InlineBackend.figure_format='retina'\nsns.set() # Revert to matplotlib defaults\nplt.rcParams['figure.figsize'] = (9, 6)\nplt.rcParams['axes.labelpad'] = 10\nsns.set_style(\"darkgrid\")\n\n# + [markdown] id=\"KklURvf1qRIz\"\n# ### Loading the data\n# ---\n\n# + id=\"oDMUKHOeqVcb\"\n# Uncomment following or upload the file\n# # !wget https://raw.githubusercontent.com/sagunkayastha/CAI_Workshop/main/Workshop_1/data/BostonHousing.csv\n\n\n# + id=\"khDeEW8iqRIz\"\n\nboston = pd.read_csv('data/BostonHousing.csv')\n\n# + [markdown] id=\"uo3KLvz-qRI0\"\n# ![Alt text](https://raw.githubusercontent.com/sagunkayastha/CAI_Workshop/main/Workshop_1/images/image-1.png)\n\n# + [markdown] id=\"MLT9ISPmqRI0\"\n# proxy for socio-economic status.\n\n# + id=\"LF4xT7feqRI0\"\nboston\n\n# + [markdown] id=\"KwLH0mmFqRI0\"\n# Question - What do we want to do with this data? What is our Goal\n\n# + id=\"iELdw0ZqqRI0\"\n# What fields are in the dictionary?\nboston.keys()\n\n# + [markdown] id=\"wRJpjpJUqRI1\"\n# We want to predict housing price(medv) (using 12 features)\n\n# + [markdown] id=\"qEz7sp0BqRI1\"\n# ## Basic EDA\n\n# + id=\"w3gZuIgNqRI1\"\n# changing the name of data set.\ndf = boston.copy()\n\n# + id=\"KwO4xkRpqRI1\"\nsummary_stats = df.describe()\nsummary_stats\n\n# + id=\"OfTxamK8qRI1\"\n\n# Set the aesthetic style of the plots\nsns.set(style=\"whitegrid\")\n\n# Draw histograms for each feature\ndf.hist(figsize=(16, 14), bins=30)\nplt.suptitle('Feature Distributions', fontsize=20)\nplt.show()\n\n\n# + id=\"e1f717mhqRI1\"\ndf.dtypes\n\n# + id=\"aPcifHcGqRI1\"\n# Identify and NaNs\ndf.isnull().sum()\n\n# + id=\"VJpph3rOqRI2\"\n# Calculate the correlation matrix\ncorrelation_matrix = df.corr()\n\n# Generate a heatmap\nplt.figure(figsize=(14, 10))\nsns.heatmap(correlation_matrix, annot=True, cmap='coolwarm', fmt=\".2f\")\nplt.title('Correlation Heatmap', fontsize=20)\nplt.show()\n# -\n\n\n\n# # Try some other plots from \n# https://seaborn.pydata.org/examples/index.html\n#\n#\n# https://pandas.pydata.org/docs/user_guide/visualization.html\n\n# +\n# plot line chart for rm vs medv\n# area plot or box plot\n# -\n\n# ## Domain expertise\n\n# + id=\"vKHvIgeDqRI2\"\n# Focus on these columns\n# Domain Expertise\ncols = ['rm', 'age', 'tax', 'lstat', 'medv']\n\n# The pairwise correlations\ndf[cols].corr()\n\n# + id=\"63RBF52bqRI2\"\n# Pairwise correlation heatmap\n\nax = sns.heatmap(\n df[cols].corr(),annot=True,\n cmap=sns.cubehelix_palette(20, light=0.95, dark=0.15),\n)\nax.xaxis.tick_top() # move labels to the top\n\n# plt.savefig(\n# 'boston-housing-corr.png',\n# bbox_inches='tight',\n# dpi=300,\n# )\n\n# + id=\"5QZZtsU2qRI2\"\nsns.pairplot(\n df[cols],\n plot_kws={'alpha': 0.6},\n diag_kws={'bins': 30},\n)\n\n\n# + id=\"KhB3p692qRI2\"\n# Categorize AGE into 3 bins\n\ndef get_age_category(x):\n if x < 50:\n age = 'Relatively New'\n elif 50 <= x < 85:\n age = 'Relatively Old'\n else:\n age = 'Very Old'\n return age\n\ndf['age_category'] = df.age.apply(get_age_category)\n\n# + id=\"CvtVe9wvqRI3\"\n# Check the segmented counts\ndf.groupby('age_category').size()\n\n# + id=\"vW3d_1FyqRI3\"\nsns.boxplot(\n x='medv',\n y='age_category',\n data=df,\n order=['Relatively New', 'Relatively Old', 'Very Old'],\n)\n\n# + id=\"uPWCSfowqRI3\"\nsns.violinplot(\n x='medv',\n y='age_category',\n data=df,\n order=['Relatively New', 'Relatively Old', 'Very Old'],\n)\n\n# + id=\"p6u7PdH3qRI3\"\ncols = ['rm', 'age', 'tax', 'lstat', 'medv', 'age_category']\nsns.pairplot(\n df[cols],\n hue='age_category',\n hue_order=['Relatively New', 'Relatively Old', 'Very Old'],\n plot_kws={'alpha': 0.5},\n)\n\n# + id=\"-ICyggmzqRI3\"\ndf\n\n# + id=\"Li0M3w1IqRI4\"\ny = df['medv'].values\nx = df['lstat'].values.reshape(-1,1)\n\n# + id=\"Xt1pfKMXqRI4\"\nfrom sklearn.preprocessing import PolynomialFeatures\n## converting into polynomial features of degree 3 (ax^3 + bx^2 + cx + d)\npoly = PolynomialFeatures(degree=3)\nx_poly = poly.fit_transform(x)\n\n# + id=\"TDtgFHt8qRI4\"\nfrom sklearn.linear_model import LinearRegression\n# fitting the polynomial regression model\nclf = LinearRegression(fit_intercept=False)\nclf.fit(x_poly, y)\nx_0, x_1, x_2, x_3 = clf.coef_\nmsg = (\n 'model: y = {:.3f} + {:.3f}x + {:.3f}x^2 + {:.3f}x^3'\n .format(x_0, x_1, x_2, x_3)\n)\nprint(msg)\n\n# + id=\"X8yXwisdqRI4\"\ny_pred = clf.predict(x_poly)\nresid_MEDV = y - y_pred\n\nfrom sklearn.metrics import mean_squared_error\nerror = mean_squared_error(y, y_pred)\nprint('mse = {:.2f}'.format(error))\n\n# + id=\"N4IR8IYkqRI4\"\nfig, ax = plt.subplots()\n\n# Plot the samples\nax.scatter(x.flatten(), y, alpha=0.6)\n\n# Plot the polynomial model\nx_ = np.linspace(2, 38, 50).reshape(-1, 1)\nx_poly = poly.fit_transform(x_)\ny_ = clf.predict(x_poly)\nax.plot(x_, y_, color='red', alpha=0.8)\n\nax.set_xlabel('LSTAT')\nax.set_ylabel('MEDV')\n\n\n\n# + [markdown] id=\"cNX7xmz-qRI4\"\n# Sklearn\n#\n\n# + id=\"72ULQb8IqRI4\"\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_squared_error, r2_score\nimport numpy as np\n\n# Extract features and target variable from the dataset\nX = df.drop(['medv','age_category'], axis=1)\n\n\ny = df['medv']\n\n# Split the data into training and testing sets (80% training, 20% testing)\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n\n\n# + id=\"jGsaSxZjqRI5\"\nfrom sklearn.preprocessing import StandardScaler\n\n# Initialize the StandardScaler\nscaler = StandardScaler()\n\n# Fit the scaler on the training data and transform both the training and test data\nX_train_scaled = scaler.fit_transform(X_train)\nX_test_scaled = scaler.transform(X_test)\n\n# Initialize the Linear Regression model\nlr_model_scaled = LinearRegression()\n\n# Fit the model to the scaled training data\nlr_model_scaled.fit(X_train_scaled, y_train)\n\n# Make predictions on the scaled test set\ny_pred_scaled = lr_model_scaled.predict(X_test_scaled)\n\n# Calculate performance metrics for the scaled data\nmse_scaled = mean_squared_error(y_test, y_pred_scaled)\nrmse_scaled = np.sqrt(mse_scaled)\nr2_scaled = r2_score(y_test, y_pred_scaled)\n\nprint(f\"Mean Squared Error (MSE) for LR: {mse_scaled :.2f}\")\nprint(f\"Root Mean Squared Error (RMSE) for LR: {rmse_scaled:.2f}\")\nprint(f\"R-squared (R2) for LR: {r2_scaled:.2f}\")\n\n\n# + id=\"NysYOCAiqRI5\"\n# Retrieve the intercept and coefficients from the model\nintercept = lr_model_scaled.intercept_\ncoefficients = lr_model_scaled.coef_\n\n# Create a dictionary to show feature names along with their corresponding coefficients\nfeature_coef_dict = {feature: coef for feature, coef in zip(X.columns, coefficients)}\n\nintercept, feature_coef_dict\n\n# + [markdown] id=\"s3VdCAN7qRI5\"\n# medv=22.80−1.00×crim+0.70×zn+0.28×indus+0.72×chas−2.02×nox+3.15×rm−0.18×age−3.08×dis+2.25×rad−1.77×tax−2.04×ptratio+1.13×b−3.61×lstat\n\n# + id=\"eESc0OIPqRI6\"\nfrom sklearn.svm import SVR\n# Initialize the Support Vector Regressor model\nsvr_model = SVR()\n\n# Fit the model to the scaled training data\nsvr_model.fit(X_train_scaled, y_train)\n\n# Make predictions on the scaled test set\ny_pred_svr = svr_model.predict(X_test_scaled)\n\n# Calculate performance metrics for the SVR model\nmse_svr = mean_squared_error(y_test, y_pred_svr)\nrmse_svr = np.sqrt(mse_svr)\nr2_svr = r2_score(y_test, y_pred_svr)\n\nprint(f\"Mean Squared Error (MSE) for SVR: {mse_svr:.2f}\")\nprint(f\"Root Mean Squared Error (RMSE) for SVR: {rmse_svr:.2f}\")\nprint(f\"R-squared (R2) for SVR: {r2_svr:.2f}\")\n\n# + id=\"MfFTpT59qRI6\"\n# Extract features and target variable from the dataset\n\n\ncols = ['rm', 'age', 'tax', 'lstat']\nX = df[cols]\ny = df['medv']\n\n# Split the data into training and testing sets (80% training, 20% testing)\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n\n# Initialize the StandardScaler\nscaler = StandardScaler()\n\n# Fit the scaler on the training data and transform both the training and test data\nX_train_scaled = scaler.fit_transform(X_train)\nX_test_scaled = scaler.transform(X_test)\n\n# Initialize the Linear Regression model\nlr_model_scaled = LinearRegression()\n\n# Fit the model to the scaled training data\nlr_model_scaled.fit(X_train_scaled, y_train)\n\n# Make predictions on the scaled test set\ny_pred_scaled = lr_model_scaled.predict(X_test_scaled)\n\n# Calculate performance metrics for the scaled data\nmse_scaled = mean_squared_error(y_test, y_pred_scaled)\nrmse_scaled = np.sqrt(mse_scaled)\nr2_scaled = r2_score(y_test, y_pred_scaled)\n\nprint(f\"Mean Squared Error (MSE) for LR with selected cols: {mse_scaled :.2f}\")\nprint(f\"Root Mean Squared Error (RMSE) for LR with selected cols: {rmse_scaled:.2f}\")\nprint(f\"R-squared (R2) for LR with selected cols: {r2_scaled :.2f}\")\n\n\n# + id=\"cTpjAucZqRI6\"\nfrom sklearn.svm import SVR\n# Initialize the Support Vector Regressor model\nsvr_model = SVR()\n\n# Fit the model to the scaled training data\nsvr_model.fit(X_train_scaled, y_train)\n\n# Make predictions on the scaled test set\ny_pred_svr = svr_model.predict(X_test_scaled)\n\n# Calculate performance metrics for the SVR model\nmse_svr = mean_squared_error(y_test, y_pred_svr)\nrmse_svr = np.sqrt(mse_svr)\nr2_svr = r2_score(y_test, y_pred_svr)\n\n\nprint(f\"Mean Squared Error (MSE) for SVR with selected cols: {mse_svr:.2f}\")\nprint(f\"Root Mean Squared Error (RMSE) for SVR with selected cols: {rmse_svr:.2f}\")\nprint(f\"R-squared (R2) for SVR with selected cols: {r2_svr:.2f}\")\n\n# + id=\"gxYNh6yuqRI6\"\n\n\n# + [markdown] id=\"sgIx3rbrrWSM\"\n# To try other datasets\n#\n# https://github.com/selva86/datasets/tree/master\n\n# + id=\"83E0eOTRrX4y\"\n\n","repo_name":"sagunkayastha/CAI_Workshop","sub_path":"Workshop_1/DS_intro1.ipynb","file_name":"DS_intro1.ipynb","file_ext":"py","file_size_in_byte":10765,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"17001908705","text":"# + [markdown] id=\"QK83VI7B-Uno\"\n# 1. scrivere una funzione chiamata sommaTutti che permetta di sommare un numero arbitrario di valori interi passati come parametri. Scrivere poi un programma che permetta all'utente di inserire un numero variabile di interi e visualizzi la somma.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"GGJI2heM-SuR\" outputId=\"23486bf7-c522-4877-8d90-871935423b05\"\ndef sommaTutti(x):\n return sum(x)\n\nnumeri = [int(s) for s in input(\"inserisci valori: \").split()]\nsommaTutti(numeri)\n\n# + [markdown] id=\"LzcXrp7w_1Cx\"\n# 2. scrivere una lambda function che calcoli la lunghezza della circonferenza di un cerchio dato il raggio. Utilizzarla poi in un programma che chieda all'utente il valore del raggio e visualizzi la lunghezza della circonferenza\n#\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"1aMzo08LAA5t\" outputId=\"19007e38-f4eb-4c44-9b21-685842bf6eec\"\ncirconferenza = lambda x: x * (2*3.1415926535)\ncirconferenza(int(input(\"inserire valore raggio: \")))\n\n\n# + [markdown] id=\"Z3iTAs-IABUV\"\n# 3. scrivere una funzione che calcoli il quadrato di un numero. Scrivere poi una funzione che calcoli la radice quadrata della somma di due numeri. Scrivere poi una lambda function che date le lunghezze di due cateti di un triangolo calcoli l'ipotenusa utilizzando le funzioni definite precedentemente. Utilizzare quest'ultima funzione in un programma che permetta all'utente di inserire le lunghezze dei cateti e di avere in risposta la lunghezza dell'ipotenusa di un triangolo rettangolo\n\n# + id=\"uig_jFn_ADkb\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"62010106-5317-458e-c48e-fb37449643d9\"\ndef quadrato(x):\n return x**2\n\ndef radice(y,z):\n j = y + z \n return pow(j,0.5)\n\ncateto1 =int(input(\"Inserire una lunghezza: \"))\ncateto2 =int(input(\"Inserire una lunghezza: \"))\n\nipotenusa = lambda x,y: radice(quadrato(x),quadrato(y))\nprint(ipotenusa(cateto1,cateto2))\n\n\n# + [markdown] id=\"U0JHe6hqztjh\"\n# 4. Scrivere le funzioni quadrato, cubo e radiceQuadrata che calcolano il quadrato, il cubo e la radice quadrata di un numero intero. Scrivere poi un programma che, utilizzando un ciclo for, richiami le tre funzioni su un valore intero inserito dall'utente e visualizzi i tre risultati.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"oLdQVy_BzwVx\" outputId=\"4ad180e3-3e18-40dc-9e99-aa0b9ecd7dbd\"\ndef quadrato(num):\n return pow(num,2)\n\ndef cubo(num):\n return pow(num,3)\n\ndef radiceQuadrata(num):\n return pow(num,0.5)\n\nnumero = int(input('Inserire valore: '))\n\nprint(quadrato(numero))\nprint(cubo(numero))\nprint(radiceQuadrata(numero))\n\n# + [markdown] id=\"J7sFBmm4z06I\"\n# 5. Utilizzando una lambda function, scrivere un programma che data una lista di numeri interi inserita dall'utente carichi in altre due liste i quadrati e i cubi dei numeri presenti nella lista inserita. Al termine, visualizzare le due liste.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"4mH8DVN-z37g\" outputId=\"73db96b0-d7b5-4909-8504-6b6d3017ce63\"\nlista1 = list(input(\"Inserire la lista1: \").split()) \nlista1 = list([int(n) for n in lista1])\n\nNewList1 = list(map(lambda x: quadrato(x),lista1)) \nNewList2 = list(map(lambda y: cubo(y),lista1)) \n\nprint(NewList1,NewList2)\n\n# + [markdown] id=\"0YVwHENm0CW6\"\n# 6. Utilizzando una lambda function, scrivere un programma che data una lista di numeri interi inserita dall'utente carichi in altre due liste i numeri pari e i numeri dispari presenti nella lista inserita. Al termine, visualizzare le due liste.\n\n# + id=\"g7YQE8Gz0GOI\"\nlista1 = list(input(\"Inserire la lista1: \").split()) \nlista1 = list([int(n) for n in lista1])\n\nlistapari = list(filter(lambda x: x%2 == 0,lista1)) \nlistadispari = list(filter(lambda y: y%2 != 0,lista1))\n\nprint(listapari,listadispari)\n\n# + [markdown] id=\"p3oiaWBH0QdX\"\n# 7. Cercare su internet che cosa si intende per fattoriale di un numero. Scrivere poi una funzione ricorsiva che calcoli il fattoriale di un numero. Utilizzare poi la funzione creata per scrivere un programma che permetta all'utente di inserire un numero intero e che visualizzi il fattoriale di quel numero.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"oHnWBsAt0UaU\" outputId=\"f4b6c14f-cf65-4087-d91e-3bb6b6b93918\"\nprint(\"Il fattoriale è la moltiplicazione di un numero per i suoi antecedenti\")\n\ndef fattoriale(n):\n if n==0:\n return 1\n else:\n return n*fattoriale(n-1)\n\nn = int(input('Inserire il numero: ')) \n\nprint('Il fattoriale è', fattoriale(n))\n\n# + [markdown] id=\"B1Sl74P40W0U\"\n# 8. Svolgere l'esercizio 7, senza ricorsione\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"HB8w0g_L0lCO\" outputId=\"2581fae2-e3ed-49b6-ad2e-f1de4487e60c\"\nn = int(input('Inserire il numero: '))\nf = 1\n\nfor i in range(1,n+1):\n f*=i\n\nprint(f)\n\n\n# + [markdown] id=\"Xd-lUSsN0pC3\"\n# 9. Cercare su internet che cosa sono i numeri di Fibonacci. Scrivere poi una funzione ricorsiva che calcoli l'n-esimo numero della sequenza di Fibonacci. Utilizzare poi la funzione creata per scrivere un programma che permetta all'utente di inserire un numero intero e che visualizzi il numero della sequenza di Fibonacci corrispondente.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"iM44QMHC0sWv\" outputId=\"a3023f8e-c8e4-4575-9dd4-054967939cfe\"\ndef fib(n):\n if n == 0:\n return 0;\n if n == 1:\n return 1;\n else:\n return fib(n-1) + fib(n-2)\n\nnum = int(input(\"Inserisci un numero: \"))\n\nprint(fib(num))\n\n","repo_name":"Goyco2/python-appunti-add-esercizi","sub_path":"Python/esercizio6.ipynb","file_name":"esercizio6.ipynb","file_ext":"py","file_size_in_byte":5415,"program_lang":"python","lang":"it","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"8731372021","text":"# # Latihan 1!\n\n# 1. Buatlah program yang meminta masukan user sebuah bilangan bulat N dimana (N> 0). Program kemudian menampilkan penjumlahan N bilangan genap positifpertama (bilangan genap ≥ 0). Contoh:\n# • Jika user memasukkan N = 3, maka outputnya: 0 + 2 + 4 = 6\n# • Jika user memasukkan N = 5, maka outputnya: 0 + 2 + 4 + 6 + 8 =20\n\nprint(\"_____Menampilkan Penjumlahan N Bilangan Genap Positif Pertama_____\")\nm = 0\nsum = 0\ni = 1\nN=int(input(\"Masukkan nilai N adalah:\"))\nprint(\"Daftar bilangan genap positif pertama yaitu\")\nwhile True:\n sum += m\n print(m)\n m += 2\n i =i+ 1\n if i > N:\n break\nprint(\"Jika memasukkan nilai N:\",N, \"maka penjumlahan dari bilangan genap positif pertama yaitu:\", sum)\n\n# 2. Buatlah sebuah program yang meminta masukan user sebuah bilangan bulat N dimana (N > 0). Kemudian, program menampilkan penjumlahan N bilangan kuadrat pertama. Bilangan kuadrat adalah = 1, 4, 9, 16, 25, 36, ...., N2\n# . Contoh:\n# • Jika user memasukkan N = 2, maka outputnya: 1 + 4 = 5\n# • Jika user memasukkan N = 3, maka outputnya: 1 + 4 + 9 = 14\n\nprint(\"______Menampilkan Penjumlahan Bilangan Kuadrat Pertama_____\")\ni,N,sum=1,0,0\nN=int(input(\"Masukkan nilai N adalah:\"))\nprint(\"Daftar bilangan kuadrat adalah: \")\nwhile True:\n sum += i*i\n print(i*i)\n i += 1\n if i > N:\n break\nprint(\"Jika memasukkan nilai N:\",N, \"maka hasil penjumlahan N bilangan kuadrat pertama yaitu:\", sum)\n\n# 3. Buatlah sebuah program yang meminta masukan user sebuah bilangan bulat N dimana (N > 0). Program kemudian memeriksa setiap digit yang ada di angka\n# tersebut, dan menampilkan berapa jumlah digit yang ganjil dari bilangan N tersebut.\n# • Jika user memasukkan N = 2345, jumlah digit yang ganjil = 2\n# • Jika user memasukkan N = 993312, jumlah digit yang ganjil = 5\n\nprint(\"_____Menampilkan Berapa Jumlah Digit Ganjil dari Bilangan N_____\")\nN = input(\"Masukkan nilai N adalah: \")\nganjil=0\ng=''\nfor i in N:\n if i in'13579':\n ganjil += 1\n g = g+i+''\nprint(\"jumlah digit yang ganjil: \",ganjil)\n\n\n","repo_name":"diajengmaharani/tugas-PPK-1","sub_path":"Latihan Modul pertemuan 5.ipynb","file_name":"Latihan Modul pertemuan 5.ipynb","file_ext":"py","file_size_in_byte":2051,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"3966184892","text":"# # Загрузка\n\ntarget = ['t˚ C трубы после спреера']\n\nls_columns_output = [\n# '№ партии',\n# '№ плавки',\n 'марка стали',\n 'диаметр',\n 'толщина стенки',\n 'Гр. прочн.',\n '1 зона по ВТР закалка',\n '2 зона по ВТР закалка',\n '3 зона по ВТР закалка',\n 'шаг балок закалочная печь, сек',\n 'Скорость прохождения трубы через спрейер, м/с', \n '1 зона ВТР и уставка отпуск', \n '2 зона ВТР и уставка отпуск', \n '3 зона ВТР и уставка отпуск',\n '4 зона ВТР и уставка отпуск',\n '5 зона ВТР и уставка отпуск',\n 'шаг балок отпускная печь, сек',\n 'C',\n 'Mn',\n 'Si',\n 'P',\n 'S',\n 'Cr',\n 'Ni',\n 'Cu',\n 'Al',\n 'V',\n 'Ti',\n 'Nb',\n 'Mo',\n 'N',\n 'B',\n 'C-coef',\n 'Параметр закалка',\n 'Параметр отпуск',\n 'Параметр отпуск новый V',\n 'Величина зерна',\n 'Тип предела текучести (1186)',\n# 'Дата термообработки',\n 'ICD',\n# 'Примечание',\n 'длина трубы'\n ]\n\nimport pandas as pd\nimport numpy as np\nimport import_ipynb\nfrom my_libs.calc_features import *\nimport random\nfrom datetime import datetime\n\npd.options.display.max_columns = 500\npd.options.display.max_rows = 1000\n\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n# %matplotlib inline\n\nfrom sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score, matthews_corrcoef, median_absolute_error\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.svm import LinearSVR\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.ensemble import RandomForestRegressor, BaggingRegressor, ExtraTreesRegressor\nfrom sklearn.model_selection import cross_val_score, StratifiedKFold, cross_val_predict, cross_validate, train_test_split, GridSearchCV\nfrom sklearn import model_selection\nimport matplotlib.pyplot as plt\nimport os\nfrom time import time\nfrom datetime import datetime\nfrom my_libs.save_lib import save_RF_model\nfrom scipy.stats.stats import pearsonr\n\ndf = pd.read_csv('DATA/prepared/prepared_to_saw_gp.csv', low_memory=False)\n\ndf['№ плавки'] = df['№ плавки'].astype(str)\ndf['№ плавки'] = df['№ плавки'].apply(lambda x: x.lower())\ndf['№ партии'] = df['№ партии'].astype(str)\n\ndf_ = df.copy()\ndf_.shape\n\n\ndef bath2spr(df):\n L = 8.4\n df['Скорость прохождения трубы через спрейер, м/с'] = L/df['время выдержки в закалочной ванне, сек.']\n df['t˚ C трубы после спреера'] = df['t˚ C трубы после ванны']\n return df\n\n\n# +\nbath = df_[~df_['время выдержки в закалочной ванне, сек.'].isnull()].copy()\ndf_ = df_[df_['время выдержки в закалочной ванне, сек.'].isnull()].copy()\n\n\nbath = bath2spr(bath)\n\ndf = pd.concat([df_, bath])\ndf.reset_index(inplace=True, drop=True)\n# -\n\ndf.shape\n\n# +\ndf = len_pipe(df)\n\ndf = mean_chem(df)\n\ndf = calc_all_features(df)\n# -\n\ndf = df[df['шаг балок закалочная печь, сек'] < 100]\ndf = df[df['шаг балок закалочная печь, сек'] >= 24]\ndf = df[df['шаг балок отпускная печь, сек'] >= 24]\ndf = df[df['Скорость прохождения трубы через спрейер, м/с'] <= 1]\ndf = df[df['t˚ C трубы после спреера'] > 1]\ndf = df[df['t˚ C трубы после спреера'] <= 250]\ndf = df[df['2 зона ВТР и уставка отпуск'] > 400]\ndf = df[df['4 зона ВТР и уставка отпуск'] > 400]\n\ndf.shape\n\ndf['Дата термообработки'] = df['Дата термообработки'].apply(lambda x: str(x).replace(' 00:00:00', ''))\ndf['Дата термообработки'] = df['Дата термообработки'].apply(lambda x: str(x).replace('-', '.'))\n\ndf[target].hist()\n\ndf[target].describe()\n\ntmp = []\nfor x in df['Дата термообработки']:\n try:\n tmp.append(datetime.strptime(x, \"%d.%m.%Y\"))\n except ValueError:\n tmp.append(datetime.strptime(x, \"%Y.%m.%d\"))\ndf['Дата термообработки'] = tmp\n\ndf[ls_columns_output+list(target)].dropna().shape\n\n# +\nls_train = ls_columns_output.copy()\n# ls_train.remove('Дата термообработки')\nls_train.remove('марка стали')\nls_train.remove('Гр. прочн.')\n\nfor s in ls_to_del:\n ls_train.remove(s)\n\n# +\ndf = df[ls_train+list(target)].dropna()\ndf.drop_duplicates(inplace=True)\n\nX, X_valid, y, y_valid = train_test_split(df[ls_train], df[target], test_size=0.2, shuffle=True)\n# -\n\nX.shape, X_valid.shape\n\nX.columns\n\n\ndef print_and_return_score(x, y, est, verb=1):\n y_pred = est.predict(x)\n# scr = est.score(x, y)\n mae = mean_absolute_error(y, y_pred)\n mse = mean_squared_error(y, y_pred)\n r2 = r2_score(y, y_pred)\n corr = np.corrcoef(y.T, y_pred)\n \n if verb==1: \n print('R^2: ', round(r2, 2))\n print('MAE: ', round(mae, 2))\n print('MSE: ', round(mse, 2))\n print('Correlation1: ', round(corr[0][1], 2))\n return [mae, mse, corr[0][1]]\n\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, shuffle=True)\n\nlen(ls_train)\n\n# +\n# с удаленными незначимыми столбцами\nrfc = RandomForestRegressor(max_features = 13, max_depth = 18, min_samples_leaf = 1, n_estimators=50, criterion='mse')\nrfc.fit(X_train, y_train)\n\nmae, mse, corr1 = print_and_return_score(X_test, y_test, rfc)\n# -\n\nX_valid.shape, X_test.shape\n\npd.merge(X_test, X_valid, how='inner').shape\n\nmae, mse, corr1 = print_and_return_score(X_valid, y_valid, rfc)\n\nval = rfc.feature_importances_\nlab = ls_train\ndict_feat_import = dict(zip(lab, val))\nls_to_del = []\nfor feat, imp in zip(lab, val):\n print(feat, ' ', imp.round(2))\n if imp.round(2) < 0.01:\n ls_to_del.append(feat)\n\nls_to_del\n\n# ## GridSearchCV\n\n# +\nparam_grid = {\n 'max_depth': range(10, 18, 2),\n 'max_features': range(10, 18, 2),\n 'min_samples_leaf': range(1, 4),\n 'n_estimators': range(50, 300, 50)\n}\n\nrf = RandomForestRegressor()\n\ngrid_search = GridSearchCV(estimator = rf, param_grid = param_grid, \n cv = 3, n_jobs = -1, verbose = 2, scoring='neg_mean_absolute_error')\n# -\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, shuffle=True)\n\ngrid_search.fit(X_train, y_train)\n\ngrid_search.best_params_\n\nmae, mse, corr = print_and_return_score(X_test, y_test, grid_search)\n\ny_predict = grid_search.predict(X_test)\n\nplt.subplots(figsize=(10,10))\nplt.scatter(y_test, y_predict, marker='o', c=y_test, edgecolors='black', cmap='viridis')\n# plt.colorbar()\nplt.show()\n\n# ## Cross-validation with KFold\n\nkfold = model_selection.KFold(n_splits=5, shuffle=True)\nscores = []\nfor train, test in kfold.split(X, y):\n x_train, y_train = X.iloc[train], y.iloc[train]\n x_test, y_test = X.iloc[test], y.iloc[test]\n grf = grid_search.best_estimator_\n grf.fit(x_train, y_train)\n\n scores.append(print_and_return_score(X_valid, y_valid, grf))\n\nfor i in range(3):\n tmp = []\n for j in range(3):\n tmp.append(scores[j][i])\n print(round(np.mean(tmp), 2))\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)\ngrf = grid_search.best_estimator_\ngrf.fit(X_train, y_train)\nmae, mse, corr1 = print_and_return_score(X_test, y_test, grf)\n\n''' Проверка на 147 строчках ванны '''\n# bath_valid_ = bath_valid.dropna() \n# X_valid = bath_valid_[ls_train_col]\n# y_valid = bath_valid_[targets]\n\nX_valid.shape\n\n# +\ny_pred = pd.DataFrame(rfc.predict(X_valid), columns=['прогноз t˚ C трубы после спреера'])\ny_pred.reset_index(inplace=True, drop=True)\ny_valid.reset_index(inplace=True, drop=True)\n\nmae, mse, corr1 = print_and_return_score(X_valid, y_valid, rfc)\nscr = r2_score(y_valid, y_pred)\n\nscore_df = pd.concat([pd.DataFrame({'Score':[scr], 'MAE':[mae], 'MSE':[mse], 'Correlation':[corr1],}),\n y_pred,\n y_valid],\n axis=1)\n\nscore_df['MAE'] = np.abs(score_df['t˚ C трубы после спреера'] - score_df['прогноз t˚ C трубы после спреера'])\n\n# +\ny_pred = pd.DataFrame(grf.predict(X_valid), columns=['прогноз t˚ C трубы после спреера'])\ny_pred.reset_index(inplace=True, drop=True)\ny_valid.reset_index(inplace=True, drop=True)\n\nmae, mse, corr1 = print_and_return_score(X_valid, y_valid, grf)\nscr = r2_score(y_valid, y_pred)\n\nscore_df = pd.concat([pd.DataFrame({'Score':[scr], 'MAE':[mae], 'MSE':[mse], 'Correlation':[corr1],\n }),\n y_pred,\n y_valid],\n axis=1)\n\nscore_df['MAE'] = np.abs(score_df['t˚ C трубы после спреера'] - score_df['прогноз t˚ C трубы после спреера'])\n# -\n\nsave_RF_model(rfc, ls_train, 'temp pipe after spr', score_df)\n","repo_name":"ChelpipeBigDataTeam/PNTZ","sub_path":"Model_temp_aft_spr.ipynb","file_name":"Model_temp_aft_spr.ipynb","file_ext":"py","file_size_in_byte":9416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"20"} +{"seq_id":"14949161512","text":"import numpy as np\nimport healpy as hp\nimport gzip\nimport sys\n\n\n# +\nnside = 256\nlmax = 3*nside-1\nell, TT, EE, BB, TE = np.loadtxt('totcls_lensed_r0p1.txt', unpack=True)\n\nprefactor = 2*np.pi/(ell * (ell + 1))\nprefactor[0] = 0 \ncl = np.array([TT, EE, BB, TE])\ncl *= prefactor\n\n# +\nmask = np.zeros(hp.nside2npix(nside))\nth, ph = hp.pix2ang(nside, np.arange(hp.nside2npix(nside)))\n\nph[np.where(ph > np.pi)[0]] -= 2 * np.pi\n\nmask[np.where(np.sqrt(ph**2+((th-np.pi/2)/1)**2)\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nrecords = pd.read_csv('../stats/records.csv')\noff_stats = pd.read_csv('../stats/offensive_stats.csv')\ndef_stats = pd.read_csv('../stats/defensive_stats.csv')\n\npythag_table = records.copy()\n\noff_stats.head()\n\ndef_stats.head()\n\n# +\npythag_table.sort_values('team_id', inplace=True)\noff_stats.sort_values('team_id', inplace=True)\ndef_stats.sort_values('team_id', inplace=True)\n\npythag_table['runs_scored'] = off_stats['runs']\npythag_table['runs_allowed'] = def_stats['runs']\n# -\n\npythag_table['pythag_win_estimate'] = ((pythag_table['runs_scored']**2) \n / ((pythag_table['runs_scored']**2) + (pythag_table['runs_allowed']**2)))\n\npythag_table.head()\n\npythag_table[['win_%', 'pythag_win_estimate']].corr()\n\nmodel_data = pythag_table[['runs_scored', 'runs_allowed', 'win_%']]\n\nX = model_data[['runs_scored', 'runs_allowed']].to_numpy()\ny = model_data['win_%'].to_numpy()\n\nX[0]\n\n# +\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.2)\n# -\n\nruns_scored = [i[0] for i in X_train]\nruns_allowed = [i[1] for i in X_train]\n\n\n# +\ndef PythagPredict(runs_scored, runs_allowed, alpha):\n ''' This function runs a single instance of the simulation with a given alpha value for\n Pythagorean Theorem of Baseball: runs_scored^(alpha) / (runs_scored^(alpha) + runs_allowed^(alpha)).\n '''\n rsp = np.power(runs_scored, alpha)\n rap = np.power(runs_allowed, alpha)\n rsp_plus_rap = np.add(rsp, rap)\n\n np.divide(rsp, rsp_plus_rap)\n \n return np.divide(rsp, rsp_plus_rap)\n\ndef mean_absolute_error(predictions, observed):\n '''calculates the mean absolute error of predictions and observed values'''\n error = np.absolute(predictions - observed) / len(predictions)\n \n return np.sum(error)\n\n\ndef PythagOptimization(runs_scored, runs_allowed, win_percentage, alphas=np.linspace(0,4,401)):\n ''' This function runs a model over all alphas to determine the best fitting alpha value for \n Pythagorean Theorem of Baseball. The loss function that we are minimizing in this function is\n Mean Absolute Error(MAE).'''\n \n error=float('inf')\n for alpha in alphas:\n local_prediction = PythagPredict(runs_scored, runs_allowed, alpha)\n local_error = mean_absolute_error(local_prediction, win_percentage)\n if local_error < error:\n error = local_error\n optimal_alpha = alpha\n optimal_prediction = local_prediction\n \n return optimal_alpha, optimal_prediction, error\n\n\n# -\n\nalpha, predictions, error = PythagOptimization(runs_scored, runs_allowed, y_train)\n\nalpha\n\npredictions\n\nerror\n\nruns_scored_test = [i[0] for i in X_test]\nruns_allowed_test = [i[1] for i in X_test]\n\ntest = PythagPredict(runs_scored_test, runs_allowed_test, alpha)\noriginal = PythagPredict(runs_scored_test, runs_allowed_test, 2)\n\nmae_test = mean_absolute_error(test, y_test)\nmae_original = mean_absolute_error(original, y_test)\n\nprint(f'Error (alpha = {alpha}): {mae_test}')\nprint(f'Error (alpha = 2): {mae_original}')\n\n# #### To reach a complete error, the model needs to be run numerous times as to determine the accuracy of the model\n\ntrials = 100\nsim = np.empty(trials)\nfor trial in range(trials):\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.2)\n \n runs_scored = [i[0] for i in X_train]\n runs_allowed = [i[1] for i in X_train]\n \n sim[trial] = (PythagOptimization(runs_scored, runs_allowed, y_train)[0])\n\nmean = sim.mean()\nsd = sim.std()\n\nmean\n\nsd\n\nz_score99 = 2.58\n\nmargin = z_score99 * sd/(trials**0.5)\n\nconfidence_interval = (mean - margin, mean + margin)\n\nconfidence_interval\n\nprint(f'True alpha: {mean} ' + u'\\u00B1' + f' {margin}' )\n\nalpha = mean\n\npythag_table['model_pythag_win_%'] = (pythag_table['runs_scored']**alpha) / ((pythag_table['runs_scored']**alpha) + (pythag_table['runs_allowed']**alpha))\n\npythag_table.head()\n\npythag_corr = pythag_table[['win_%', 'pythag_win_estimate', 'model_pythag_win_%']].corr()\n\npythag_corr['win_%']\n\npythag_table.sort_values('win_%', inplace=True)\n\npythag_table.head()\n\n# %matplotlib qt\n\n# +\nindex = np.arange(1, len(pythag_table)+1)\n\nplt.plot(index, pythag_table['pythag_win_estimate'], label='Pythag Estimate \\u03B1 = 2', alpha=.5)\nplt.plot(index, pythag_table['model_pythag_win_%'], label=f'Pythag Estimate \\u03B1 = {round(alpha, 2)}', alpha=.5)\nplt.plot(index, pythag_table['win_%'], color='#000000', label='True Win Percentage')\n\nplt.xticks([])\nplt.ylabel('Win Percentage')\nplt.title('Plot of Pythagorean Win Rates')\nplt.grid(True)\nplt.legend()\nplt.tight_layout()\nplt.show()\n\n# +\nline = [.3,.7]\nplt.scatter(pythag_table['win_%'], pythag_table['model_pythag_win_%'], label='Original Estimate \\u03B1 = 2', color='blue', s=10, alpha=.5)\nplt.scatter(pythag_table['win_%'], pythag_table['pythag_win_estimate'], label=f'Model Estimate \\u03B1 = {round(alpha, 2)}', color='red', s=10, alpha=.5)\nplt.plot(line, line, color='#000000', label='Accuracy Line')\n\nplt.legend()\nplt.title('Pythag Estimate to Win Rate Comparison')\nplt.ylabel(f'Pythag Estimate')\nplt.xlabel('True Win Rate')\nplt.tight_layout()\nplt.show()\n# -\n\npythag_table.to_csv('../stats/pythag_table.csv', index=False)\n\n\n","repo_name":"rs314314/Baseball","sub_path":"code/PythagoreanTheoremOfBaseball.ipynb","file_name":"PythagoreanTheoremOfBaseball.ipynb","file_ext":"py","file_size_in_byte":5369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"20"} +{"seq_id":"15062195391","text":"# # Programmierübung: Der Page Rank - Algorithmus\n#\n# ## Modul: Lineare Algebra und Geometrie (lag)\n#\n# ## FS 2020\n#\n# ## Prof. Dr. Andreas Vogt\n#\n# Das folgende Notebook ist von Ihnen auszufüllen. Der Abgabetermin ist am 3. April 2020. Es wird sowohl die Korrektheit der Programme als auch die Darstellung bewertet. Wie genau die Note in die Erfahrungsnote bzw. die Endnote des Moduls einfliesst, ist zur Zeit noch nicht ganz klar.\n\n# Wir laden zuerst die für diese Übung benötigten Module. **Hinweis:** Wir benutzen das Modul `networkx` für die graphische Darstellung von Graphen. Gegebenenfalls müssen Sie dies noch nachinstallieren.\n\n# + pycharm={\"is_executing\": false}\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport networkx as nx\nimport scipy\n# -\n\n# ## Adjazenz- und Inzidenzmatrix\n\n# Recherchieren Sie, was die Adjazenzmatrix bzw. die Inzidenzmatrix eines Graphen $G$ ist. Stellen Sie beide Konzepte in sauberem LaTeX dar. Illustrieren Sie beide Konzepte an Hand eines Beispiels.\n\n# + [markdown] pycharm={\"is_executing\": false, \"name\": \"#%% md\\n\"}\n# \n\n# + [markdown] pycharm={\"name\": \"#%% md\\n\"}\n# \n\n# + [markdown] pycharm={\"name\": \"#%% md\\n\"}\n# \n\n# + [markdown] pycharm={\"name\": \"#%% md\\n\"}\n# Den Latex-Code, welcher die Basis für die oben angezeigten Bilder bildet, finden sie im File [\"main.tex\"](main.tex) in der Projektstruktur.\n# -\n\n# Der folgende Graph sei nun gegeben:\n\n# \n\n# Definieren Sie zuerst seine Inzidenzmatrix $E$ als Numpy-array.\n\n# + pycharm={\"is_executing\": false}\nnodes = [0, 1, 2, 3, 4, 5, 6, 7]\nedges = [[0, 1], [0, 6], [0, 7], \n [1, 2], [1, 7], \n [2, 1], [2, 7], \n [3, 5], [3, 7], \n [4, 5], \n [5, 6], \n [6, 5], \n [7, 6]]\n\nG = nx.DiGraph()\nG.add_nodes_from(nodes)\nG.add_edges_from(edges)\n\nincidence_matrix = -nx.incidence_matrix(G, oriented=True)\n\nE = np.array(incidence_matrix.toarray())\n\n\n# -\n\n# Schreiben Sie eine Funktion, die als Eingabe die Inzidenzmatrix eines Graphen erhält und die entsprechende Adjazenzmatrix ausgibt.\n\n# + pycharm={\"is_executing\": false}\ndef turn_im_into_am( E ):\n edge_starting_points = np.where(E.T > 0)\n edge_end_points = np.where(E.T < 0)\n\n g = nx.DiGraph()\n\n for i in range(len(E)):\n g.add_node(i)\n\n for i in range(len(edge_starting_points[1])):\n foo = edge_starting_points[1][i]\n bar = edge_end_points[1][i]\n g.add_edge(foo, bar)\n\n am = nx.adjacency_matrix(g)\n\n return np.array(am.toarray())\n\n\n# -\n\n# Zur Visualisierung Ihrer Graphen stellen wir Ihnen eine Funktion zur Verfügung. \n\n# + pycharm={\"is_executing\": false}\ndef plot_graph( A, knoten_gewichte=None ):\n \"\"\"\n Funktion zur graphischen Darstellung eines Graphen. \n Benutzt das 'spring layout', eventuell muss die Funktion mehrere Male ausgeführt werden, bis eine schöne Darstellung \n des Graphen vorliegt.\n \n Arguments: \n A -- Adjazenzmatrix (shape (n_knoten,n_knoten))\n knoten_gewichte -- Liste mit Gewichte für jeden Knoten im Graphen (bei None erhalten alle Knoten die gleichen Gewichte)\n \"\"\"\n \n if knoten_gewichte is None:\n knoten_gewichte = np.array( [1] * A.shape[0] )\n \n assert( len( knoten_gewichte) == A.shape[0] )\n \n knoten_gewichte = knoten_gewichte / np.mean( knoten_gewichte )\n \n plt.figure(figsize=(8,8))\n G = nx.DiGraph( A )\n pos = nx.layout.spring_layout(G)\n options = {\n 'node_color': '#dd0000',\n 'node_size': knoten_gewichte*2500,\n 'width': 3,\n 'arrowstyle': '-|>',\n 'arrowsize': 12,\n }\n \n nx.draw_networkx(G, pos, arrows=True, **options )\n plt.axis(\"off\")\n plt.show()\n\n\n# -\n\n# Lassen Sie von ihrer Funktion die Ajazenzmatrix $A$ zu der oben eingegebenen Inzidenzmatrix $E$ berechnen und visualisieren Sie den zugehörigen Graphen mit der obigen Funktion.\n\n# + pycharm={\"is_executing\": false}\nA = turn_im_into_am(E)\nplot_graph(A)\n\n\n# -\n\n# Schreiben SIe eine Funktion, die als Eingabe die Adjazenzmatrix eines Graphen erhält und die entsprechende Inzidenzmatrix ausgibt.\n\n# + pycharm={\"is_executing\": false}\ndef turn_am_into_im(A):\n g = nx.DiGraph(A)\n\n im = -nx.incidence_matrix(g, oriented=True)\n\n return np.array(im.toarray())\n\n\n\n# -\n\n# ## Der PageRank-Algorithmus\n\n# Schreiben Sie eine Funktion, die als Eingabe die Inzidenzmatrix eines Graphens erhält und die zugehörige Link-Matrix $P$ ausgibt.\n\n# + pycharm={\"is_executing\": false}\ndef create_lm_from_im(im):\n am = turn_im_into_am(im)\n am = am.astype(float)\n\n foo = np.sum(am, axis=1, dtype=float)\n\n for i, s in enumerate(foo):\n foo[i] = 1/s\n\n for iterable, value in enumerate(am):\n am[iterable] = value*foo[iterable]\n\n return am.T\n\n\n# -\n\n# Schreiben Sie eine Funktion, die als Eingabe die Inzidenzmatrix eines Graphens erhält und als Ausgabe den Vektor $v$ mit $|v|=1$ ausgibt, der die Bedeutung der Webseiten erhält. Verwenden Sie $\\alpha=0.85$.\n\n# + pycharm={\"is_executing\": false}\n# Studentenversion\ndef create_meaning_vector_from_im(im, alpha=0.85):\n\n # Create Link Matrix and multiply by alpha to get P\n P = create_lm_from_im(im)\n P = P * alpha\n\n # Create Matrix of Random Surf-behaviour and multiply by 1-alpha to get S\n S = np.ones((len(P), len(P)), dtype=float)/len(P)\n S = S * (1-alpha)\n\n # Combine P and S to get the Google Matrix\n G = P + S #G\n\n # Create Identity Matrix En\n En = np.eye(len(G), dtype=float)\n\n # Subtract Identity Matrix (En) from Google Matrix (G) to get our A for the formula Ax = B\n A = G - En #G-En\n\n # Create B for the Formula Ax = B. A Vector of Ones is chosen, since a vector of 0s would yield an unusable result.\n B = np.ones((len(A)), dtype=float)\n\n # Solve the Formula for x.\n solution = np.linalg.solve(A, B)\n\n # Normalize the Solution\n solution_normalizer = np.linalg.norm(solution)\n normalized_solution = []\n for result in solution:\n normalized_result = result / solution_normalizer\n if normalized_result < 0:\n normalized_result = 0\n normalized_solution.append(normalized_result)\n\n return normalized_solution\n\n# Professionellere Lösung\ndef create_pagerank_with_nx(im, alpha=0.85):\n g = nx.DiGraph(turn_im_into_am(im))\n\n return list(nx.pagerank(g, alpha=alpha).values())\n\n\n# -\n\n# Schreiben Sie eine Funktion, die als Eingabe die Inzidenzmatrix eines Graphens erhält und den zugehörigen Graphen plottet, wobei die Grösse der Knoten proportional zu ihrer Bedeutung sein soll.\n\n# + pycharm={\"is_executing\": false}\ndef plot_graph_from_Im(IM, use_student_made_algo=False):\n AM = turn_im_into_am(IM)\n\n if(use_student_made_algo):\n weights = create_meaning_vector_from_im(IM)\n else:\n weights = create_pagerank_with_nx(IM)\n\n plot_graph(AM, knoten_gewichte=weights)\n\n\n# + pycharm={\"is_executing\": false, \"name\": \"#%%\\n\"}\nplot_graph_from_Im(E, use_student_made_algo=True)\n\n\n# + pycharm={\"is_executing\": false, \"name\": \"#%%\\n\"}\nplot_graph_from_Im(E, use_student_made_algo=False)\n\n# + pycharm={\"is_executing\": false}\n\n","repo_name":"rberberat/lag_homework_1","sub_path":"lag_programmieraufgabe_ROBIN_BERBERAT.ipynb","file_name":"lag_programmieraufgabe_ROBIN_BERBERAT.ipynb","file_ext":"py","file_size_in_byte":7176,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"20"} +{"seq_id":"27560554014","text":"\n\n\n\n\n\n# +\nimport bisect\n\nclass Solution:\n def maxEnvelopes(self, envelopes):\n envelopes = sorted(envelopes, key = lambda x: (x[0], -x[1]))\n dp = []\n for w,h in envelopes:\n idx = bisect.bisect_left(dp, h)\n if idx == len(dp):\n dp.append(h)\n else:\n dp[idx] = h\n return len(dp)\n\n\n# -\n\nclass Solution:\n def maxEnvelopes(self, envelopes):\n envelopes.sort()\n print(envelopes)\n n = len(envelopes)\n dp = [1] * n\n for i in range(1, n):\n for j in range(i):\n if envelopes[j][0] != envelopes[i][0] and envelopes[j][1] < envelopes[i][1]:\n dp[i] = max(dp[i], dp[j] + 1)\n return max(dp)\n\n\nsolution = Solution()\nsolution.maxEnvelopes([[5,4],[6,4],[6,7],[2,3]])\n\n\n","repo_name":"YuHe0108/LeetCode","sub_path":"Dynamic Programming/1206/354. Russian Doll Envelopes.ipynb","file_name":"354. Russian Doll Envelopes.ipynb","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"20"} +{"seq_id":"2900834431","text":"# # Imports\n#\n\nimport requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd\n\n# # Input Section\n\n# +\n# here we will take the input of the actors name\nactor_name = input('\\t Enter the name of the actor')\n\n# changing the name into desired form\nactor_name= actor_name.replace(' ', '_')\n\nactor_name\n# -\n\nurl = f'https://en.wikipedia.org/wiki/{actor_name}_filmography'\n\n\n# # fetching the data\n#\n\npage = requests.get(url)\n\nsoup = BeautifulSoup(page.content, 'html.parser')\n\nsoup.prettify()\n\ntable = soup.find('table', class_='wikitable sortable plainrowheaders')\ntable.find_all('tr')\n\n# +\n# movies list \nmovies_list =[]\n\nfor rows in table.find_all('tr')[2:]:\n row =rows.find('td').text.strip('\\n')\n movies_list.append(row)\n# -\n\n# now descending order\nmovies_list = movies_list[::-1]\n# final result\nprint(f'The Descending order of movies list of {actor_name} is:')\nfor movie in movies_list:\n print(movie)\n\n\n\n\n","repo_name":"thapakazi624/Web_Scapping","sub_path":"Web Scrapping.ipynb","file_name":"Web Scrapping.ipynb","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"20"} +{"seq_id":"753342959","text":"# ### 1. Напишите код, моделирующий выпадение поля в рулетке (с учетом поля зеро).\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\nimport numpy as np\n\nwhile input() != 'q':\n print(np.random.randint(37), end='')\n\n# ### 2. \n# **1)** Напишите код, проверяющий любую из теорем сложения или умножения вероятности на примере рулетки или подбрасывания монетки.\n\n# Проверим, что для противоположных событий p(A) + p(B) = 1. \n# Подбросим монетку n раз (пусть 1 - орел и 0 - решка) и посчитаем сколько раз выпал орел (k раз). После этого посчитаем вероятности выпадения орла и решки (p1 и p2 соответственно) как количество выпадений орла (k) и решки (n-k) на этой дистанции к общему количетву испытаний (n). Согласно теореме сумма этих вероятностей должна равняться 1.\n\n# **Прим.:** метод count для подсчета количества вхождений элемента в массив не работает с типом numpy.ndarray, возвращаемым np.random.randint. Поэтому преобразуем numpy.ndarray в list\n\nn = 1000\nk = list(np.random.randint(0, 2, n)).count(1)\np1 = k / n\np2 = (n - k) / n\nprint(p1, p2, p1 + p2)\n\n# **2)** Сгенерируйте десять выборок случайных чисел х0, …, х9.\n# и постройте гистограмму распределения случайной суммы х0+х1+ …+ х9.\n\nimport matplotlib.pyplot as plt\n\n# **Прим.:** sorted() для наглядности (на результат не влияет)\n\nx = sorted([round(np.random.rand(10).sum(), 2) for i in range(10)])\nx\n\nbins = 5\nplt.hist(sorted(x), bins)\nplt.xlabel('sum')\nplt.ylabel('count')\n\n# ### 3. \n# **1)** Дополните код Монте-Карло последовательности независимых испытаний расчетом соответствующих вероятностей (через биномиальное распределение) и сравните результаты.\n\n# Сколько получается по коду из видео:\n\nk, n = 0, 10000\na = np.random.randint(0, 2, n)\nb = np.random.randint(0, 2, n)\nc = np.random.randint(0, 2, n)\nd = np.random.randint(0, 2, n)\nx = a + b + c + d\nfor i in range(n):\n if x[i] == 2:\n k = k + 1\nprint(k / n)\n\n\n# Сколько должно быть (раcчет по формулам):\n\ndef prob(k, n):\n C = np.math.factorial(n) / (np.math.factorial(k) * np.math.factorial(n - k))\n return C / pow(2, n)\n\n\nprob(2, 4)\n\n# **2)** Повторите расчеты биномиальных коэффициентов и вероятностей k успехов в последовательности из n независимых испытаний, взяв другие значения n и k.\n\nprob(3, 4)\n\nprob(3, 10)\n\n# ### 4. Из урока по комбинаторике повторите расчеты, сгенерировав возможные варианты перестановок для других значений n и k\n\nimport itertools\n\nprint(len(list(itertools.permutations('012', 3))))\nprint('---')\nfor i in itertools.permutations('012', 3):\n print(''.join(i))\n\nprint(len(list(itertools.permutations('01235', 4))))\nprint('---')\nfor i in itertools.permutations('01235', 4):\n print(''.join(i))\n\n# ### 5. Дополните код расчетом коэффициента корреляции x и y по формуле\n\nn = 100\nr = 0.7\nx = np.random.rand(n)\ny = r * x + (1 - r) * np.random.rand(n)\nplt.plot(x, y, 'o')\nplt.xlabel('x')\nplt.ylabel('y')\nplt.grid(True)\na = (np.sum(x) * np.sum(y) - n * np.sum(x * y)) / (np.sum(x) * np.sum(x) - n * np.sum(x * x))\nb = (np.sum(y) - a * np.sum(x)) / n\nA = np.vstack([x, np.ones(len(x))]).T\na1, b1 = np.linalg.lstsq(A, y)[0]\nprint(a, b)\nprint(a1, b1)\n\nc = np.sum((x - np.mean(x)) * (y - np.mean(y))) /\\\n np.sqrt(np.sum(np.square(x - np.mean(x))) * np.sum(np.square(y - np.mean(y))))\nc1 = np.corrcoef(x, y)\nprint(c, c1[0][1])\n","repo_name":"nikola4725/Geekbrains_Introduction_to_Higher_Mathematics","sub_path":"lesson_05/lesson_05.ipynb","file_name":"lesson_05.ipynb","file_ext":"py","file_size_in_byte":4472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"20"} +{"seq_id":"73094791729","text":"# + colab={} colab_type=\"code\" id=\"ry52yimkPRXe\"\nimport torch\nimport torch.nn as nn\nimport numpy as np\nfrom torch.nn import Conv2d, Linear, ConvTranspose2d\nfrom complextensor import ComplexTensor\n\n\n# -\n\nclass complexLayer(nn.Module):\n '''\n Turns a pytorch layer into a complex layer. works for Linear, Conv and ConvTranspose\n '''\n def __init__(self, Layer,kwargs):\n super().__init__()\n self.device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n self.bias = kwargs.get('bias',False)\n # turn the bias off so as to only do matrix multiplication \n # if you leave the bias on, then the complex arithmetic does not \n # work out correctly\n kwargs['bias'] = False\n self.f_ma = Layer(**kwargs)\n self.f_ph = Layer(**kwargs)\n self.b = None\n out_dim_keyNames = set(['out_channels', 'out_features'])\n self.outType = list(out_dim_keyNames.intersection(kwargs.keys()))[0]\n self.out_dim = kwargs[self.outType]\n if self.bias:\n b_r = np.random.randn(self.out_dim,1).astype('float32')\n b_i = np.random.randn(self.out_dim,1).astype('float32')\n z = b_r + 1j*b_i\n self.b = ComplexTensor(z) \n\n def forward(self, x): \n magnitude = self.f_ma(x.magn)\n phas = self.f_ph(x.phase)\n if self.bias:\n if self.outType == 'out_channels':\n # expand the dims\n b_m = self.b.real.reshape(1,len(self.b),1,1)\n b_p = self.b.imag.reshape(1,len(self.b),1,1)\n else:\n b_m = self.b.real.reshape(len(self.b),)\n b_p = self.b.imag.reshape(len(self.b),)\n real = real + b_m\n imaginary = imaginary + b_p\n result = torch.cat([magnitude, phas], dim=-2)\n result.__class__ = ComplexTensor\n return result\n \n def __call__(self,x):\n result = self.forward(x)\n return result\n\n\nbz = 16\nbias = True # vary this for testing purposes\nx = torch.randn((bz,2,3,100,100))\nx_np = x.detach().numpy()\nmagn = np.squeeze(x_np[:,0,:,:])\nphase = np.squeeze(x_np[:,1,:,:])\nz = np.concatenate([magn, phase], axis=-2)\n\nComplexTensor(z)\n\n\n","repo_name":"Xiaoqi-Long-Caltech/complex-neural-nets","sub_path":"complexlayer.ipynb","file_name":"complexlayer.ipynb","file_ext":"py","file_size_in_byte":2216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"20"} +{"seq_id":"72840471729","text":"import xarray as xr\nimport pandas as pd\nimport os\nimport matplotlib.pyplot as plt\n\nUKGrid=xr.open_dataset(\"UKGrid/maxtmax-uk.nc\")\n\nthis_year_date=pd.DatetimeIndex(data=['2022-01-01T00:00:00.000000000'])\nthis_year=xr.Dataset(\n {\n \"tasmax\": (38.1),\n },\n coords={\"time\": this_year_date},\n)\n\nwarmest_day_of_year=xr.combine_by_coords([UKGrid,this_year])\nwarmest_day_of_year\n\nplt=warmest_day_of_year.tasmax.plot(ylim=[25,45],xlim=pd.DatetimeIndex(['1960-01-01','2080-01-01']),marker='o', color='black')\n\nUKCP18=xr.open_mfdataset(paths=\"UKCP18/*.nc\")\nUKCP18.maxtmax[:,0].plot(ylim=[25,50])\nUKCP18.time\n\n# +\nobs_year=pd.DatetimeIndex(warmest_day_of_year.time).year\nfig=plt.plot(obs_year,warmest_day_of_year.tasmax,marker='o', color='black')\n\n#UKCP18.maxtmax[:,0].plot(ylim=[25,50])\n# -\n\n\n","repo_name":"chrisbrierley/UK_hottest_days","sub_path":"Plotting_script.ipynb","file_name":"Plotting_script.ipynb","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"20"} +{"seq_id":"2905956313","text":"# + id=\"kuTMv_0elgJx\"\n# !pip install pytorch_lightning\n# !pip install nlp\n# !pip install transformers\n# !pip install flax\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"hGhn0Zolk65R\" outputId=\"eb723628-ca56-4766-a351-dcbc4328b762\"\nimport argparse\nimport glob\nimport os\nimport json\nimport time\nimport logging\nimport random\nimport re\nfrom itertools import chain\nfrom string import punctuation\nimport textwrap\nfrom tqdm.auto import tqdm\nimport nltk\nnltk.download('punkt')\nfrom nltk.tokenize import sent_tokenize\n\nimport pandas as pd\nimport numpy as np\nimport torch\nimport pytorch_lightning as pl\nfrom torch.utils.data import Dataset, DataLoader\nfrom pytorch_lightning.loggers import WandbLogger\nfrom nlp import load_metric\n\nfrom transformers import (\n AdamW,\n T5ForConditionalGeneration,\n AutoTokenizer,\n get_linear_schedule_with_warmup\n)\n\n# + id=\"uBXQjOU_rfI2\"\ntrain_path = 'train.csv'\ntest_path = 'validation.csv'\n\n# -\n\ntrain_df = pd.read_csv(train_path)\ntest_df = pd.read_csv(test_path)\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"JUUylwwNAOVo\" outputId=\"726a0eb5-b26a-4d2f-cd70-3d9817dec523\"\n\ndef concatenate(row):\n return 'متن: ' + row['context'] + '، پرسش: ' + row['question']\n\ndef format_df(k):\n # Apply the function to create a new 'input' column\n k['input'] = k.apply(concatenate, axis=1)\n\n # Extract the first answer from the 'answers' column\n k['output'] = k['answers']\n\n # Create a new DataFrame with 'input' and 'output' columns\n df = pd.DataFrame({'input': k['input'], 'output': k['output']})\n return df\n\n# -\n\n\n\ntrain_data = format_df(train_df)\ntest_data = format_df(test_df)\n\ntest_data[input]\n\n# + id=\"4DUFeP91IfwK\"\ndf = df.iloc[50000:,:]\n\n\n# + id=\"G67Cqwi_sV19\"\ndef set_seed(seed):\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n if torch.cuda.is_available():\n torch.cuda.manual_seed_all(seed)\nset_seed(42)\n\n\n# + id=\"rIfgljPgQjAA\"\nclass bigbang(Dataset):\n def __init__(self, df, tokenizer, input_length, output_length): \n self.dataset = df\n self.input_length = input_length\n self.tokenizer = tokenizer\n self.output_length = output_length\n def __len__(self):\n return self.dataset.shape[0]\n def clean_text(self, text):\n text = text.replace('\\n','')\n return text\n def convert_to_features(self, example_batch):\n input_ = self.clean_text(example_batch['input'])\n target_ = self.clean_text(example_batch['output'])\n source = self.tokenizer.batch_encode_plus([input_], max_length=self.input_length, \n padding='max_length', truncation=True, return_tensors=\"pt\")\n targets = self.tokenizer.batch_encode_plus([target_], max_length=self.output_length, \n padding='max_length', truncation=True, return_tensors=\"pt\")\n return source, targets\n def __getitem__(self, index):\n source, targets = self.convert_to_features(self.dataset.iloc[index])\n source_ids = source[\"input_ids\"].squeeze()\n target_ids = targets[\"input_ids\"].squeeze()\n src_mask = source[\"attention_mask\"].squeeze()\n target_mask = targets[\"attention_mask\"].squeeze()\n return {\"source_ids\": source_ids, \"source_mask\": src_mask, \"target_ids\": target_ids, \"target_mask\": target_mask} \n\n\n# + id=\"mx0h_SPiKEY8\"\nmodel_path = 'parsT5'\nconfigs = {\n \"local_files_only\": True,\n \"from_flax\": True\n}\n# -\n\n# !pip install lfs\n# !git clone https://huggingface.co/Ahmad/parsT5\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"0rvcHiU4eFHA\" outputId=\"6b7feec4-b367-4698-9c05-3d9f6eb06133\"\nfrom google.colab import drive\ndrive.mount('./drive')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"nS3dfqbgRGn-\" outputId=\"c3e8c79e-d725-412e-a381-246042c09850\"\ntokenizer = AutoTokenizer.from_pretrained(model_path, **configs)#('Ahmad/parsT5-base')#('google/mt5-base')\ndataset = bigbang(train_data, tokenizer, 512, 150)\nlen(dataset)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"LmaEBH0QRKv4\" outputId=\"d807ea55-2733-409d-af14-4e87370fe230\"\ndata = dataset[50]\nprint()\nprint(\"Shape of Tokenized Text: \", data['source_ids'].shape)\nprint()\nprint(\"Sanity check - Decode Text: \", tokenizer.decode(data['source_ids']))\nprint(\"====================================\")\nprint(\"Sanity check - Decode Summary: \", tokenizer.decode(data['target_ids']))\n\n\n# + id=\"vutwd9MyYupu\"\ndef get_dataset(df, tokenizer, args):\n return bigbang(df, tokenizer=tokenizer, input_length=args.max_input_length, \n output_length=args.max_output_length)\n\n\n# + id=\"LN3h98Tf6tRl\"\nclass T5FineTuner(pl.LightningModule):\n def __init__(self, hparams):\n super(T5FineTuner, self).__init__()\n self.hparamss = hparams \n self.tokenizer = AutoTokenizer.from_pretrained(\"model2\")\n self.model = T5ForConditionalGeneration.from_pretrained(\"model2\")\n # self.model = T5ForConditionalGeneration.from_pretrained(hparams.model_name_or_path)\n # self.tokenizer = AutoTokenizer.from_pretrained(hparams.tokenizer_name_or_path)\n# self.rouge_metric = load_metric('rouge') \n n_observations_per_split = {\n \"train\": self.hparamss.n_train,\n \"validation\": self.hparamss.n_val,\n \"test\": self.hparamss.n_test,\n }\n self.n_obs = {k: v if v >= 0 else None for k, v in n_observations_per_split.items()}\n def freeze_params(self, model):\n for par in model.parameters():\n par.requires_grad = False\n def lmap(self, f, x):\n \"\"\"list(map(f, x))\"\"\"\n return list(map(f, x))\n def is_logger(self):\n return self.trainer.global_rank <= 0\n def parse_score(self, result):\n return {k: round(v.mid.fmeasure * 100, 4) for k, v in result.items()} \n def forward(\n self, input_ids, attention_mask=None, decoder_input_ids=None, decoder_attention_mask=None, labels=None\n ):\n return self.model(\n input_ids,\n attention_mask=attention_mask,\n decoder_input_ids=decoder_input_ids,\n decoder_attention_mask=decoder_attention_mask,\n labels=labels,\n )\n def _step(self, batch):\n labels = batch[\"target_ids\"]\n labels[labels[:, :] == self.tokenizer.pad_token_id] = -100\n outputs = self(\n input_ids=batch[\"source_ids\"],\n attention_mask=batch[\"source_mask\"],\n labels=labels,\n decoder_attention_mask=batch['target_mask'])\n loss = outputs[0]\n return loss\n def ids_to_clean_text(self, generated_ids):\n gen_text = self.tokenizer.batch_decode(\n generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True\n )\n return self.lmap(str.strip, gen_text)\n def _generative_step(self, batch) :\n t0 = time.time()\n generated_ids = self.model.generate(\n batch[\"source_ids\"],\n attention_mask=batch[\"source_mask\"],\n use_cache=True,\n decoder_attention_mask=batch['target_mask'],\n max_length=150, \n num_beams=2,\n repetition_penalty=2.5, \n length_penalty=1.0, \n early_stopping=True)\n preds = self.ids_to_clean_text(generated_ids)\n target = self.ids_to_clean_text(batch[\"target_ids\"]) \n gen_time = (time.time() - t0) / batch[\"source_ids\"].shape[0] \n loss = self._step(batch)\n base_metrics = {'val_loss': loss}\n summ_len = np.mean(self.lmap(len, generated_ids))\n base_metrics.update(gen_time=gen_time, gen_len=summ_len, preds=preds, target=target)\n# self.rouge_metric.add_batch(preds, target)\n return base_metrics\n def training_step(self, batch, batch_idx):\n loss = self._step(batch)\n tensorboard_logs = {\"train_loss\": loss}\n return {\"loss\": loss, \"log\": tensorboard_logs}\n def training_epoch_end(self, outputs):\n avg_train_loss = torch.stack([x[\"loss\"] for x in outputs]).mean()\n tensorboard_logs = {\"avg_train_loss\": avg_train_loss}\n def validation_step(self, batch, batch_idx):\n return self._generative_step(batch)\n def validation_epoch_end(self, outputs):\n avg_loss = torch.stack([x[\"val_loss\"] for x in outputs]).mean()\n tensorboard_logs = {\"val_loss\": avg_loss}\n# rouge_results = self.rouge_metric.compute() \n# rouge_dict = self.parse_score(rouge_results)\n# tensorboard_logs.update(rouge1=rouge_dict['rouge1'], rougeL=rouge_dict['rougeL'])\n self.target_gen= []\n self.prediction_gen=[]\n return {\"avg_val_loss\": avg_loss, \n# \"rouge1\" : rouge_results['rouge1'],\n# \"rougeL\" : rouge_results['rougeL'],\n \"log\": tensorboard_logs, 'progress_bar': tensorboard_logs}\n def configure_optimizers(self):\n \"Prepare optimizer and schedule (linear warmup and decay)\"\n model = self.model\n no_decay = [\"bias\", \"LayerNorm.weight\"]\n optimizer_grouped_parameters = [\n {\n \"params\": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)],\n \"weight_decay\": self.hparamss.weight_decay,\n },\n {\n \"params\": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)],\n \"weight_decay\": 0.0,\n },\n ]\n optimizer = AdamW(optimizer_grouped_parameters, lr=self.hparamss.learning_rate, eps=self.hparamss.adam_epsilon)\n self.opt = optimizer\n return [optimizer]\n def optimizer_step(self,\n epoch=None,\n batch_idx=None,\n optimizer=None,\n optimizer_idx=None,\n optimizer_closure=None,\n on_tpu=None,\n using_native_amp=None,\n using_lbfgs=None):\n optimizer.step()\n optimizer.zero_grad()\n optimizer_closure()\n self.lr_scheduler.step()\n def get_tqdm_dict(self):\n tqdm_dict = {\"loss\": \"{:.3f}\".format(self.trainer.avg_loss), \"lr\": self.lr_scheduler.get_last_lr()[-1]}\n return tqdm_dict\n def train_dataloader(self): \n n_samples = self.n_obs['train']\n train_dataset = get_dataset(train_data, tokenizer=self.tokenizer, args=self.hparamss)\n dataloader = DataLoader(train_dataset, batch_size=self.hparamss.train_batch_size, drop_last=True, shuffle=True, num_workers=2)\n t_total = (\n (len(dataloader.dataset) // (self.hparamss.train_batch_size * max(1, self.hparamss.n_gpu)))\n // self.hparamss.gradient_accumulation_steps\n * float(self.hparamss.num_train_epochs)\n )\n scheduler = get_linear_schedule_with_warmup(\n self.opt, num_warmup_steps=self.hparamss.warmup_steps, num_training_steps=t_total\n )\n self.lr_scheduler = scheduler\n return dataloader\n def val_dataloader(self):\n n_samples = self.n_obs['validation']\n validation_dataset = get_dataset(test_data,tokenizer=self.tokenizer, args=self.hparamss)\n return DataLoader(validation_dataset, batch_size=self.hparamss.eval_batch_size, num_workers=2)\n def test_dataloader(self):\n n_samples = self.n_obs['test']\n test_dataset = get_dataset(test_data, tokenizer=self.tokenizer, args=self.hparamss)\n return DataLoader(test_dataset, batch_size=self.hparamss.eval_batch_size, num_workers=2)\n\n\n# + id=\"5reD83P4vqXF\"\nlogger = logging.getLogger(__name__)\nclass LoggingCallback(pl.Callback):\n def on_validation_end(self, trainer, pl_module):\n logger.info(\"***** Validation results *****\")\n if pl_module.is_logger():\n metrics = trainer.callback_metrics\n for key in sorted(metrics):\n if key not in [\"log\", \"progress_bar\"]:\n logger.info(\"{} = {}\\n\".format(key, str(metrics[key])))\n\n def on_test_end(self, trainer, pl_module):\n logger.info(\"***** Test results *****\")\n if pl_module.is_logger():\n metrics = trainer.callback_metrics\n output_test_results_file = os.path.join(pl_module.hparams.output_dir, \"test_results.txt\")\n with open(output_test_results_file, \"w\") as writer:\n for key in sorted(metrics):\n if key not in [\"log\", \"progress_bar\"]:\n logger.info(\"{} = {}\\n\".format(key, str(metrics[key])))\n writer.write(\"{} = {}\\n\".format(key, str(metrics[key])))\n# logger = LoggingCallback()\n\n\n# +\nfrom pytorch_lightning.loggers import TensorBoardLogger\n\nlogger = TensorBoardLogger(\"logs/\", name=\"my_model\")\n\n# + id=\"WRq4BwiDvfIy\"\nargs_dict = dict(\n output_dir=\"model\", \n model_name_or_path='Ahmad/parsT5',\n tokenizer_name_or_path='Ahmad/parsT5',\n max_input_length=512,\n max_output_length=150,\n freeze_encoder=False,\n freeze_embeds=False,\n learning_rate=3e-4,\n weight_decay=0.0,\n adam_epsilon=1e-8,\n warmup_steps=0,\n train_batch_size=8,\n eval_batch_size=8,\n num_train_epochs=1,\n gradient_accumulation_steps=8,\n n_gpu=1,\n resume_from_checkpoint=None, \n val_check_interval = 10, \n limit_val_batches = 0,\n n_val=5,\n n_train=-1,\n n_test=-1,\n early_stop_callback=False,\n fp_16=False, # if you want to enable 16-bit training then install apex and set this to true\n opt_level='O1', # you can find out more on optimisation levels here https://nvidia.github.io/apex/amp.html#opt-levels-and-properties\n max_grad_norm=1.0, # if you enable 16-bit training then set this to a sensible value, 0.5 is a good default\n seed=42,\n)\n\n# + id=\"QpwvZUNvwiwh\"\n# !mkdir -p t5_bigbang\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"hPT6ceyQvbUR\" outputId=\"fe936187-4d5c-4bda-893c-9d3d0e6f859e\"\nargs_dict.update({ 'num_train_epochs':4,\n 'train_batch_size': 8, 'eval_batch_size': 8})\nargs = argparse.Namespace(**args_dict)\nprint(args_dict)\n\n# + id=\"czgubNOSvV6f\"\ncheckpoint_callback = pl.callbacks.ModelCheckpoint(\n dirpath=args.output_dir, monitor=\"val_loss\", mode=\"min\", save_top_k=3\n)\ntrain_params = dict(\n accumulate_grad_batches=args.gradient_accumulation_steps,\n gpus=args.n_gpu,\n max_epochs=5,\n # early_stop_callback=False,\n precision= 32,\n amp_backend='apex',\n amp_level=args.opt_level,\n resume_from_checkpoint=args.resume_from_checkpoint,\n gradient_clip_val=args.max_grad_norm,\n val_check_interval=args.val_check_interval,\n num_sanity_val_steps=0 ,\n limit_val_batches = 0,\n logger=logger,\n callbacks=[LoggingCallback()],\n)\n\n# + id=\"AhgHhiAlzjmq\"\nmodel = T5FineTuner(args)\n# -\n\nmodel.model.save_pretrained('parsT5')\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"GNIigBRw1vq6\" outputId=\"4e1a1c3c-b50b-4f8d-c0aa-c3b6a05d3045\"\ntrainer = pl.Trainer(**train_params)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 347, \"referenced_widgets\": [\"9e62ca451e9146d9a754f43a782fae63\", \"1eb7e082e87a4391af2f1709b922026e\", \"0d325e1310554dcd9ec1621da7aad860\", \"02236697a1c742c39aa921bfde36e8c8\", \"2b8905ab953943ba8bf02099a8ce2382\", \"d835b21a1f8643d4afb32513abe0adb7\", \"ea1d3177d5c6489f974569763842a8d0\", \"86c7ae40504a4ea484d4559c8eabd6a1\", \"daad5d1dbd3a463abc9769a402e78326\", \"b396aabd83374914874d02f0e50acfd9\", \"74fbcec5dec04d84b906aa41f7b209b6\"]} id=\"_deAgQDB2CSq\" outputId=\"ed98ecdd-1eca-4d22-cc00-e5d5ed82a5fd\"\ntrainer.fit(model)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"fW-0_ULdSyw4\" outputId=\"ac5dcfe1-eed9-43e0-f985-4eedba60acb5\"\n# !mkdir model_final\nmodel.model.save_pretrained('./model_final')\nmodel.tokenizer.save_pretrained('./model_final')\n# -\n\n# model2.model.from_pretrained('./model2')\nmodel2.tokenizer.from_pretrained('./model2')\n\n# + [markdown] id=\"YdxlTjdoCwdM\"\n# ### testing\n\n# + id=\"MPRklSDBSyw5\"\ndf = df_test\n\n# + id=\"aAFJzvioCydb\"\ntokenizer = AutoTokenizer.from_pretrained('./model_final')\nmodel = T5ForConditionalGeneration.from_pretrained('./model_final')\ndataset = bigbang(test_data, tokenizer, 512, 150)\n# -\n\ntokenizer.save_pretrained(\"./model2\")\n\n# + id=\"UQWK-GjIDSCg\"\nmodel.to('cuda')\ndec, targets = [], []\nfor i in range(len(test_data)//32):\n loader = DataLoader(dataset, 32, shuffle=True)\n it = iter(loader)\n batch = next(it)\n batch[\"source_ids\"].shape\n outs = model.generate(\n batch[\"source_ids\"].cuda(),\n attention_mask=batch[\"source_mask\"].cuda(),\n use_cache=True,\n decoder_attention_mask=batch['target_mask'].cuda(),\n max_length=150, \n num_beams=2,\n repetition_penalty=2.5, \n length_penalty=1.0, \n early_stopping=True\n )\n\n dec = dec + [tokenizer.decode(ids) for ids in outs]\n\n# texts = [tokenizer.decode(ids) for ids in batch['source_ids']]\n targets = targets + [tokenizer.decode(ids) for ids in batch['target_ids']]\n\n# + id=\"yYqn4AUuWnSu\"\nd_test = pd.DataFrame()\nd_test['pred'] = dec\nd_test['target'] = targets\n\n# + id=\"3OX97xkCWpmT\"\nd_test['pred'] = [i.replace('', '').replace('', '').strip() for i in d_test['pred']]\nd_test['target'] = [i.replace('', '').replace('', '') for i in d_test['target']]\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 424} id=\"R5_PcnmBFqPu\" outputId=\"8348ef13-e92a-4119-a1bc-299ef4df5f5c\"\nd_test \n\n# + id=\"dS7rqD_MKcpc\"\nd_test.to_csv('./model/outs.csv')\n\n# + id=\"4Uq-hKqzK-DU\"\nd_test = pd.read_csv('./model/outs.csv')\n\n# +\nfrom nltk.translate.bleu_score import sentence_bleu\n\n\ndef compute_f1(prediction, answer):\n pred_tokens = prediction.split()\n answer_tokens = answer.split()\n \n if len(pred_tokens) == 0 or len(answer_tokens) == 0:\n return int(pred_tokens == answer_tokens)\n \n common_tokens = set(pred_tokens) & set(answer_tokens)\n \n if len(common_tokens) == 0:\n return 0\n \n prec = len(common_tokens) / len(pred_tokens)\n rec = len(common_tokens) / len(answer_tokens)\n \n return 2 * (prec * rec) / (prec + rec)\n\n \n prec = len(common_tokens) / len(pred_tokens)\n rec = len(common_tokens) / len(answer_tokens)\n \n return 2 * (prec * rec) / (prec + rec)\n\ndef compute_exact_match(prediction, answer):\n return int(prediction == answer)\n\ndef bleu(prediction, answer) : \n reference = [answer.split(' ')]\n candidate = pred.split(' ')\n BLEU = sentence_bleu(reference, candidate)\n BLEU1 = sentence_bleu(reference, candidate, weights=(1, 0, 0, 0))\n BLEU4 = sentence_bleu(reference, candidate, weights=(0, 0, 0, 1))\n\n return BLEU, BLEU1, BLEU4\n\n\n\n# +\nEH = 0\nF1 = 0\nBLEU = 0\nBLEU1 = 0\nBLEU4 = 0\nfor idx, row in d_test.iterrows():\n target = row['target']\n pred = row['pred']\n if target == '':\n if pred == 'بدون پاسخ':\n EH += 1\n F1 += 1\n BLEU += 1\n BLEU1 += 1\n BLEU4 += 1\n continue\n\n EH += compute_exact_match(pred, target)\n F1 += compute_f1(pred, target)\n b, b1, b4 = bleu(pred, target)\n BLEU += b\n BLEU1 += b1\n BLEU4 += b4\n\nEH /= len(d_test)\nF1 /= len(d_test)\nBLEU /= len(d_test)\nBLEU1 /= len(d_test)\nBLEU4 /= len(d_test)\n \n\n# +\nprint('Exact match of ParsT5 on testset : ' + str(EH))\nprint('F1 score of ParsT5 on testset : ' + str(F1))\n# print('BLEU score of ParsT5 on testset : ' + str(BLEU))\nprint('BLEU1 score of ParsT5 on testset : ' + str(BLEU1))\n# print('BLEU4 score of ParsT5 on testset : ' + str(BLEU4))\n \n\n","repo_name":"vidarmz/Persian-QA-MLSD","sub_path":"ParsT5.ipynb","file_name":"ParsT5.ipynb","file_ext":"py","file_size_in_byte":19590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"44040392677","text":"import pandas as pd\nimport numpy as np\nimport pickle\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.multiclass import OneVsRestClassifier\n\n# +\nf1 = open(\"google_refine.txt\", \"r\", encoding=\"utf8\")\nrev_data = f1.read()\nrev_list = rev_data.split('\\n')\nrev_list = [sent for sent in rev_list if sent != '']\nf1.close()\n\nsize = len(rev_list)\ntest_text = np.asarray(rev_list)\n\n# +\nvectorizer = pickle.load(open(\"vectorizer.pickle\", \"rb\"))\n\nx_test = vectorizer.transform(test_text)\n# -\n\n# # Multi-class classification (only BOW, excluding metadata)\n\n# ## Multiple Binary Classifications - (One Vs Rest Classifier)\n\n# +\nclassifier_b = pickle.load(open(\"classifier_b.pickle\", \"rb\"))\nclassifier_f = pickle.load(open(\"classifier_f.pickle\", \"rb\"))\nclassifier_r = pickle.load(open(\"classifier_r.pickle\", \"rb\"))\nclassifier_u = pickle.load(open(\"classifier_u.pickle\", \"rb\"))\n\nprediction_b = classifier_b.predict(x_test)\nprediction_f = classifier_f.predict(x_test)\nprediction_r = classifier_r.predict(x_test)\nprediction_u = classifier_u.predict(x_test)\n# -\n\nprint(prediction_b)\nprint(prediction_f)\nprint(prediction_r)\nprint(prediction_u)\n\n\n","repo_name":"CS17B022/Team_2_AppStoreAnalysis","sub_path":"final_release/final_release/appStoreAnalysis_r2/appRecommend/classify/.ipynb_checkpoints/exp-checkpoint.ipynb","file_name":"exp-checkpoint.ipynb","file_ext":"py","file_size_in_byte":1291,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"24939116984","text":"# +\n# %load_ext autoreload\n# %autoreload 2\n\nimport sys, os\n\nimport matplotlib.style as style\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport time\nfrom tqdm import tqdm\n\nimport scqubits as scq\nimport qutip as qt\nimport qutip.visualization as qplt\n\nfrom PulseSequence import PulseSequence\nfrom QSwitch import QSwitch\n\nstyle.use('default')\nplt.rcParams['figure.figsize'] = [9.7, 6]\ndefault_colors = plt.rcParams['axes.prop_cycle'].by_key()['color']\n# scq.settings.PROGRESSBAR_DISABLED = True\n\n# +\nhbar = 1.054e-34\nh = hbar*2*np.pi\nqe = 1.602e-19\nred_flux_quant = hbar/2/qe \n\n# Unit conversions\nMHz = 10.0**(-3)\nGHz = 1.0\nkHz = 10.0**(-6)\nus = 10.0**3\nns = 1.0\n# -\n\n# Plotting functions\n\n# +\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\ndef show_mat_2d(mat, ax, title, labels, cmax=1, show=True):\n \"\"\"\n Plot an arbitrary 2D matrix with labels\n \"\"\"\n plt.sca(ax)\n plt.title(title, fontsize=18)\n plt.imshow(np.real(mat), cmap='RdBu')\n # hinton(np.real(mat), xlabels=labels, ylabels=labels)\n plt.xticks(np.arange(len(mat)), labels, fontsize=18)\n plt.yticks(np.arange(len(mat)), labels, fontsize=18)\n # Loop over data dimensions and create text annotations.\n for ii in range(len(mat)):\n for jj in range(len(mat)):\n plt.text(ii, jj, round(mat[jj, ii], 3), ha=\"center\", va=\"center\", color=\"w\", size=16)\n divider = make_axes_locatable(ax)\n cax = divider.append_axes(\"right\", size=\"5%\", pad=0.05)\n cbar = plt.colorbar(cax=cax, ticks=[-cmax, 0, cmax])\n cbar.ax.tick_params(labelsize=14)\n plt.clim(vmin=-cmax, vmax=cmax)\n plt.tight_layout()\n if show: plt.show()\n\ndef show_plot_rho_2d(rho_sim, rho_id=None, title='', cmax=None, savetitle=None):\n \"\"\"\n Plot real and imag parts of rho, optionally also with a comparison ideal rho\n \"\"\"\n if savetitle is not None: plt.style.use('dark_background')\n\n labels = [\"00\", \"01\", \"10\", \"11\"]\n if rho_id is None:\n fig = plt.figure(figsize=(12, 4))\n ax1 = fig.add_subplot(121)\n ax2 = fig.add_subplot(122)\n else:\n fig = plt.figure(figsize=(10, 8))\n ax1 = fig.add_subplot(221)\n ax2 = fig.add_subplot(222)\n ax3 = fig.add_subplot(223)\n ax4 = fig.add_subplot(224)\n plt.suptitle(title, fontsize=18)\n if cmax is None: cmax = np.max(np.abs(np.array([np.real(rho_sim), np.imag(rho_sim), np.real(rho_id), np.imag(rho_id)])))\n show_mat_2d(np.real(rho_sim), ax=ax1, title=\"Re[$\\\\rho_{Sim}$]\", labels=labels, cmax=cmax, show=False)\n show_mat_2d(np.imag(rho_sim), ax=ax2, title=\"Im[$\\\\rho_{Sim}$]\", labels=labels, cmax=cmax, show=False)\n if rho_id is not None:\n show_mat_2d(np.real(rho_id), ax=ax3, title=\"Re[$\\\\rho_{Ideal}$]\", labels=labels, cmax=cmax, show=False)\n show_mat_2d(np.imag(rho_id), ax=ax4, title=\"Im[$\\\\rho_{Ideal}$]\", labels=labels, cmax=cmax, show=False)\n plt.tight_layout()\n\n if savetitle is not None:\n plt.savefig(savetitle, format='png', bbox_inches='tight', transparent = True)\n \n plt.show()\n\n\ndef show_plot_rho_3d(rho_sim, rho_id=None, title='', zmin=None, zmax=None, width=0.75, elev=30, azim=-20, savetitle=None):\n if savetitle is not None: plt.style.use('dark_background')\n fig = plt.figure(figsize=(15, 7))\n ax1 = fig.add_subplot(121, projection='3d')\n ax2 = fig.add_subplot(122, projection='3d')\n \n labels = [\"00\", \"01\", \"10\", \"11\"]\n _xx, _yy = np.meshgrid(np.arange(4), np.arange(4))\n x, y = _xx.ravel(), _yy.ravel()\n if zmax is None: zmax = np.max(np.array([np.real(rho_sim), np.imag(rho_sim), np.real(rho_id), np.imag(rho_id)]))\n if zmin is None: zmin = np.min((0, np.min(np.array([np.real(rho_sim), np.imag(rho_sim), np.real(rho_id), np.imag(rho_id)]))))\n\n ax1.view_init(elev=elev, azim=azim)\n ax1.set_xticks(np.arange(4), minor=False)\n ax1.set_xticklabels(labels, fontdict=None, minor=False, fontsize=16)\n ax1.set_yticks(np.arange(1, 5, 1), minor=False)\n ax1.set_yticklabels(labels, fontdict=None, minor=False, fontsize=16)\n for t in ax1.zaxis.get_major_ticks(): t.label.set_fontsize(16)\n ax1.bar3d(x, y, z=np.zeros((16)), dx=width, dy=width, dz=np.real(rho_id).flatten(), edgecolor='k', alpha=0)\n ax1.bar3d(x, y, z=np.zeros((16)), dx=0.95*width, dy=width, dz=np.real(rho_sim).flatten(), color='cornflowerblue', edgecolor='mediumblue', alpha=1.0)\n ax1.set_zlim(zmin, zmax)\n ax1.set_title(\"Re[$\\\\rho$]\", fontsize=20)\n\n ax2.view_init(elev=elev, azim=azim)\n ax2.set_xticks(np.arange(4), minor=False)\n ax2.set_xticklabels(labels, fontdict=None, minor=False, fontsize=16)\n ax2.set_yticks(np.arange(1, 5, 1), minor=False)\n ax2.set_yticklabels(labels, fontdict=None, minor=False, fontsize=16)\n for t in ax2.zaxis.get_major_ticks(): t.label.set_fontsize(16)\n ax2.bar3d(x, y, z=np.zeros((16)), dx=width, dy=width, dz=np.imag(rho_id).flatten(), edgecolor='k', alpha=0)\n ax2.bar3d(x, y, z=np.zeros((16)), dx=0.95*width, dy=width, dz=np.imag(rho_sim).flatten(), color='cornflowerblue', edgecolor='mediumblue', alpha=1.0)\n ax2.set_zlim(zmin, zmax)\n ax2.set_title(\"Im[$\\\\rho$]\", fontsize=20)\n\n plt.suptitle(title, fontsize=22)\n plt.tight_layout()\n\n if savetitle is not None:\n plt.savefig(savetitle, format='png', bbox_inches='tight', transparent=True)\n plt.show()\n\n\n# -\n\n# # Get couplings and bare frequencies by optimization\n\nsys.path.append(os.getcwd()+'/../../qutip_sims')\nfrom scipy.optimize import minimize\nfrom slab import AttrDict\n\n\n# Provide measured qubit freqs (GHz), alphas (GHz), ZZ matrix (GHz)\n# For use in optimization\ndef ZZ_g_fq_diff(fqs_gs, *args):\n qubit_freqs, alphas, ZZ_matrix = args # measured values\n fqs = fqs_gs[:4] \n gs = fqs_gs[4:]\n # print(args)\n qram = QSwitch(\n EJs=None,\n ECs=None,\n gs=gs,\n qubit_freqs=fqs,\n alphas=alphas,\n cutoffs=[4, 5, 4, 4],\n isCavity=[False]*4,\n )\n # print(qram.get_ZZ_matrix())\n # return np.sum(np.abs(ZZ_matrix - qram.get_ZZ_matrix()))\n error_ZZ = np.sum(np.abs(1e3*(ZZ_matrix - qram.get_ZZ_matrix()))**2)\n error_fq = 0\n gstate = 'gggg'\n for i in range(4):\n estate = gstate[:i] + 'e' + gstate[i+1:]\n error_fq += np.sum(np.abs(1e3*(qram.get_base_wd(gstate, estate)/2/np.pi - qubit_freqs[i])**2))\n return error_ZZ + error_fq\n\n\n# config_dir = 'C:\\\\Users\\\\slab\\\\Desktop\\\\Connie\\\\experiments\\\\qramLL_4QR2'\nconfig_dir = 'S:\\\\Connie\\\\experiments\\\\qramLL_4QR2'\n# config_file = 'config_zcu216.yml'\n# config_file = 'config_q3diamond.yml'\n# config_file = 'config_q3diamond_full688_reset.yml'\nconfig_file = 'config_q3diamond_full688and638_reset.yml'\nconfig_path = config_dir + '\\\\' + config_file\nprint('Config will be', config_path)\n\n# +\nimport yaml\nwith open(config_path, 'r') as cfg_file:\n yaml_cfg = yaml.safe_load(cfg_file)\nyaml_cfg = AttrDict(yaml_cfg)\n\nqubit_freqs_MHz = np.array(yaml_cfg.device.qubit.f_ge) + np.array(yaml_cfg.hw.soc.dacs.qubit.mixer_freq)\nef_freqs_MHz = np.array(yaml_cfg.device.qubit.f_ef)\nalphas_MHz = ef_freqs_MHz + np.array(yaml_cfg.hw.soc.dacs.qubit.mixer_freq) - qubit_freqs_MHz\nZZshifts_MHz = np.reshape(np.array(yaml_cfg.device.qubit.ZZs), (4,4)) # MHz\n\nprint('qubit freqs', qubit_freqs_MHz)\nprint('ef freqs', ef_freqs_MHz)\nprint('alphas', alphas_MHz)\n\n# +\ndelta_fq = 20e-3 # GHz away from measured\nx0 = np.array([*qubit_freqs_MHz, 100, 100, 100, 10, 10, 10])\nbounds_fq = [(1e-3*fq_MHz - delta_fq, 1e-3*fq_MHz + delta_fq) for fq_MHz in qubit_freqs_MHz]\nbounds = [*bounds_fq, (1e-3, 2e-1), (1e-3, 2e-1), (1e-3, 2e-1), (1e-3, 2e-1), (1e-3, 2e-1), (1e-3, 2e-1)] # GHz\n\nresult = minimize(ZZ_g_fq_diff, x0=1e-3*x0, args=(1e-3*qubit_freqs_MHz, 1e-3*alphas_MHz, 1e-3*ZZshifts_MHz), bounds=bounds , method='L-BFGS-B')\n# -\n\nprint(f'Success: {result.success}')\nfqs_gs_opt = result.x\nfqs_opt = fqs_gs_opt[:4] \ngs_opt = fqs_gs_opt[4:]\n\n\n# Optimize to get EJ, EC values\n\n# +\ndef transmon_f0n(n, EC, EJ):\n return np.sqrt(8*EJ*EC)*n - EC/12*(6*n**2 + 6*n + 3) + EC/4\ndef transmon_fge(EC, EJ):\n return transmon_f0n(1, EC, EJ)\ndef transmon_fef(EC, EJ):\n return transmon_f0n(2, EC, EJ) - transmon_f0n(1, EC, EJ)\ndef transmon_alpha(EC, EJ):\n return transmon_fef(EC, EJ) - transmon_fge(EC, EJ)\n\ndef ECEJ_cost(ECEJ, *args):\n EC, EJ = ECEJ\n f_ge, f_ef = args # measured values\n return (transmon_fge(EC, EJ) - f_ge)**2 + (transmon_fef(EC, EJ) - f_ef)**2\n\nEJopts = []\nECopts = []\nfor q in range(4):\n # x0 = np.array([qubit_freqs_MHz[q], ef_freqs_MHz[q]])*1e-3 # GHz\n x0 = [200, 16000]\n bounds = [(10, 1000), (1000, 100000)] # GHz\n bounds = None\n result = minimize(ECEJ_cost, x0=x0, args=(qubit_freqs_MHz[q], ef_freqs_MHz[q]), bounds=bounds, method='L-BFGS-B')\n EC_opt, EJ_opt = result.x\n ECopts.append(EC_opt)\n EJopts.append(EJ_opt)\nprint('EJ optimized (GHz)', np.array(EJopts)*1e-3)\nprint('EC optimized (GHz)', np.array(ECopts)*1e-3)\n# -\n\nqram = QSwitch(\n EJs=None,\n ECs=None,\n gs=gs_opt,\n qubit_freqs=fqs_opt,\n alphas=1e-3*alphas_MHz,\n cutoffs=[4, 5, 4, 4],\n isCavity=[False]*4,\n)\nprint('Measured (coupled) qubits freqs [MHz]')\nprint(qubit_freqs_MHz)\nprint('Optimized (uncoupled) qubit freqs [MHz]')\nprint(1e3*fqs_opt)\nprint(f'Optimized g01, g12, g13, g02, g03, g23 [MHz]: {1e3*gs_opt}')\nprint()\nprint('ZZ matrix = (QA freq when QB is in e) - (QA freq when QB is in g) [MHz]')\nprint('Down: spectroscopy qubit (QA), Right: pi pulse qubit (QB)')\nprint('Measured ZZ matrix [MHz]')\nprint(ZZshifts_MHz)\nprint('Optimized ZZ matrix [MHz]')\nprint(1e3*qram.get_ZZ_matrix())\nprint()\nprint(f'Optimization error: {ZZ_g_fq_diff(fqs_gs_opt, 1e-3*qubit_freqs_MHz, 1e-3*alphas_MHz, 1e-3*ZZshifts_MHz)}')\n\n# +\n# MAKE SURE DRESSED STATES ARE MAPPED CORRECTLY, AT LEAST FOR <= n EXCITATIONS\n# qram.check_state_mapping(n=3)\n# -\n\n# # Set qubit parameters\n\n# +\n# # q_in, q_switch, q_out1, q_out2\n\n# # EJs = [13.41, 12.52, 8.94, 12.52]\n# # EJs = [12.109, 11.195, 7.997, 11.195]\n# # EJs = [17.523, 16.450, 11.622, 16.450]\n\n# # ECs = [0.237, 0.133, 0.270, 0.215]\n\n# # gs = [0.0827, 0.0787, 0.0652] # g01, g12, g13\n# # gs = [1e-3*73.44448637160531, 1e-3*70.62005211780702, 1e-3*58.4998799537415]\n# # gs = [1e-3*88.68898701296644, 1e-3*85.3693409331001, 1e-3*70.91300299056793]\n# # gs = [0,0,0]\n# # gs = [1e-3*66.56542672271766, 1e-3*65.06457214018066, 1e-3*51.68752851908644]\n# # gs = [0.0613, 0.0600, 0.0475]\n\n# qubit_freqs = None\n# alphas = None\n\n# EJs = None\n# ECs = None\n# # qubit_freqs = np.array([4140.530270731964, 3463.742568636059, 4800.079246546452, 4415.18623279066])*1e-3\n# qubit_freqs = np.array([4140.53027073, 3463.72489158, 4800.07924655, 4415.18623279])*1e-3\n# # alphas = [-0.182, -0.108, -0.220, -0.168]\n# ef_freqs = np.array([3914.7570214638718, 3363.398427976613, 4610.7977211230145, 4243.1626645869358])*1e-3\n# alphas = ef_freqs - qubit_freqs\n# print(alphas)\n# gs = np.array([54.38663964, 52.60236201, 41.1249601, 6.26475719, 2.73059709, 6.00700312])*1e-3 # g01, g12, g13, g02, g03, g23\n# # gs = gs[:3]\n\n# # qubit_freqs = np.array([4146.29086881774893, 3464.7403852710677, 4806.4284729347243, 4426.85588770023173])*1e-3\n# # # alphas = [-0.182, -0.108, -0.220, -0.168]\n# # ef_freqs = np.array([4000-78.90376315971923, 3364.253, 4611.098326885819, 4254.36098271568733])*1e-3\n# # alphas = ef_freqs - qubit_freqs\n# # print(alphas)\n# # gs = [0.054, 0.043, 0.040] # g01, g12, g13\n\nfrom slab import AttrDict\nconfig_file = 'config_q3diamond_full688and638_reset.yml'\nconfig_path = os.getcwd() + '\\\\..\\\\experiments\\\\qramLL_4QR2\\\\' + config_file\nimport yaml\nwith open(config_path, 'r') as cfg_file:\n yaml_cfg = yaml.safe_load(cfg_file)\nyaml_cfg = AttrDict(yaml_cfg)\n\nqubit_freqs = np.array(yaml_cfg.device.qubit.f_ge) * 1e-3\n# qubit_freqs[0] -= 1.0\nef_freqs = np.array(yaml_cfg.device.qubit.f_ef) * 1e-3\n# ef_freqs[0] -= 1.0\ngs = np.array(yaml_cfg.device.qubit.gs) * 1e-3\n\nZZs_4q = None\n# ZZs_4q = np.reshape(np.array(yaml_cfg.device.qubit.ZZs), (4,4)) * 1e-3\nEJs = None\nECs = None\nalphas = ef_freqs - qubit_freqs\n\nprint(qubit_freqs*1e3)\nprint(ef_freqs*1e3)\nprint(alphas*1e3)\nif gs is not None: print(gs*1e3)\nif ZZs_4q is not None: print(ZZs_4q*1e3)\n\n# -\n\n# # Analytical swap\n\n# +\ncutoffs = [4, 5, 4, 4]\n# cutoffs = [2, 3, 2, 2]\nisCavity = [False, False, False, False]\n\nqram = QSwitch(\n EJs=EJs,\n ECs=ECs,\n gs=gs,\n ZZs=ZZs_4q,\n qubit_freqs=qubit_freqs,\n alphas=alphas,\n cutoffs=cutoffs,\n isCavity=isCavity,\n useZZs=False,\n)\n\n# qram = QSwitch(\n# EJs=EJs,\n# ECs=ECs,\n# qubit_freqs=qubit_freqs,\n# alphas=alphas,\n# cutoffs=cutoffs,\n# isCavity=isCavity,\n# gs=None,\n# useZZs=True,\n# ZZs=ZZshifts_MHz*1e-3,\n# )\n\n\nqubit_freqs = qram.qubit_freqs\nalphas = qram.alphas\nprint('qubit freqs (GHz)', *qubit_freqs)\nprint('ef freqs (GHz)', *ef_freqs)\nprint('alphas (GHz)', *alphas)\n# print('aprox sideband freqs (GHz)', 2*qubit_freqs[1] + alphas[1] - qubit_freqs)\n# print([qram.get_base_wd('ggeg', 'gfgg')/2/np.pi])\n\n\n# print('capacitances (fF)', *(qe**2/(2*h*np.array(ECs)*1e9)*1e15))\n# print('lumped L (nH)', *(red_flux_quant**2/h/np.array(EJs)))\nprint(qubit_freqs-qubit_freqs[0])\n# -\n\nprint('ZZ matrix = (QA freq when QB is in e) - (QA freq when QB is in g) [MHz]')\nprint('Down: spectroscopy qubit (QA), Right: pi pulse qubit (QB)')\nprint(1e3*qram.get_ZZ_matrix())\n\n# ## Create pulse sequence\n\n# ### Set pulses phases and amps\n\n# +\nphase_I = -np.pi/2 # |0+1>\n# phase_I = -np.pi # |0+i1>\n\nphase_S = -np.pi/2 # doesn't affect the protocol implementation, just definining the initialization phase (?)\n\nphase_IS = 0\nphase_SL = 0\nphase_SR = 0\n\namp_swap_01 = 0.08\namp_swap_12 = 0.08\namp_swap_13 = 0.08\namp_pi = 0.01 # pi pulse in the protocol\namp_pi_2 = 0.01 # init pi pulse amp\namp_pi_2_2 = 0.01\n\n\n# -\n\n# ### Defining the ideal density matrix\n\n# +\ndef ideal_rho(phi_I, phi_IS, phi_SL, phi_SR):\n\n rho = np.zeros((4, 4), dtype = 'complex')\n\n rho[0, 0] = 0.5\n rho[1, 1] = 0.25\n rho[2, 2] = 0.25\n\n rho[0, 1] = 1j*np.exp(1j*(phi_IS - phi_SR + phi_I))/4\n rho[0, 2] = 1j*np.exp(1j*(phi_IS - phi_SL + phi_I))/4\n\n rho[1, 0] = np.conj(rho[0, 1])\n rho[2, 0] = np.conj(rho[0, 2]) \n\n rho = qt.Qobj(rho, dims=[[2, 2], [2, 2]])\n\n return rho \n\nrho_ideal = ideal_rho(phase_I, phase_IS, phase_SL, phase_SR)\nshow_plot_rho_2d(rho_sim=rho_ideal.full(), cmax=0.5)\n\n\n# -\n\n# ### Generate pulse sequence\n\n# QCTRL pulses\n\nfrom qctrl import Qctrl\nfrom qctrlvisualizer import get_qctrl_style, plot_controls\nqctrl = Qctrl()\n\n# ctrl_result = qctrl.get_result(action_id=1760758)\n# ctrl_result = qctrl.get_result(action_id=1761100) # 300 ns Q1 drive only, 16 input states\n# ctrl_result = qctrl.get_result(action_id=1761543)\n# ctrl_result = qctrl.get_result(action_id=1762374)\n# ctrl_result = qctrl.get_result(action_id=1764628)\nctrl_result = qctrl.get_result(action_id=1766039)\n\n# +\nprint(\"Fidelity:\", 1-ctrl_result.output[\"cost\"][\"value\"])\n\ncontrols = []\n\ncontrol_times = []\nI_values_pi = []\nQ_values_pi = []\ncontrol_qubits = []\nfor q in range(qram.nqubits):\n if f\"$\\gammaI_{q}$\" not in ctrl_result.output: continue\n I_values_q = []\n Q_values_q = []\n t = 0\n for j in range(2): # I, Q\n name = f\"$\\gamma{'I' if j==0 else 'Q'}_{q}$\"\n control = ctrl_result.output[name]\n for step, pulse in enumerate(control):\n if q==1 and j==0: control_times.append(t)\n t += pulse['duration']\n # factor of 1/2, -1, and 2pi due to how their controls are defined relative to ours\n if j==0: I_values_q.append(pulse['value'])\n else: Q_values_q.append(pulse['value'])\n\n # append to controls in same order as PICO/ALTRO pulses\n controls.append(-np.array(Q_values_q))\n controls.append(np.array(I_values_q))\n\n I_values_pi.append(I_values_q)\n Q_values_pi.append(Q_values_q)\n control_qubits.append(q)\n\ncontrol_times = np.array(control_times)\nI_values_pi = np.array(I_values_pi)\nQ_values_pi = np.array(Q_values_pi)\ncontrol_qubits = np.array(control_qubits)\n\nI_values = I_values_pi\nQ_values = Q_values_pi\n# plt.figure(figsize=(6,8))\nplt.suptitle('I, Q Controls (qubit drives)', fontsize=14)\nymax = 1.1*max(abs(np.concatenate((I_values.flatten(), Q_values.flatten()))))\n\ncontrols_index = 0\nfor q in range(qram.nqubits):\n if f\"$\\gammaI_{q}$\" not in ctrl_result.output: continue\n # plt.subplot(int(f'41{q+1}'))\n plt.plot(control_times, 1e3*I_values[controls_index], label=f'$I_{q}$')\n plt.plot(control_times, 1e3*Q_values[controls_index], label=f'$Q_{q}$')\n plt.ylim(-1e3*ymax, 1e3*ymax)\n plt.ylabel(f'$\\gamma_{q}/2\\pi$ [MHz]')\n plt.legend()\n controls_index += 1\nplt.xlabel('Times [ns]')\n# plt.tight_layout()\nplt.show()\n# -\n\n# PICO pulses\n\n# +\nimport h5py\nfilename = 'C:/Users/slab/Downloads/pulse_drives_0_1_3.hdf5'\n# filename = 'pulse_all_drives_1.hdf5'\n# filename = '../optimal_control/robust-pulses/out/qram/control_transmon_pi/00033_control_transmon_pi.h5'\nh5 = h5py.File(filename,'r')\nprint(h5.keys())\ncontrols = np.array(h5['pulse'])\ncontrol_times = np.array(h5['ts'])\nprint(controls.shape)\nplt.plot(control_times, controls)\ncontrols = controls.transpose()\nplt.xlabel('Time (ns)')\nplt.ylabel('Amplitude (GHz)')\nplt.title('Controls')\nplt.show()\n\ncontrol_qubits = [0, 1, 3]\n\ncontrol_index = 0\nfor q in control_qubits:\n controls_q = [controls[2*control_index], controls[2*control_index+1]]\n I_q=controls_q[1]\n Q_q=-controls_q[0]\n fourier = np.fft.fftshift(np.abs(np.fft.fft(I_q + 1j*Q_q)))\n freqs = np.fft.fftshift(np.fft.fftfreq(len(fourier), d=(control_times[1]-control_times[0])))\n plt.plot(1e3*freqs, fourier, label=f'Q{q}')\n control_index += 1\nplt.xlabel('Frequency [MHz]')\nplt.xlim(-1200, 1200)\nplt.title('FFT')\nplt.legend()\nplt.show()\n\n# -\n\n# Altro pulses\n\n# +\nimport h5py\nfilename = '../optimal_control/robust-pulses/out/qram/control_transmon_pi/00033_control_transmon_pi.h5'\nh5 = h5py.File(filename,'r')\nprint(h5.keys())\ncontrols_idx = np.array(h5['controls_idx'])\ncontrol_times = np.array(h5['ts'])\nprint('dt', control_times[1], 'num steps', len(control_times))\nprint(controls_idx)\nprint(np.array(h5['astates']).shape)\nprint(control_times.shape)\ncontrols = np.array(h5['astates'][controls_idx[0]-1:controls_idx[1], :])/2/np.pi\ncontrols = np.array([np.append(controls[0], [0]), np.append(controls[1], [0])])\ncontrol_times = np.append(control_times, [control_times[-1]+(control_times[1]-control_times[0])])\ncontrols = np.array(controls)\nprint(controls.shape)\n# for i in range(len(controls)):\n# for j in range(len(controls[0])):\n# controls[i,j] = min(controls[i,j], 0.02)\n# controls[i,j] = max(controls[i,j], -0.02)\n\nplt.plot(control_times, controls[0])\nplt.plot(control_times, controls[1])\n# plt.ylim(-0.02, 0.02)\nplt.xlabel('Time (ns)')\nplt.ylabel('Amplitude (GHz)')\nplt.title('Controls')\nplt.show()\n\nacontrols = np.array(h5['acontrols'])/2/np.pi\nplt.plot(control_times[:-2], acontrols[0])\nplt.plot(control_times[:-2], acontrols[1])\nplt.xlabel('Time (ns)')\nplt.ylabel('Amplitude (GHz)')\nplt.title('Second Derivative of Controls')\nplt.show()\n# -\n\n# import into pulse sequence\n\nseq = PulseSequence(start_time=0)\nwd00 = qram.get_base_wd('gggg', 'gegg')\n# qram.add_precise_pi_pulse(seq, 'gggg', 'gegg', wd=wd00, amp=0.01, drive_qubit=1, type='gauss', sigma_n=4, phase=0)\nwd01 = qram.get_base_wd('ggge', 'gege')\nqram.add_precise_pi_pulse(seq, 'gggg', 'gegg', wd=(wd00+wd01)/2, amp=0.01, drive_qubit=1, type='gauss', sigma_n=4, phase=0)\n# qram.add_precise_pi_pulse(seq, 'gggg', 'gegg', amp=0.015, mu=6, beta=4, drive_qubit=1, type='adiabatic', phase=0, t_pulse=120*4, wd=wd)\n# wd00 = qram.add_sequential_pi_pulse(seq, 'gggg', 'gegg', amp=0.01, drive_qubit=1, type='gauss', phase=-np.pi/2, pihalf=False)\n# seq.pulse_IQ(wd=wd, amp=1, pulse_levels=('gggg', 'gegg'), I_values=controls[1], Q_values=-controls[0], times=control_times, drive_qubit=1, t_start=0, phase=0)\n# seq.pulse_IQ(wd=wd+2*np.pi*5e-3, amp=1, pulse_levels=('gggg', 'gegg'), I_values=controls[1], Q_values=-controls[0], times=times, drive_qubit=1, t_start=0, phase=np.pi/2)\n\n# +\nseq = PulseSequence(start_time=0)\n# for q in range(4):\n\nqubit_frame = 1 # qubit frequency to rotate at\nprint(f'using rotating frame of qubit {qubit_frame}')\n\ncontrol_index = 0\nfor q in control_qubits:\n gstate = 'gggg'\n estate = gstate[:qubit_frame]+'e'+gstate[qubit_frame+1:]\n wd = qram.get_base_wd(gstate, estate)\n print(wd/2/np.pi)\n # wd = 2*np.pi*qram.qubit_freqs[q]\n controls_q = [controls[2*control_index], controls[2*control_index+1]]\n # seq.pulse_IQ(wd=wd, amp=1, pulse_levels=(gstate, estate), I_values=0*controls_q[1], Q_values=-0*controls_q[0], times=control_times, drive_qubit=q, t_start=0, phase=0)\n seq.pulse_IQ(wd=wd, amp=1, pulse_levels=(gstate, estate), I_values=controls_q[1], Q_values=-controls_q[0], times=control_times, drive_qubit=q, t_start=0, phase=0)\n print(f'added pulse IQ on qubit {q}')\n # seq.pulse_IQ(wd=wd, amp=1, pulse_levels=(gstate, estate), I_values=controls_q[1], Q_values=controls_q[0], times=control_times, drive_qubit=q, t_start=0, phase=0)\n control_index += 1\n\n# +\nseq = PulseSequence(start_time=0)\n\namp = 0.008\nt_pulse = qram.get_Tpi('gggg', 'eggg', amp=amp, drive_qubit=0, type='gauss')\n\nwd00 = qram.add_precise_pi_pulse(seq, 'gggg', 'eggg', amp=amp, t_pulse=t_pulse, drive_qubit=0, type='gauss', phase=0, sigma_n=4)\n# qram.add_precise_pi_pulse(seq, 'gggg', 'eggg', amp=amp, wd=wd00, t_pulse=t_pulse, drive_qubit=1, type='gauss', phase=0, t_offset=-seq.get_pulse_lengths()[-1], sigma_n=4)\n# qram.add_precise_pi_pulse(seq, 'gggg', 'eggg', amp=amp, wd=wd00, t_pulse=t_pulse, drive_qubit=2, type='gauss', phase=0, t_offset=-seq.get_pulse_lengths()[-1], sigma_n=4)\n# qram.add_precise_pi_pulse(seq, 'gggg', 'eggg', amp=amp, wd=wd00, t_pulse=t_pulse, drive_qubit=3, type='gauss', phase=0, t_offset=-seq.get_pulse_lengths()[-1], sigma_n=4)\n\n\n# +\nseq = PulseSequence(start_time=0)\n\n\n# ---- PREPARE Q1 and Q2\n\n# # |0>|0+1>\n# wd01 = qram.add_sequential_pi_pulse(seq, 'gggg', 'gegg', amp=amp_pi_2, drive_qubit=1, type='gauss', phase=-np.pi/2, pihalf=True)\n\n# # |1>|0+1>\n# wd00 = qram.add_sequential_pi_pulse(seq, 'gggg', 'eggg', amp=amp_pi_2, drive_qubit=0, type='gauss', phase=0, pihalf=False)\n# wd01 = qram.add_sequential_pi_pulse(seq, 'eggg', 'eegg', amp=amp_pi_2, drive_qubit=1, type='gauss', phase=-np.pi/2, pihalf=True)\n\n# |0+1>|0+1>\nphase_I = -np.pi/2\nwd00 = qram.add_sequential_pi_pulse(seq, 'gggg', 'eggg', amp=amp_pi_2, drive_qubit=0, type='gauss', phase=-np.pi/2, pihalf=True)\nwd01_1 = qram.get_wd('eggg', 'eegg', amp=amp_pi_2_2, drive_qubit=1, verbose=True)\nTpi_1 = qram.get_Tpi('eggg', 'eegg', amp=amp_pi_2_2, drive_qubit=1, type='gauss')\nwd01_2 = qram.get_wd('gggg', 'gegg', amp=amp_pi_2_2, drive_qubit=1, verbose=True)\nTpi_2 = qram.get_Tpi('gggg', 'gegg', amp=amp_pi_2_2, drive_qubit=1, type='gauss')\nwd01 = qram.add_sequential_pi_pulse(seq, 'eggg', 'eegg', amp=amp_pi_2_2, t_pulse=(Tpi_1+Tpi_2)/2/2, drive_qubit=1, type='gauss', phase=phase_I, pihalf=True, wd=np.average((wd01_1, wd01_2)))\n\n# # |0+i1>|0+1>\n# phase_I = -np.pi\n# wd00 = qram.add_sequential_pi_pulse(seq, 'gggg', 'eggg', amp=amp_pi_2, drive_qubit=0, type='gauss', phase=phase_I, pihalf=True)\n# wd01_1 = qram.get_wd('eggg', 'eegg', amp=amp_pi_2_2, drive_qubit=1, verbose=True)\n# wd01_2 = qram.get_wd('gggg', 'gegg', amp=amp_pi_2_2, drive_qubit=1, verbose=True)\n# wd01 = qram.add_sequential_pi_pulse(seq, 'eggg', 'eegg', amp=amp_pi_2_2, drive_qubit=1, type='gauss', phase=-np.pi/2, pihalf=True, wd=np.average((wd01_1, wd01_2)))\n\n\n# ---- FORWARD PROTOCOL ---- \n\n# First swap\nprint('w_swap_0')\nw_swap_0 = qram.get_wd('eggg', 'gfgg', amp=amp_swap_01, drive_qubit=1, verbose=True)\nwd0 = qram.add_sequential_pi_pulse(seq, 'eggg', 'gfgg', amp=amp_swap_01, drive_qubit=1, phase=phase_IS, wd=w_swap_0)\n\nprint('w_swap_1')\nw_swap_1 = qram.get_wd('gfgg', 'ggeg', amp=amp_swap_12, drive_qubit=1, verbose=True)\nwd1 = qram.add_sequential_pi_pulse(seq, 'gfgg', 'ggeg', amp=amp_swap_12, drive_qubit=1, phase=phase_SL, wd=w_swap_1)\nprint('wd2')\n\n# Second swap\nprint('w_pi')\nwd2_1 = qram.get_wd('eegg', 'eggg', amp=amp_pi, drive_qubit=1, verbose=True)\nwd2_2 = qram.get_wd('ggeg', 'geeg', amp=amp_pi, drive_qubit=1, verbose=True)\nwd2_3 = qram.get_wd('gegg', 'gggg', amp=amp_pi, drive_qubit=1, verbose=True)\nwd2 = qram.add_sequential_pi_pulse(seq, 'eegg', 'eggg', amp=amp_pi, drive_qubit=1, \n wd=np.average((wd2_1, wd2_2, wd2_3)), type='gauss', phase=0)\n\nprint('w_swap_2')\nwd3 = qram.add_sequential_pi_pulse(seq, 'eggg', 'gfgg', amp=amp_swap_01, drive_qubit=1, wd=w_swap_0, phase=phase_IS)\n\nprint('w_swap_3')\nwd4 = qram.add_sequential_pi_pulse(seq, 'gfgg', 'ggge', amp=amp_swap_13, drive_qubit=1, phase=phase_SR)\n\nprint('w_pi')\nwd5_1 = qram.get_wd('ggge', 'gege', amp=amp_pi, drive_qubit=1, verbose=True)\nwd5_2 = qram.get_wd('geeg', 'ggeg', amp=amp_pi, drive_qubit=1, verbose=True)\nwd5_3 = qram.get_wd('gegg', 'gggg', amp=amp_pi, drive_qubit=1, verbose=True)\nwd5 = qram.add_sequential_pi_pulse(seq, 'ggge', 'gege', amp=amp_pi, \n drive_qubit=1, wd=np.average((wd5_1, wd5_2, wd5_3)), type='gauss', phase=0)\n\n\nprint('Done.')\n# -\n\n# CHECK FOR CLASHING LEVELS\ntolerance = 100*MHz\nproblem_pulses = qram.check_level_resonances(seq, tolerance=tolerance)\ngood_freqs = seq.get_pulse_freqs(simplified=True)\nprint(good_freqs)\nif len(problem_pulses.items()) == 0:\n print(f'No clashes found within {tolerance} GHz!')\nfor good_pulse, problem_pulse_dict in problem_pulses.items():\n print('Clashes to', tolerance,'GHz with', good_pulse[0], '<->', good_pulse[1], f'(freq = {good_freqs[good_pulse]})', 'tpi', qram.get_Tpi(good_pulse[0], good_pulse[1], amp=0.05))\n for problem_pulse, freq in problem_pulse_dict.items():\n diff_freq = np.abs(freq)-np.abs(good_freqs[good_pulse])\n if np.abs(diff_freq) > tolerance:\n diff_freq = 2*np.abs(freq)-np.abs(good_freqs[good_pulse])\n print('\\t', 'GOOD PULSE' if problem_pulse in good_freqs.keys() else '', problem_pulse[0], '<->', problem_pulse[1], freq, f'(off by {diff_freq*1e3} MHz)', 'tpi', qram.get_Tpi(problem_pulse[0], problem_pulse[1], amp=0.05))\n\nimport scqubits as sc\nEC = 0.280\nEJ = 3.470**2/8/EC\nprint(EJ, EC, EJ/EC)\ntransmon = sc.Transmon(EJ=EJ, EC=EC, ng=0, ncut=31)\n\n# +\nng_vals = np.linspace(0, 3, 300)\n\ndata = transmon.get_spectrum_vs_paramvals('ng', ng_vals, evals_count=6, subtract_ground=False, get_eigenstates=True, filename=None, num_cpus=None)\nge_freq = data.energy_table[:,1] - data.energy_table[:,0]\nplt.plot(ge_freq)\nplt.ylim(np.average(ge_freq)-0.01, np.average(ge_freq) + 0.01)\n# data.plot_evals_vs_paramvals(which=[0, 1],subtract_ground=True)\n# -\n\n# ### Plot pulse seq envelopes\n\n# +\nenvelope_seq = seq.get_envelope_seq()\npulse_amps = seq.get_pulse_amps()\npulse_freqs = seq.get_pulse_freqs()\npulse_lens = seq.get_pulse_lengths()\ndrive_funcs = seq.get_pulse_seq()\nprint(seq.get_pulse_freqs(), '(GHz)')\nprint(pulse_lens, '(ns)')\nprint('total pulse length', sum(seq.get_pulse_lengths()), 'ns')\n\n# times = []\n# tot_time = 0\n# for pulse_len in pulse_lens:\n# # times.append(np.linspace(tot_time, tot_time + pulse_len, 100))\n# nsteps = 50\n# dt = pulse_len/nsteps\n# if dt > 5: nsteps = int(pulse_len // 10)\n# times = np.append(times, np.linspace(tot_time, tot_time + pulse_len, nsteps))\n# tot_time = tot_time + pulse_len\n# print('num time points', len(times))\n\n# times = np.linspace(0, sum(seq.get_pulse_lengths())+10, 900)\n# times = np.linspace(0, sum(seq.get_pulse_lengths())+30, 200)\n# times = np.linspace(0, sum(seq.get_pulse_lengths()), 50)\ntimes = np.linspace(0, seq.get_pulse_lengths()[-1], 900)\n\nflat_times = np.array(times).flatten()\n# drive_v_times = []\nenvelope_v_times = []\nfor i in range(len(envelope_seq)):\n if isinstance(envelope_seq[i], list) and len(envelope_seq[i]) == 2:\n envelope_v_time_I = [pulse_amps[i]*envelope_seq[i][0](t)/MHz for t in flat_times]\n envelope_v_time_Q = [pulse_amps[i]*envelope_seq[i][1](t)/MHz for t in flat_times]\n plt.plot(flat_times, envelope_v_time_I, label=f'Pulse {i} I')\n plt.plot(flat_times, envelope_v_time_Q, label=f'Pulse {i} Q')\n else:\n envelope_v_time = [pulse_amps[i]*envelope_seq[i](t)/MHz for t in flat_times]\n envelope_v_times.append(envelope_v_time)\n plt.plot(flat_times, envelope_v_time, label=f'Pulse {i}')\nplt.xlabel('Time (ns)')\nplt.ylabel('Drive Amplitude (MHz)')\n# plt.xlim(0, 100)\nplt.title('Pulse Sequence')\nplt.legend()\nplt.show()\n# -\n\n# ## Run simulation\n\n# +\nT1 = 60e3 # ns\nT2 = 30e3 # ?\n\n# T1 = 10e3\n\n# c_ops = [\n# np.sqrt(1/T1)*qram.a,\n# np.sqrt(1/T1)*qram.b,\n# np.sqrt(1/T1)*qram.c,\n# np.sqrt(1/T1)*qram.d,\n# ]\n\nc_ops = None\n# -\n\n# Make extended qram state given 2q tomo result (e.g. from experiment) - assumes all other states are 0\n\n# +\nexptpsi0 = np.array(\n[[ 0.28 +0.j, -0.052+0.118j, 0.162-0.116j, -0.08 -0.028j],\n [-0.052-0.118j, 0.265+0.j, 0.023+0.02j, -0.154+0.077j],\n [ 0.162+0.116j, 0.023-0.02j, 0.276+0.j, -0.093-0.02j ],\n [-0.08 +0.028j, -0.154-0.077j, -0.093+0.02j, 0.18 +0.j ]])\n\nexptpsi0 = np.array(\n[[0.25, 0.25, 0.25, 0.25],\n [0.25, 0.25, 0.25, 0.25],\n [0.25, 0.25, 0.25, 0.25],\n [0.25, 0.25, 0.25, 0.25]] \n)\n\npsi0 = 0*qt.ket2dm(qram.state('gggg'))\nfor i in range(len(exptpsi0)):\n for j in range(len(exptpsi0[0])):\n iq0 = i // 2\n iq1 = i % 2\n jq0 = j // 2\n jq1 = j % 2\n # print(iq0, iq1, jq0, jq1, exptpsi0[i,j])\n psi0 += exptpsi0[i, j] * qram.make_bare((iq0, iq1, 0, 0)) * qram.make_bare((jq0, jq1, 0, 0)).dag()\npsi0 = psi0.unit()\n# print(psi0)\n# print(gggg)\n# np.abs([gggg.dag()*psi0*gggg])\n# -\n\n# SIMULATE\n\n# +\n# psi0_name = 'eggg'\n# psi0_name = 'gfgg'\n# psi0_name = 'efgg'\n# psi0_name = 'eegg'\n# psi0_name = 'ggeg'\n# psi0_name = 'ggge'\n\n# psi0 = qram.state(psi0_name)\n# psi0 = qram.state('gegg')\n# psi0 = (qram.state('gggg') + qram.state('eggg')).unit()\n# psi0 = (qram.state('gggg') + qram.state('gegg')).unit()\n# psi0 = (qram.state('eggg') + 1j*qram.state('eegg')).unit()\npsi0 = (qram.state('gggg') + qram.state('ggge')).unit()\n# psi0 = (qram.state('eggg', esys=esys_rot_wd) + 1j*qram.state('eegg', esys=esys_rot_wd)).unit()\n# psi0 = (qram.make_bare('eggg') + 1j*qram.make_bare('eegg')).unit()\n# psi0 = (qram.state('ggeg') + qram.state('geeg')).unit()\n# psi0 = (qram.state('ggge') + qram.state('gege')).unit()\n# psi0 = np.sqrt(0.5) * qram.state('gegg') + np.sqrt(0.5) * qram.state('eegg') # QRAM start |0+1>|1>\n# psi0 = np.sqrt(0.5) * qram.state('eggg') + np.sqrt(0.5) * qram.state('eegg') # QRAM start |1>|0+1>\n# psi0 = np.sqrt(0.5) * qram.state('gggg') + np.sqrt(0.5) * qram.state('gegg') # QRAM start |0>|0+1>\n# psi0 = (qram.state('eggg') + qram.state('eegg') + qram.state('gggg') + qram.state('gegg')).unit() # QRAM start |0+1>|0+1>\n# psi0 = (1j*qram.state('eggg') + 1j*qram.state('eegg') + qram.state('gggg') + qram.state('gegg')).unit() # QRAM start |0+i1>|0+1>\n\nresult_lab = qram.evolve(psi0, seq, times, c_ops=None, nsteps=200, use_str_solve=False)\n# result = qram.evolve_rot_frame(psi0, seq, times, c_ops=None, nsteps=20000)\n\n# gstate = 'gggg'\n# estate = gstate[:qubit_frame]+'e'+gstate[qubit_frame+1:]\n# wd = qram.get_base_wd(gstate, estate)\n# print(wd/2/np.pi)\n# result_lab = qt.mesolve(qram.H_solver_rot_wd(seq=seq, wframe=wd), psi0, times, progress_bar=True, options=qt.Options(nsteps=1000)).states\n# -\n\n# result = [result_lab_t.unit() for result_lab_t in result_lab]\nresult = result_lab\n\n# Save result state\n\n# import sys\n# orig_stdout = sys.stdout\n# with open('forward_protocol_input0plusi1_switch5050.txt', 'w') as f:\n# sys.stdout = f\n# print(result)\n# sys.stdout = original_stdout\nprint(result)\n\nresult_dict = dict()\n\nresult_dict.update({'|1>|0+1>':result})\n\nresult = result_dict['|0+i1>|0+1>']\n\n# Plot evolution results\n\n# +\nsaveplot = False\n\nplt.figure(figsize=(10,6))\nif saveplot: plt.style.use('dark_background')\n\n# states for 1 input\n# plot_states = ['eggg', 'gfgg', 'ggeg', 'eegg', 'ggge', 'geeg', 'gege', 'gggg', 'gegg']\nplot_states = ['eggg', 'gfgg', 'ggeg', 'eegg', 'ggge', 'geeg', 'gege', 'gggg', 'gegg', 'efgg'] #, 'ehgg', 'ghgg']\nprob_states = dict()\nfor state in plot_states:\n psi = qram.state(state)\n prob_states.update({state:[np.abs(psi.overlap(result[t]))**2 for t in range(len(times))]})\n\nfor state in plot_states:\n plt.plot(times, prob_states[state], label=rf'$|{state}\\rangle_D$')\n\nplt.legend(fontsize=10, ncol=2)\nplt.ylim(0, 1)\n# plt.xlim(750, 1000)\nplt.tick_params(labelsize=14)\nplt.xlabel('Time (ns)', fontsize=14)\nplt.ylabel('Probability', fontsize=14)\n# plt.title(r'$\\psi_0=|$'+psi0_name+r'$\\rangle$')\n# plt.title('QRAM state evolution in memory access operation')\nplt.grid(linewidth=0.3)\n\nif saveplot:\n plot_filename = 'qram_protocol_simulated.png'\n plt.savefig(plot_filename, format='png', bbox_inches='tight', transparent = True)\n print('Saved', plot_filename)\n\nplt.show()\n# -\n\n# Get non zero levels\n\n# +\nmax_prob = 0.001\n\nT = times[-1] # ns\n\nsum_psi = 0\nT = np.argmin(np.abs(times-T))\nprobs = dict()\nprint(f\"Non-zero levels to {max_prob*100}% error:\")\nfor i1 in range(cutoffs[0]):\n for i2 in range(cutoffs[1]):\n for i3 in range(cutoffs[2]):\n for i4 in range(cutoffs[3]):\n prob = np.abs(qram.state([i1, i2, i3, i4]).overlap(result[T]))**2\n if prob > max_prob:\n probs.update({qram.level_nums_to_name([i1, i2, i3, i4]):prob})\n sum_psi += prob\nprobs = sorted(probs.items(), key=lambda item:-item[1])\nfor level, prob in probs:\n print(level, '(%):', prob*100)\nprint('Sum probabilities (%):', sum_psi*100)\n\n# +\n# ket_target = qram.state('ggeg')\nket_target = (qram.state('gegg') + qram.state('gggg')).unit()\nqram.fidelity(qram.state('ggeg'), result[-1])\nqram.fidelity(qram.state('gege'), result[-1])\n\nfidelities = [qram.fidelity(ket_target, result[t]) for t in range(len(times))]\nprint(f'Max fidelity [%]: {1e2*max(fidelities)}')\nprint(f'Final fidelity [%]: {1e2*fidelities[-1]}')\n\nplt.figure(figsize=(9.7,3))\nplt.plot(times, fidelities)\n\n# plt.legend(fontsize=16, ncol=2)\nplt.ylim(0, 1)\n# plt.xlim(750, 1000)\nplt.tick_params(labelsize=14)\nplt.xlabel('Time (ns)', fontsize=16)\nplt.ylabel('Fidelity', fontsize=16)\n# plt.title(r'$\\psi_0=|$'+psi0_name+r'$\\rangle$')\n# plt.title('QRAM state evolution in memory access operation')\nplt.grid(linewidth=0.3)\nplt.show()\n# -\n\n# ## Truncate result so it's compatible with 2q tomography\n\n# Get ideal rho\n\npsi0 = '(g+e)(g+ie)gg'\nresult = [qt.Qobj(ctrl_result.output[psi0]['value'][t], dims = [[3, 3, 3, 3], [1, 1, 1, 1]], shape = (81, 1)) for t in range(len(ctrl_result.output[psi0]['value']))]\n\n# +\npsiZ = [qt.basis(2,0), qt.basis(2,1)]\npsi00 = qt.tensor(psiZ[0], psiZ[0])\npsi01 = qt.tensor(psiZ[0], psiZ[1])\npsi10 = qt.tensor(psiZ[1], psiZ[0])\npsi11 = qt.tensor(psiZ[1], psiZ[1])\n\nrho_ids = dict()\nrho_ids.update({'|0>|0+1>':qt.ket2dm(psi00).unit()})\nrho_ids.update({'|1>|0+1>':(qt.ket2dm(psi10) + qt.ket2dm(psi01)).unit()})\nrho_ids.update({'|0+1>|0+1>':(qt.ket2dm(psi00 + psi10) + qt.ket2dm(psi00 + psi01)).unit()})\nrho_ids.update({'|0+i1>|0+1>':(qt.ket2dm(psi00 + 1j*psi10) + qt.ket2dm(psi00 + 1j*psi01)).unit()})\n\nrho_id = rho_ids['|0+1>|0+1>']\n\n# rho_id = qt.ket2dm(qt.tensor(psiZ[0]+psiZ[1], psiZ[0]+psiZ[1])).unit()\nrho_id = qt.ket2dm(psi10 + psi11).unit()\n# rho_id = qt.ket2dm(psi00 - 1j*psi01 + psi10 - 1j*psi11).unit()\n# rho_id = qt.ket2dm(psi11).unit()\n# -\n\n# Unrotate when solving in the rotating frame of wd\n\nesys_rot_wd = qram.H_rot(wd=wd).eigenstates()\nevals, evecs = esys_rot_wd\ndef unrotate(result, t):\n # return result\n result_rot = 0*result\n evals, evecs = esys_rot_wd\n for eval, evec in zip(evals, evecs):\n # |a> = sum_i(|biXbi|a>), a.overlap(b) = \n evec_flat = evec.full().flatten()\n overlap = np.sum(np.conj(evec_flat) * result.full().flatten())\n # print(eval)\n result_rot += np.exp(1j*eval*t) * overlap * evec\n return result_rot\nresult = [unrotate(result_lab[-1], times[-1])]\n\n# Unrotate when solving in the lab frame\n\n# result = qram.evolve_unrotate(times=times, result=result_lab)\nresult = qram.evolve_unrotate(times=[times[-1]], result=[result_lab[-1]])\n\n# Get 2Q partial trace density matrix\n\n# +\n# print(result[-1].dims)\n# tomo_qubits = [0, 1]\n# tomo_qubits = [2, 3]\n# tomo_qubits = [1, 2]\ntomo_qubits = [1, 3]\nresult2q = qt.ptrace(result[-1].unit(), tomo_qubits)\n# result2q = qt.ptrace(psi0, tomo_qubits)\norig_dims = result2q.dims[0]\n# result2q = qt.ptrace(result.unit(), tomo_qubits)\n# print('orig dims', orig_dims)\n# rho_result2q = result2q\nprint(result2q)\n\nstates_inds = [i*orig_dims[1]+ j for i in range(2) for j in range(2)]\n# print('extract state indices', states_inds)\nrho_result2q = result2q.extract_states(states_inds, normalize=True)\n\n\nid2q = qt.tensor(qt.qeye(2), qt.qeye(2))\nrho_result2q = qt.Qobj(rho_result2q , dims=id2q.dims, shape=id2q.shape).unit()\nprint(rho_result2q)\n\nshow_plot_rho_2d(rho_sim=rho_result2q.full(), rho_id=rho_id.full(), title=f'Simulated tomo on Q{tomo_qubits[0]}, Q{tomo_qubits[1]}', cmax=0.5) #, savetitle='0_0+1_simulated_flat.png') #, cmax=1.0)\n\nfid = qt.fidelity(rho_result2q, rho_id)**2 # qutip uses N&C fidelity which is \"sqrt fidelity\"\npurity_sim = np.real(np.trace(rho_result2q.full() @ rho_result2q.full()))\npurity_id = np.real(np.trace(rho_id.full() @ rho_id.full()))\nprint(f'Fidelity: {fid}')\nprint(f'Purity (sim): {purity_sim}')\nprint(f'Purity (ideal): {purity_id}')\n\n\n# -\n\n# Define virtual Z gate optimization \n\n# +\ndef z_gate_2q(phi1, phi2):\n return qt.tensor(qt.qip.operations.gates.rz(phi1), qt.qip.operations.gates.rz(phi2)) \n\n# The simulation density matrix from MLE may be offset from the ideal density matrix by a Z gate - due to different pulse times, ac stark shifts, etc. Rotate rho_rot to best match rho_target\ndef opt_virtualZ_MLE(rho0, rho_target, nphi=100, phi_mins=[0]*2, phi_maxs=[2*np.pi]*2):\n phis1 = np.linspace(phi_mins[0], phi_maxs[0], nphi)\n phis2 = np.linspace(phi_mins[1], phi_maxs[1], nphi)\n best_fid = qt.fidelity(rho0, rho_target)**2\n all_fids = []\n best_phis = [0, 0]\n best_rho_rot = rho0\n for phi1 in tqdm(phis1):\n for phi2 in phis2:\n z_phi12 = z_gate_2q(phi1, phi2)\n rho_rot = (z_phi12*rho0*z_phi12.dag()).unit()\n fid = qt.fidelity(rho_rot, rho_target)**2\n all_fids.append(fid)\n # print(fid)\n if fid > best_fid:\n best_fid = fid\n best_phis = [phi1, phi2]\n best_rho_rot = rho_rot\n print(f'Improved fidelity by (%) {(best_fid - qt.fidelity(rho0, rho_target)**2)*100}')\n all_fids = np.array(all_fids)\n all_fids = np.reshape(all_fids, (nphi, nphi))\n return best_rho_rot, best_phis, best_fid, all_fids\n\n\n# -\n\n# Optimize over virtual Z gates\n\nrho_result2q = qt.Qobj(inpt=np.array( # |1>|0+1> input, forward simulation smaller amps, averaged pi pulses, q2/q3\n[[ 0.592+0.j , -0.008-0.172j, -0.201+0.033j, -0.011+0.014j],\n [-0.008+0.172j, 0.285+0.j , -0.045-0.005j, -0.017-0.017j],\n [-0.201-0.033j, -0.045+0.005j, 0.094+0.j , -0.008+0.005j],\n [-0.011-0.014j, -0.017+0.017j, -0.008-0.005j, 0.028+0.j ]]),\n dims=rho_id.dims, shape=rho_id.shape)\n\n# +\nnphi_round1 = 25\nnphi_round2 = 25\n\nrho_rot, best_phis, best_fid, all_fids = opt_virtualZ_MLE(qt.Qobj(rho_result2q, dims=rho_id.dims), rho_id, nphi=nphi_round1)\n\nfid_ZZ_rot = best_fid\nprint(f'Fidelity (after rotation round 1): {fid_ZZ_rot}')\nprint(f'Best rotation round 1: {best_phis}')\nshow_plot_rho_2d(rho_rot, rho_id, title='MLE with ZZ Correction, Phase Optimized Round 1') #, cmax=1.0)\n\nphis = np.linspace(0, 2*np.pi, nphi_round1)\nplt.figure(figsize=(5,5))\nplt.pcolormesh(phis*180/np.pi, phis*180/np.pi, all_fids, cmap='viridis', shading='auto')\nplt.xlabel(\"phi 2 [deg]\")\nplt.ylabel(\"phi 1 [deg]\")\nplt.colorbar(label='Fidelity')\nplt.show()\n\nphi_mins = np.array(best_phis)-2*np.pi/nphi_round1\nphi_maxs = np.array(best_phis)+2*np.pi/nphi_round1\nrho_rot, best_phis, best_fid, all_fids = opt_virtualZ_MLE(qt.Qobj(rho_result2q, dims=rho_id.dims), rho_id, nphi=nphi_round2, phi_mins=phi_mins, phi_maxs=phi_maxs)\nfid_ZZ_rot = best_fid\nprint(np.around(rho_rot, decimals=3))\nprint(f'Fidelity (after rotation round 2): {fid_ZZ_rot}')\nprint(f'Best rotation round 2: {best_phis}')\n\nphis1 = np.linspace(phi_mins[0], phi_maxs[0], nphi_round2)\nphis2 = np.linspace(phi_mins[1], phi_maxs[1], nphi_round2)\nplt.figure(figsize=(5,5))\nplt.pcolormesh(phis1*180/np.pi, phis2*180/np.pi, all_fids, cmap='viridis', shading='auto')\nplt.xlabel(\"phi 2 [deg]\")\nplt.ylabel(\"phi 1 [deg]\")\nplt.colorbar(label='Fidelity')\nplt.show()\n\nshow_plot_rho_2d(rho_rot, rho_id, title='MLE with ZZ Correction, Phase Optimized Round 2', cmax=None, savetitle='0+1_0+1_simulated_flat.png')\nshow_plot_rho_3d(rho_sim=rho_rot.full(), rho_id=rho_id.full(), title=f'Simulated tomo on Q{tomo_qubits[0]}, Q{tomo_qubits[1]}', width=0.75, elev=30, azim=-20) #, savetitle='0+1_0+1_simulated.png')\n# -\n\nz_phi12 = z_gate_2q(2.4609142453120043, 3.7699111843077517)\nrho_rot = (z_phi12*rho_result2q*z_phi12.dag()).unit() \nfid = qt.fidelity(rho_rot, rho_id)**2\nshow_plot_rho_2d(rho_rot, rho_id, title=f'MLE with ZZ Correction, Phase Optimized, Fidelity {100*fid:.3}%', cmax=None, savetitle='0+i1_0+1_simulated_flat.png')\nshow_plot_rho_3d(rho_sim=rho_rot.full(), rho_id=rho_id.full(), title=f'Simulated tomo on Q{tomo_qubits[0]}, Q{tomo_qubits[1]}', width=0.75, elev=30, azim=-20) #, savetitle='0+1_0+1_simulated.png')\n\nprint('want', qram.get_base_wd('eggg', 'gfgg')/2/np.pi)\nprint('want', qram.get_base_wd('eegg', 'eggg')/2/np.pi)\n# print('want', qram.get_wd('eggg', 'gfgg', 0.10, verbose=False)/2/np.pi)\n# print('want', qram.get_wd('eegg', 'gfgg', 0.10, verbose=False)/2/np.pi)\n# print('want', qram.get_wd('ggge', 'gege', 0.05, verbose=False)/2/np.pi)\n# print('resonant to', qram.get_wd('ggeg', 'geeg', 0.05)/2/np.pi)\n# print('2 photon transition to', qram.get_base_wd('eggg', 'efgg')/2/np.pi)\n\n# ## Simulation iteration things\n\n# Iterate over pulse detuning\n\n# (adiabatic pulse)\n\n# +\nwd_span = 0.060*2*np.pi # GHz\nnpts = 100\n\nwd = qram.get_base_wd('gggg', 'gegg')\nprint(wd/2/np.pi, (wd-wd_span/2)/2/np.pi, (wd+wd_span/2)/2/np.pi)\nwd_sweep = np.linspace(wd-wd_span/2, wd+wd_span/2, npts)\npsi0 = (qram.state('gggg') + qram.state('gegg')).unit() # QRAM start |0>|0+1>\ngegg = qram.state('gegg')\neegg = qram.state('eegg')\ngeeg = qram.state('geeg')\ngege = qram.state('gege')\nprobs_q1e = []\nfor wd in tqdm(wd_sweep):\n seq = PulseSequence(start_time=0)\n qram.add_precise_pi_pulse(seq, 'gggg', 'gegg', amp=0.015, mu=6, beta=4, drive_qubit=1, type='adiabatic', phase=0, t_pulse=120*4, wd=wd)\n times = np.linspace(0, sum(seq.get_pulse_lengths()), 30)\n result = qram.evolve(psi0, seq, times, c_ops=None, nsteps=50000, use_str_solve=False, progress=False)[-1]\n prob_q1e = np.abs(gegg.overlap(result))**2 + np.abs(eegg.overlap(result))**2 + np.abs(geeg.overlap(result))**2 + np.abs(gege.overlap(result))**2\n probs_q1e.append(prob_q1e)\nplt.plot(wd_sweep/2/np.pi, probs_q1e)\nplt.show()\n# -\n\n# (IQ pulse)\n\nwd = qram.get_base_wd('gggg', 'gegg')\ndetunings = np.linspace(0, 5e-3, num=25)\ngggg = qram.state('gggg')\ngegg = qram.state('gegg')\npsi0 = (gggg + gegg).unit()\nphases = []\nfor idet, detune in enumerate(tqdm(detunings)):\n seq = PulseSequence(start_time=0)\n seq.pulse_IQ(wd=wd + 2*np.pi*detune, amp=1, pulse_levels=('gggg', 'gegg'), I_values=controls[1], Q_values=-controls[0], times=control_times, drive_qubit=1, t_start=0, phase=0)\n times = np.linspace(0, sum(seq.get_pulse_lengths()), 50)\n result = qram.evolve(psi0, seq, times, c_ops=None, nsteps=20000, use_str_solve=False, progress=False)\n psif = result[-1]\n phase = psif.overlap(gegg) / psif.overlap(gggg)\n phase /= abs(phase)\n try: phase = np.arctan(np.imag(phase) / np.real(phase))\n except ZeroDivisionError: phase = np.pi/2\n if idet == 0:\n phase0 = phase\n print('phase 0:', phase0)\n phase -= phase0\n phases.append(phase)\n\nplt.plot(detunings*1e3, np.array(phases)/2/np.pi*180, 'o')\nplt.ylabel('Phase (deg)')\nplt.xlabel('Detuning (MHz)')\nplt.show()\n\n# Iterate over pulse amplitude\n\n# +\nwd = qram.get_base_wd('gggg', 'gegg')\nIQscale = max(np.max(np.abs(controls_q[0])), np.max(np.abs(controls_q[1])))\namps = np.linspace(0, 2*IQscale, num=100)\ngggg = qram.state('gggg')\ngegg = qram.state('gegg')\n# psi0 = (gggg + gegg).unit()\npsi0 = gggg\nplot_states = ['eggg', 'gfgg', 'ggeg', 'eegg', 'ggge', 'geeg', 'gege', 'gggg', 'gegg', 'efgg'] #, 'ehgg', 'ghgg']\nresults_amps = []\nfor iamp, amp in enumerate(tqdm(amps)):\n seq = PulseSequence(start_time=0)\n seq.pulse_IQ(wd=wd, amp=amp, pulse_levels=('gggg', 'gegg'), I_values=controls[1]/IQscale, Q_values=-controls[0]/IQscale, times=control_times, drive_qubit=1, t_start=0, phase=0)\n # times = np.linspace(control_times[0], control_times[-1], 50)\n times = control_times\n result = qt.mesolve(qram.H_solver_rot_wd(seq=seq, wframe=qram.get_base_wd('gggg', 'gegg')), psi0, times, progress_bar=None, options=qt.Options(nsteps=1000)).states\n results_amps.append(result[-1])\n\nprob_states = dict()\nfor state in plot_states:\n psi = qram.state(state)\n prob_states.update({state:[np.abs(psi.overlap(results_amps[i_amp]))**2 for i_amp in range(len(amps))]})\n\nfor state in plot_states:\n plt.plot(amps*1e3, prob_states[state], label=rf'$|{state}\\rangle_D$')\n\nplt.legend(fontsize=10, ncol=2)\nplt.ylim(0, 1)\n# plt.xlim(750, 1000)\nplt.tick_params(labelsize=14)\nplt.xlabel('Amps (MHz)', fontsize=14)\nplt.ylabel('Probability', fontsize=14)\n# plt.title(r'$\\psi_0=|$'+psi0_name+r'$\\rangle$')\n# plt.title('QRAM state evolution in memory access operation')\nplt.grid(linewidth=0.3)\n# -\n\n\n\n\n","repo_name":"conniemiao/qutip_sims","sub_path":"4transmon_fixed_freq_swap.ipynb","file_name":"4transmon_fixed_freq_swap.ipynb","file_ext":"py","file_size_in_byte":45691,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"15920566362","text":"# # Data Cleaning for houses sold\n\n# +\nimport pandas as pd\n\nsold_data = pd.read_csv('housesSold.csv')\nsold_data.drop(columns = ['Unnamed: 0'], inplace = True)\n\nsold_data['Price'] = sold_data['Price'].str.replace('$','')\nsold_data['Price'] = sold_data['Price'].str.replace(',','')\nsold_data['Square Ft'] = sold_data['Square Ft'].str.replace(',', '')\nsold_data['Lot Size'] = sold_data['Lot Size'].str.replace(' Sq. Ft.','')\nsold_data['Lot Size'] = sold_data['Lot Size'].str.replace(',','')\nsold_data.drop(sold_data[sold_data['Type'] != 'Single Family Residential'].index, inplace = True)\n\n# +\n#getting rid of missing value entries\n\ndf_filtered = sold_data[sold_data['Lot Size'] != '—']\ndf_filtered = df_filtered[df_filtered['Stories'] != '—']\ndf_filtered = df_filtered[df_filtered['Square Ft'] != '—']\ndf_filtered = df_filtered[df_filtered['Beds'] != '—']\n\ndf_filtered.head()\n\n\n# -\n\n#some listings are in acres so we need to standardize\ndef standardize_lot(string):\n if 'Acres' in string:\n output = string[:len(string)-6]\n output = float(output)\n output *= 43560\n output = int(output)\n else:\n output = int(string)\n return output\n\n\n# +\ndf_filtered['Lot Size'] = df_filtered['Lot Size'].apply(standardize_lot)\n\ndf_filtered['Price'] = df_filtered['Price'].astype(float)\ndf_filtered['Beds'] = df_filtered['Beds'].astype(float)\ndf_filtered['Baths'] = df_filtered['Baths'].astype(float)\ndf_filtered['Year Built'] = df_filtered['Year Built'].astype(float)\ndf_filtered['Square Ft'] = df_filtered['Square Ft'].astype(float)\ndf_filtered['Stories'] = df_filtered['Stories'].astype(float)\n# -\n\n# # Data Cleaning for houses currently listed for sale\n\n# +\nlst_data = pd.read_csv('forSale.csv')\nlst_data.drop(columns = ['Unnamed: 0'], inplace = True)\n\nlst_data['Price'] = lst_data['Price'].str.replace('$','')\nlst_data['Price'] = lst_data['Price'].str.replace(',','')\nlst_data['Square Ft'] = lst_data['Square Ft'].str.replace(',', '')\nlst_data['Lot Size'] = lst_data['Lot Size'].str.replace(' Sq. Ft.','')\nlst_data['Lot Size'] = lst_data['Lot Size'].str.replace(',','')\nlst_data.drop(lst_data[lst_data['Type'] != 'Single Family Residential'].index, inplace = True)\n# -\n\nfor_sale = lst_data[lst_data['Lot Size'] != '—']\nfor_sale = for_sale[for_sale['Stories'] != '—']\nfor_sale = for_sale[for_sale['Square Ft'] != '—']\nfor_sale = for_sale[for_sale['Beds'] != '—']\n\n# +\nfor_sale['Lot Size'] = for_sale['Lot Size'].apply(standardize_lot)\n\nfor_sale['Price'] = for_sale['Price'].astype(float)\nfor_sale['Beds'] = for_sale['Beds'].astype(float)\nfor_sale['Baths'] = for_sale['Baths'].astype(float)\nfor_sale['Year Built'] = for_sale['Year Built'].astype(float)\nfor_sale['Square Ft'] = for_sale['Square Ft'].astype(float)\nfor_sale['Stories'] = for_sale['Stories'].astype(float)\n# -\n\nfor_sale.describe\n\n# # Data Analysis\n\nimport matplotlib.pyplot as plt\n\n# +\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\n\n#use these variables to try and predict price\npredictors = df_filtered[['Square Ft', 'Beds', 'Baths', 'Year Built', 'Lot Size', 'Stories']]\ntarget = df_filtered[['Price']]\n# -\n\n#split our data with 40% reserved for testing model\nX_train, X_test, y_train, y_test = train_test_split(predictors, target, test_size = .40, random_state = 21)\n\n#create linear regression model with training data\nlr = LinearRegression()\nlr.fit(X_train, y_train)\n\n# +\ny_pred = lr.predict(X_test) #use model to predict on testing set\n\npredicted_df = pd.DataFrame(y_test) #price listings of actual prices sold\npredicted_df['Predicted'] = y_pred #prices that we predicted\n\npredicted_df['Dif'] = (predicted_df['Price'] - predicted_df['Predicted']).astype(int) #compare difference in prices\npredicted_df['Percent'] = (predicted_df['Dif'] / predicted_df['Price']) #find percentage\npredicted_df\n\n# +\nprint(predicted_df['Percent'].sum()) #negative number means we tend to under estimate price\n\nresult = predicted_df['Percent'].abs()\nresult.sum()/result.shape[0] #our model is off on average 20%\n# -\n\nplt.scatter(predicted_df['Dif'], predicted_df['Percent'])\nplt.show()\n\n# # Analysis for houses currently listed for sale\n\nsale_predictors = for_sale[['Square Ft', 'Beds', 'Baths', 'Year Built', 'Lot Size', 'Stories']]\nsale_target = for_sale[['Price']]\nX_train_sale, X_test_sale, y_train_sale, y_test_sale = train_test_split(sale_predictors, sale_target, test_size = 46, random_state = 21) #use all data for test size\n\n# +\ny_pred_sale = lr.predict(X_test_sale) #use model to predict on testing set\n\npredicted_df_sale = pd.DataFrame(y_test_sale) #price listings of actual prices sold\npredicted_df_sale['Predicted'] = y_pred_sale #prices that we predicted\n\npredicted_df_sale['Dif'] = (predicted_df_sale['Price'] - predicted_df_sale['Predicted']).astype(int)\npredicted_df_sale['Percent'] = (predicted_df_sale['Dif'] / predicted_df_sale['Price'])\npredicted_df_sale.head()\n\n# +\nprint(predicted_df_sale['Percent'].sum()) #again we under estimate prices\n\nresult = predicted_df_sale['Percent'].abs()\navg_percent_dif = result.sum()/result.shape[0]\nprint(avg_percent_dif) #off on average around 22%, keep in mind these houses havent sold yet so our model might indicate that these houses can sell for different values\n\n# -\n\n#plot shows our under estimation of prices, could be due to inflation?\nplt.scatter(predicted_df_sale['Dif'], predicted_df_sale['Percent'])\nplt.show()\n\n","repo_name":"sminowada/Redfin-Housing-Price-Prediction","sub_path":"redfinCleaningAnalysis.ipynb","file_name":"redfinCleaningAnalysis.ipynb","file_ext":"py","file_size_in_byte":5424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"24890016367","text":"# +\n#Importing Libraries\n##Deep Learning \nfrom tensorflow.keras.layers import Activation, Convolution2D, Dropout, Conv2D,DepthwiseConv2D\nfrom tensorflow.keras.layers import AveragePooling2D, BatchNormalization\nfrom tensorflow.keras.layers import GlobalAveragePooling2D\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Flatten\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.layers import Input\nfrom tensorflow.keras.layers import MaxPooling2D\nfrom tensorflow.keras.layers import Reshape\nfrom tensorflow.keras.layers import SeparableConv2D\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.regularizers import l2\n\n## import models\nfrom cnn import mobileNet\nfrom cnn import ms_model_R\nfrom cnn import ms_model_M\n\n## Load and processing data \nimport load_and_process as lp\n# -\n\n# parameters\nbatch_size = 32\nnum_epochs = 10000\ninput_shape = (48, 48, 1)\nvalidation_split = .2\nverbose = 1\nnum_classes = 7\npatience = 50\nbase_path = 'models/'\n\n# +\n#load fer2013 data \nfaces1, emotions1 = lp.load_fer2013()\nfaces1 = lp.preprocess_input(faces1)\nx1_train, x1_test,y1_train,y1_test = train_test_split(faces1, emotions,test_size=0.2,shuffle=True)\n\n# load AfectNet data,\n#The training data and test data of the AffectNet dataset are separate, and the test set is imported here\nfaces2, emotions2 = lp.load_affectnet( dir_path =\"AffectNet\\train_set\", num_class = num_classes)\nfaces2 = lp.preprocess_input(faces2)\nx2_test = faces2\ny2_test = emotions2\n# -\n\n#View the CNN structure for the three models\n## MovblieNet model: with 3235463 parameters\nmovblie = mobileNet(num_classes, input_shape)\nmovblie.summary()\n\n## MovblieNet model: with 175303 parameters\nms_r_model = ms_model_R(num_classes, input_shape)\nms_r_model.summary()\n\n## MovblieNet model: with 175303 parameters\nms_m_model = ms_model_M(num_classes, input_shape)\nms_m_model.summary()\n\n# +\n# Import the trained models to evaluat models accuracy\n\n## import movblie model trained by fer2013 dataset\nfer_movblie = load_model('models/fer_mov.119-0.74.hdf5', compile=True)\n\n## Evaluat models by fer2013 dataset: accuracy is 74.11%\nscores = fer_movblie.evaluate(x1_test, y1_test, verbose=0)\nprint(\"%s: %.2f%%\" % (fer_movblie.metrics_names[1], scores[1]*100))\n\n# +\n## import movblie model trained by AffectNet dataset\naff_movblie = load_model('models/aff_mov.103-0.56.hdf5', compile=True)\n\n## Evaluat models by fer2013 dataset: accuracy is 56.48%\nscores = aff_movblie.evaluate(x2_test, y2_test, verbose=0)\nprint(\"%s: %.2f%%\" % (aff_movblie.metrics_names[1], scores[1]*100))\n\n# +\n## import ms_model_R model trained by fer2013 dataset\nfer_ms_R = load_model('models/fer_sm_R.123-0.73.hdf5', compile=True)\n\n## Evaluat models by fer2013 dataset: accuracy is 74.11%\nscores = fer_ms_R.evaluate(x1_test, y1_test, verbose=0)\nprint(\"%s: %.2f%%\" % (fer_ms_R.metrics_names[1], scores[1]*100))\n\n# +\n## import ms_model_R model trained by AffectNet dataset\naff_ms_R = load_model('models/aff_sm_R.120-0.56.hdf5', compile=True)\n\n## Evaluat models by fer2013 dataset\nscores = aff_ms_R.evaluate(x2_test, y2_test, verbose=0)\nprint(\"%s: %.2f%%\" % (aff_ms_R.metrics_names[1], scores[1]*100))\n\n# +\n## import ms_model_M model trained by fer2013 dataset\nfer_ms_M = load_model('models/fer_sm_M.124-0.74.hdf5', compile=True)\n\n## Evaluat models by fer2013 dataset: accuracy is 74.11%\nscores = fer_ms_M.evaluate(x1_test, y1_test, verbose=0)\nprint(\"%s: %.2f%%\" % (fer_ms_M.metrics_names[1], scores[1]*100))\n\n# +\n## import ms_model_M model trained by AffectNet dataset\naff_ms_M = load_model('models/aff_sm_M.126-0.56.hdf5', compile=True)\n\n## Evaluat models by fer2013 dataset\nscores = aff_ms_M.evaluate(x2_test, y2_test, verbose=0)\nprint(\"%s: %.2f%%\" % (aff_ms_M.metrics_names[1], scores[1]*100))\n# -\n\n\n","repo_name":"jianyuhe/Emotion-recognition-base-audio-and-face","sub_path":"src/Emotion Recognition/Models_evaluation.ipynb","file_name":"Models_evaluation.ipynb","file_ext":"py","file_size_in_byte":3763,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"39575810484","text":"# + [markdown] colab_type=\"text\" id=\"CazISR8X_HUG\"\n# # Multiple Linear Regression (다중 선형 회귀)\n# -\n\n# - In this practice, we are going to find regression model to predict *profit* of the startup company with various dependent varialbes such as R&D spend and Marketting spend.\n# - For simplicity, we will not consider *categorical value* such as 'state'.\n\n# + [markdown] colab_type=\"text\" id=\"pOyqYHTk_Q57\"\n# ## Importing the libraries\n\n# + colab={} colab_type=\"code\" id=\"T_YHJjnD_Tja\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# + [markdown] colab_type=\"text\" id=\"vgC61-ah_WIz\"\n# ## Importing the dataset\n\n# + colab={} colab_type=\"code\" id=\"UrxyEKGn_ez7\"\ndataset = pd.read_csv('50_Startups.csv')\n# -\n\ndataset # 데이터 정보확인\n\n# Sklearn's regression models expect the shape of X and y as \n#\n# - X : [number_of_data, number_of_features ]\n# - y : [number_of_data, number_of_features]\n#\n# Therefore, we need to convert dataframe's result to correct numpy object\n\ndataset.columns\n\ndataset[ ['R&D Spend', 'Administration', 'Marketing Spend'] ]\n\nX_input = dataset[ ['R&D Spend', 'Administration', 'Marketing Spend'] ] # do not use 'state'\ny_input = dataset[ 'Profit' ]\n\nX_input.values\n\ny_input\n\nX = X_input.values\ny = y_input.values\nprint(\"Shape of X : \", X.shape)\nprint(\"Shape of y : \", y.shape)\n\n# + [markdown] colab_type=\"text\" id=\"WemVnqgeA70k\"\n# ## Splitting the dataset into the Training set and Test set\n\n# + colab={} colab_type=\"code\" id=\"Kb_v_ae-A-20\"\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)\n# -\n\nX_test.shape\n\n# + [markdown] colab_type=\"text\" id=\"k-McZVsQBINc\"\n# ## Training the Multiple Linear Regression model on the Training set\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34} colab_type=\"code\" executionInfo={\"elapsed\": 757, \"status\": \"ok\", \"timestamp\": 1586353664008, \"user\": {\"displayName\": \"Hadelin de Ponteves\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GhEuXdT7eQweUmRPW8_laJuPggSK6hfvpl5a6WBaA=s64\", \"userId\": \"15047218817161520419\"}, \"user_tz\": -240} id=\"ywPjx0L1BMiD\" outputId=\"099836bc-4d85-4b4f-a488-093faf02e8cb\"\nfrom sklearn.linear_model import LinearRegression\nregressor = LinearRegression()\nregressor.fit(X_train, y_train)\n\n# + [markdown] colab_type=\"text\" id=\"xNkXL1YQBiBT\"\n# ## Predicting the Test set results\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 185} colab_type=\"code\" executionInfo={\"elapsed\": 951, \"status\": \"ok\", \"timestamp\": 1586353666678, \"user\": {\"displayName\": \"Hadelin de Ponteves\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GhEuXdT7eQweUmRPW8_laJuPggSK6hfvpl5a6WBaA=s64\", \"userId\": \"15047218817161520419\"}, \"user_tz\": -240} id=\"TQKmwvtdBkyb\" outputId=\"493436bf-a4ae-4374-ca16-0b0c25d19457\"\ny_pred = regressor.predict(X_test)\nnp.set_printoptions(precision=2)\nprint(np.concatenate((y_pred.reshape(len(y_pred),1), y_test.reshape(len(y_test),1)),1))\n# -\n\n# To check the result easily, convert the reference and the predict to dataframe.\n\ndata = { 'ref': y_test, 'pred':y_pred, 'diff':np.abs( (y_test - y_pred) ) }\ndf = pd.DataFrame(data)\ndf\n\n\n","repo_name":"KwanHoo/coding-playground","sub_path":"DeepLearning/1. regression/multiple_linear_regression.ipynb","file_name":"multiple_linear_regression.ipynb","file_ext":"py","file_size_in_byte":3195,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"35882200830","text":"# +\nimport dlib\n\nimport cv2 as cv\nimport cv2\nimport os\nimport re\nimport json\nfrom pylab import *\nfrom PIL import Image, ImageChops, ImageEnhance\nimport fn\nimport glob\nimport pandas as pd\nimport face_recognition\n# -\n\nfile = glob.glob(f'/projects/jbaldo/Deepfake/dfdc_train_part_*9/*.mp4')\n\npath = glob.glob('/projects/jbaldo/Deepfake/dfdc_train_part_*/metadata.json')\ndl=[]\nfor i in path:\n dl.append(pd.read_json(i).T)\ndf=pd.concat(dl)\ndf.head()\n\nFake=df[df['label']=='FAKE']\nReal=df[df['label']=='REAL']\nFake.drop_duplicates(subset='original', inplace=True)\ndf_clean=pd.concat([Fake,Real],axis=0)\nlen(df_clean)\n\n\ndef cap_img(file):\n video_file = file\n cap = cv2.VideoCapture(video_file)\n frames = []\n c = 0\n timeF = 60\n while(cap.isOpened()):\n ret, frame = cap.read()\n if ret==True:\n if c%timeF == 0: \n frames.append(frame)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n c+=1\n else:\n break\n cap.release()\n return frames\n\n\nfor f in file:\n name=f.split('/')[-1]\n if name in df_clean.index:\n label = df.loc[name][\"label\"]\n frame=cap_img(f)\n for n,f in enumerate(frame):\n image = cv.cvtColor(f, cv.COLOR_BGR2RGB)\n face_locations = face_recognition.face_locations(image)\n for num,face_location in enumerate(face_locations):\n top, right, bottom, left = face_location\n face_image = image[top:bottom, left:right]\n if label == 'REAL': \n cv2.imwrite(\"/projects/jbaldo/Deepfake/Images11/Real/\"+name.replace(\".mp4\",\"\")+str(n)+\".png\",cv2.resize(face_image, (128, 128)))\n elif label =='FAKE':\n cv2.imwrite(\"/projects/jbaldo/Deepfake/Images11/Fake/\"+name.replace(\".mp4\",\"\")+str(n)+\".png\",cv2.resize(face_image, (128, 128)))\n\n\n","repo_name":"DAEN690-capstone/deepfakedetection","sub_path":"Frames_Argo.ipynb","file_name":"Frames_Argo.ipynb","file_ext":"py","file_size_in_byte":1902,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"21"} +{"seq_id":"39662390667","text":"# ## Predictive Maintenance Example: Machine Learning Modeling Improvements\n# #### Supplement to 'Operationalizing Predictive Maintenance on a Distributed Network of Equipment'\n# ###### Melissa Perry\n# ###### UWEX Data Science Masters Program Capstone\n# ###### December 12, 2021\n\n# +\n# computational imports\nimport pandas as pd\nimport numpy as np\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import GridSearchCV, cross_val_score, KFold, RandomizedSearchCV\nimport xgboost as xgb\nfrom scipy.stats import uniform, randint\nfrom GPyOpt.methods import BayesianOptimization\nfrom tpot import TPOTRegressor\nfrom pprint import pprint\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.feature_selection import RFE\nfrom statsmodels.stats.outliers_influence import variance_inflation_factor as vif\nimport statsmodels.formula.api as smf\n\n# plotting imports\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set_style(\"darkgrid\")\n\n# for reading files from urls\nimport urllib.request\n# display imports\nfrom IPython.display import display, IFrame\nfrom IPython.core.display import HTML\n\n# # import notebook styling for tables and width etc.\n# response = urllib.request.urlopen('https://raw.githubusercontent.com/DataScienceUWL/DS775v2/master/ds755.css')\n# HTML(response.read().decode(\"utf-8\"));\n\n# import warnings\nimport warnings\n# -\n\n# import data from previous notebook.\nX_train = pd.read_csv('x_train.csv').iloc[: , 2:]\ny_train = pd.read_csv('y_train.csv')['RUL']\nX_test = pd.read_csv('x_test.csv').iloc[: , 2:]\ny_test = pd.read_csv('y_test.csv')['RUL']\n\n\n# +\n#bring in useful functions from previous notebook. \ndef my_regression_results(model):\n score_test = model.score(X_test,y_test)\n print('Model r-squared score from test data: {:0.4f}'.format(score_test))\n \n y_pred = model.predict(X_test)\n # import matplotlib.pyplot as plt\n plt.figure(figsize=(9,6))\n plt.plot(y_test,y_pred,'k.')\n plt.plot(y_pred, y_pred, color = 'red', label = 'x=y')\n plt.xlabel('Test Values')\n plt.ylabel('Predicted Values');\n\n # from sklearn.metrics import mean_squared_error\n mse = mean_squared_error(y_test,y_pred)\n rmse = np.sqrt(mse)\n print('Mean squared error on test data: {:0.2f}'.format(mse))\n print('Root mean squared error on test data: {:0.2f}'.format(rmse))\n\n#write a function to display results in a short list with no visuals.\ndef my_short_regression_results(model):\n score_test = model.score(X_test,y_test)\n y_pred = model.predict(X_test)\n mse = mean_squared_error(y_test,y_pred)\n rmse = np.sqrt(mse)\n return(score_test, mse, rmse)\n\n\n# -\n\n# #### Proposed Methods to Improve Model Performance\n# 1. Scale the data to symmetry for tree based models.\n# 2. Add lagged aggregates to capture degradation over time for all models. \n# 3. Use hyperparameter tuning for tree-based models. \n\n# ##### Proposal 1: Scaling the Data for the tree-based regression models.\n\n#implement standard scaling routine for train and test sets. \nscaler = StandardScaler()\nscaler = StandardScaler().fit(X_train.values)\nfeatures = scaler.transform(X_train.values)\nX_train_scaled = pd.DataFrame(features, columns = X_train.columns)\nX_train_scaled\n\n#repeat for test\nscaler = StandardScaler().fit(X_test.values)\nfeatures = scaler.transform(X_test.values)\nX_test_scaled = pd.DataFrame(features, columns = X_test.columns)\nX_test_scaled \n\n# Now attempt to redo tree based models and assess whether there is model improvement. \n\n# +\n#random forest regression model\nX_test = X_test_scaled\n\nrf_model = RandomForestRegressor(random_state=0)\nrf_model.fit(X_train_scaled,y_train)\n\nmy_regression_results(rf_model)\n# -\n\nround(rf_model.score(X_train,y_train),2)\n\n# +\n#xgboost regression model\nxgbr_model = xgb.XGBRegressor(objective ='reg:squarederror')\nxgbr_model.fit(X_train_scaled,y_train)\n\nmy_regression_results(xgbr_model)\n# -\n\nround(xgbr_model.score(X_train,y_train),2)\n\n# This treatment was ineffective in improving performance of the tree-based models. We are better off leaving the data unscaled. The random forest model shows a negative r-squared, which proves worse than having no model at all. The xgboost model performs worse than initially on the test set. We will reverse course and pull in the data as we had before to attempt the next proposal. \n\n# import data from previous notebook.\nX_train = pd.read_csv('x_train.csv').iloc[: , 2:]\nX_test = pd.read_csv('x_test.csv').iloc[: , 2:]\n\n\n# ##### Proposal 2: Add lagged aggregates to capture degradation over time for all models. \n# We will adapt learnings from existing code bases to help create efficient functions that can be used to create both rolling aggregates and lags of them in our dataset. We will experiment with both short and long term lags to help train the model to detect degradation of sensors over time. \n#\n# Sources:\n# * https://towardsdatascience.com/time-series-analysis-for-predictive-maintenance-of-turbofan-engines-1b3864991da4\n# * https://www.oreilly.com/library/view/predictive-maintenance-meets/9781491972540/\n\n#adapt function from Peter Koen's time series work to add lagged variables. \ndef add_lagged_variables(df_input, lags, columns):\n df = df_input.copy()\n for i in range(lags):\n lagged_columns = [col + '_lag_{}'.format(i+1) for col in columns]\n df[lagged_columns] = df.groupby('unit_number')[columns].shift(i+1)\n df.dropna(inplace=True)\n return df\n\n\n#write a function to generate rolling aggregate value within a particular window over a list of grouped dataframes.\ndef add_rolling_agg_variables(key, value_df, window):\n df = value_df.assign(group = key) # this pandas method returns a copy of the df, with group columns assigned the key value\n #for each col in the df, generate the aggregate, then rename the column with the aggregate name\n df = df.sort_values(by=[\"time_in_cycles\"], ascending=True).set_index([\"time_in_cycles\"])\n for c in df.columns:\n df[str(c+'_roll_median'+str(window))] = df[c].rolling(3).median()\n df.dropna(inplace=True)\n return (df)\n\n\n# +\n# define filepath to read data\ndir_path = './data/'\n\n# define column names for easy indexing\nindex_names = ['unit_number', 'time_in_cycles']\nsetting_names = ['setting_1', 'setting_2', 'setting_3']\nsensor_names = ['T2','T24','T30','T50','P2','P15','P30','Nf','Nc','epr','Ps30','phi','NRf','NRc','BPR','farB','htBleed','Nf_dmd','PCNfR_dmd','W31','W32']\ncol_names = index_names + setting_names + sensor_names\n\n# read data\ntrain = pd.read_csv((dir_path+'train_FD001.txt'), sep='\\s+', header=None, names=col_names)\ntest = pd.read_csv((dir_path+'test_FD001.txt'), sep='\\s+', header=None, names=col_names)\ny_test = pd.read_csv((dir_path+'RUL_FD001.txt'), sep='\\s+', header=None, names=['RUL'])\n\ntrain.head()\n\n\n# +\ndef add_remaining_useful_life(df):\n # Get the total number of cycles for each unit\n grouped_by_unit = df.groupby(by=\"unit_number\")\n max_cycle = grouped_by_unit[\"time_in_cycles\"].max()\n \n # Merge the max cycle back into the original frame\n result_frame = df.merge(max_cycle.to_frame(name='max_cycle'), left_on='unit_number', right_index=True)\n \n # Calculate remaining useful life for each row\n remaining_useful_life = result_frame[\"max_cycle\"] - result_frame[\"time_in_cycles\"]\n result_frame[\"RUL\"] = remaining_useful_life\n \n # drop max_cycle as it's no longer needed\n result_frame = result_frame.drop(\"max_cycle\", axis=1)\n return result_frame\n\ntrain = add_remaining_useful_life(train)\ntrain[index_names+['RUL']].head()\n\n# +\n#take the difference of variables from their demanded levels. \ntrain['Nf_diff']=train['Nf']-train['Nf_dmd']\ntrain['NRf_diff'] = train['NRf']-train['PCNfR_dmd']\ntest['Nf_diff']=test['Nf']-test['Nf_dmd']\ntest['NRf_diff'] = test['NRf']-test['PCNfR_dmd']\n\n# drop unwanted columns and split target variable from training set\ndrop_sensors = ['T2', 'P2','epr','farB','Nf_dmd','PCNfR_dmd','Nc','Nf','NRf'] # observe rationale in Predictive Maintenance EDA and Feature Engineering file, where these variables produce no additional data. \ndrop_labels = setting_names+drop_sensors # alter this version of the work to keep RUL and Unit number, as we need these to add lags and aggregates. \n\nX_train = train.drop(drop_labels, axis=1)\n#y_train = X_train.pop('RUL') #do this later following transformations.\nremaining_sensors = X_train.columns.difference(index_names+['RUL'])\n\n# Since the true RUL values for the test set are only provided for the last time cycle of each enginge, \n# the test set is subsetted to represent the same\n#X_test = test.groupby('unit_number').last().reset_index().drop(drop_labels, axis=1)\nX_test = test.drop(drop_labels, axis=1)\n\nprint(X_train.columns) # check remaining columns\n\n# +\n#prepare X_train. \n\n#apply rolling aggregates to train. \ngrouped_df=X_train.groupby(['unit_number'])\ndflist = [add_rolling_agg_variables(g, grouped_df.get_group(g),3) for g in grouped_df.groups.keys()]\nX_train = pd.concat(dflist, axis=0).reset_index()\n\n#apply lags to the aggregates in the short and long term. \nagg_columns=[col for col in X_train.columns if 'median' in col]\nX_train = add_lagged_variables(X_train,10,agg_columns)\ny_train = X_train.pop('RUL')\n\n\n#Repeat for X_test. \n\n#apply rolling aggregates to test. \ngrouped_df=X_test.groupby(['unit_number'])\ndflist = [add_rolling_agg_variables(g, grouped_df.get_group(g),3) for g in grouped_df.groups.keys()]\nX_test = pd.concat(dflist, axis=0).reset_index()\n\n#apply lags to the aggregates in the short and long term. \nagg_columns=[col for col in X_test.columns if 'median' in col]\nX_test= add_lagged_variables(X_test,10,agg_columns)\n# -\n\nX_train\n\n# +\n# #implement standard scaling routine for train and test sets. \n# scaler = StandardScaler()\n# scaler = StandardScaler().fit(X_train.values)\n# features = scaler.transform(X_train.values)\n# X_train_scaled = pd.DataFrame(features, columns = X_train.columns)\n# X_train_scaled\n\n# X_train = X_train_scaled\n# X_train.head()\n\n# +\n# #repeat for test\n# scaler = StandardScaler().fit(X_test.values)\n# features = scaler.transform(X_test.values)\n# X_test_scaled = pd.DataFrame(features, columns = X_test.columns)\n# X_test = X_test_scaled \n# X_test.head()\n\n# +\n#clean out unhelpful columns from train and test sets. \n\n#start with train\ngroup_columns=[col for col in X_train.columns if 'group' in col]\nrul_columns=[col for col in X_train.columns if 'RUL' in col]\nunit_number_columns=[col for col in X_train.columns if 'unit_number' in col]\n\ndrop_labels = group_columns+rul_columns+unit_number_columns+index_names\nX_train = X_train.drop(drop_labels,axis=1)\n\n#repeat for test\nX_test = X_test.groupby('unit_number').last().reset_index()\ngroup_columns=[col for col in X_test.columns if 'group' in col]\nunit_number_columns=[col for col in X_test.columns if 'unit_number' in col]\ndrop_labels = group_columns+unit_number_columns+index_names\nX_test = X_test.drop(drop_labels,axis=1)\n# -\n\ny_train\n\nlist(X_train.columns)\n\nlist(X_test.columns)\n\n\n\n# For this attempt we arbitrarily chose 10 lags of 3-cycle rolling medians for each of the sensor values. We anticipate this kind of transformation will add severe multicollinearity, and as a result we will scale the dataset as we did before before attempting our modeling efforts. \n\nX_test\n\n# +\n# from sklearn.linear_model import LinearRegression\nmodel_lr = LinearRegression()\nmodel_lr.fit(X_train,y_train)\n\nmy_regression_results(model_lr)\n# -\n\nround(cross_val_score(model_lr,X_train,y_train,scoring='r2', cv=5).mean(),2)\n\n# +\n# from sklearn.ensemble import RandomForestRegressor\n\nrf_model = RandomForestRegressor(random_state=0)\nrf_model.fit(X_train,y_train)\n\nmy_regression_results(rf_model)\n\n# +\n# import xgboost as xgb\n\nxgbr_model = xgb.XGBRegressor(objective ='reg:squarederror')\nxgbr_model.fit(X_train,y_train)\n\nmy_regression_results(xgbr_model)\n# -\n\n# ##### Model Results Following Changes after Proposal 2\n\nd = {'Algorithm' : ['Linear Regression', 'Random Forest Regression','XGBoost Regression' ]\n ,'Data Transformations':['Adding Lagged Aggregates','..','..']\n ,'Train R-squared':[round(model_lr.score(X_train,y_train),2),round(rf_model.score(X_train,y_train),2),round(xgbr_model.score(X_train,y_train),2)]\n ,'Test R-squared':[round(my_short_regression_results(model_lr)[0],2),round(my_short_regression_results(rf_model)[0],2),round(my_short_regression_results(xgbr_model)[0],2)]\n ,'Test Mean Squared Error':[round(my_short_regression_results(model_lr)[1],2),round(my_short_regression_results(rf_model)[1],2),round(my_short_regression_results(xgbr_model)[1],2)]\n ,'Test Root Mean Squared Error':[round(my_short_regression_results(model_lr)[2],2),round(my_short_regression_results(rf_model)[2],2),round(my_short_regression_results(xgbr_model)[2],2)]}\ndf = pd.DataFrame(data=d)\ndf\n\n# ##### Test for Multicollinearity\n\n#take a small subset of 200 rows to assess issue quickly.\nX_train_200 = X_train[:200]\n#from statsmodels.stats.outliers_influence import variance_inflation_factor as vif\nvifs = {X_train_200.columns[i]:round(vif(X_train_200.values, i), 2) for i in range(len(X_train_200.columns))}\ndisplay(vifs)\n\n# We have high multicollinearity, which is unacceptable for a multiple linear regression model, where we are shooting VIFs around ~5. We should start with fewer lags and assess which are most critical to keep in our model. \n\n# +\n# define filepath to read data\ndir_path = './data/'\n\n# define column names for easy indexing\nindex_names = ['unit_number', 'time_in_cycles']\nsetting_names = ['setting_1', 'setting_2', 'setting_3']\nsensor_names = ['T2','T24','T30','T50','P2','P15','P30','Nf','Nc','epr','Ps30','phi','NRf','NRc','BPR','farB','htBleed','Nf_dmd','PCNfR_dmd','W31','W32']\ncol_names = index_names + setting_names + sensor_names\n\n# read data\ntrain = pd.read_csv((dir_path+'train_FD001.txt'), sep='\\s+', header=None, names=col_names)\ntest = pd.read_csv((dir_path+'test_FD001.txt'), sep='\\s+', header=None, names=col_names)\ny_test = pd.read_csv((dir_path+'RUL_FD001.txt'), sep='\\s+', header=None, names=['RUL'])\n\n# add remaining useful life\ntrain = add_remaining_useful_life(train)\ntrain[index_names+['RUL']].head()\n\n#take the difference of variables from their demanded levels. \ntrain['Nf_diff']=train['Nf']-train['Nf_dmd']\ntrain['NRf_diff'] = train['NRf']-train['PCNfR_dmd']\ntest['Nf_diff']=test['Nf']-test['Nf_dmd']\ntest['NRf_diff'] = test['NRf']-test['PCNfR_dmd']\n\n# drop unwanted columns and split target variable from training set\ndrop_sensors = ['T2', 'P2','epr','farB','Nf_dmd','PCNfR_dmd','Nc','Nf','NRf'] # observe rationale in Predictive Maintenance EDA and Feature Engineering file, where these variables produce no additional data. \ndrop_labels = setting_names+drop_sensors # alter this version of the work to keep RUL and Unit number, as we need these to add lags and aggregates. \n\nX_train = train.drop(drop_labels, axis=1)\n#y_train = X_train.pop('RUL') #do this later following transformations.\nremaining_sensors = X_train.columns.difference(index_names+['RUL'])\n\n# Since the true RUL values for the test set are only provided for the last time cycle of each enginge, \n# the test set is subsetted to represent the same\n#X_test = test.groupby('unit_number').last().reset_index().drop(drop_labels, axis=1)\nX_test = test.drop(drop_labels, axis=1)\n\nprint(X_train.columns) # check remaining columns\n\n# +\n#prepare X_train. \n\n#apply rolling aggregates to train. \ngrouped_df=X_train.groupby(['unit_number'])\ndflist = [add_rolling_agg_variables(g, grouped_df.get_group(g),3) for g in grouped_df.groups.keys()]\nX_train = pd.concat(dflist, axis=0).reset_index()\n\n#apply lags to the aggregates in the short and long term. \nagg_columns=[col for col in X_train.columns if 'median' in col]\nX_train = add_lagged_variables(X_train,1,agg_columns).reset_index(drop=True)\n\ny_train = X_train.pop('RUL')\n\n#Repeat for X_test. \n\n#apply rolling aggregates to test. \ngrouped_df=X_test.groupby(['unit_number'])\ndflist = [add_rolling_agg_variables(g, grouped_df.get_group(g),3) for g in grouped_df.groups.keys()]\nX_test = pd.concat(dflist, axis=0).reset_index()\n\n#apply lags to the aggregates in the short and long term. \nagg_columns=[col for col in X_test.columns if 'median' in col]\nX_test = add_lagged_variables(X_test,1,agg_columns).reset_index(drop=True)\n\n# +\n#clean out unhelpful columns from train and test sets. \n\n#start with train\ngroup_columns=[col for col in X_train.columns if 'group' in col]\nrul_columns=[col for col in X_train.columns if 'RUL' in col]\nunit_number_columns=[col for col in X_train.columns if 'unit_number' in col]\n\ndrop_labels = group_columns+rul_columns+unit_number_columns+index_names\nX_train = X_train.drop(drop_labels,axis=1)\n\n#repeat for test\nX_test = X_test.groupby('unit_number').last().reset_index()\ngroup_columns=[col for col in X_test.columns if 'group' in col]\nunit_number_columns=[col for col in X_test.columns if 'unit_number' in col]\ndrop_labels = group_columns+unit_number_columns+index_names\nX_test = X_test.drop(drop_labels,axis=1)\n# -\n\nX_test\n\ny_train.shape\n\nimport statsmodels.api as sm\nmodel_lr_1 = sm.OLS(y_train,X_train)\nresults = model_lr_1.fit()\nprint(results.summary())\n\n#from statsmodels.stats.outliers_influence import variance_inflation_factor as vif\nvifs = {X_train.columns[i]:round(vif(X_train.values, i), 2) for i in range(len(X_train.columns))}\ndisplay(vifs)\n\n# +\n#try scaling the data\nscaler = StandardScaler()\nscaler = StandardScaler().fit(X_train.values)\nfeatures = scaler.transform(X_train.values)\nX_train = pd.DataFrame(features, columns = X_train.columns).reset_index(drop=True)\n#X_train\n\n#repeat for test\nscaler = StandardScaler().fit(X_test.values)\nfeatures = scaler.transform(X_test.values)\nX_test= pd.DataFrame(features, columns = X_test.columns).reset_index(drop=True)\nX_test.head()\n# -\n\nX_train.shape\n\ny_train = y_train.reset_index(drop=True)\n\n#import statsmodels.api as sm\nmodel_lr_1 = sm.OLS(y_train,X_train)\nresults = model_lr_1.fit()\nprint(results.summary())\n\ncormat = X_train_scaled.corr()\nround(cormat,2)\nsns.heatmap(cormat);\n\n#attempt to drop the rolling median columns since they are heavily correlated with the lags \ncols = list(range(16,30))\nx_train = X_train.drop(X_train.columns[cols],axis=1,inplace=True)\nx_test = X_test.drop(X_test.columns[cols],axis=1,inplace=True)\n\ncormat = X_train.corr()\nround(cormat,2)\nsns.heatmap(cormat);\n\n#import statsmodels.api as sm\nmodel_lr_1 = sm.OLS(y_train,X_train)\nresults = model_lr_1.fit()\nprint(results.summary())\n\n#from statsmodels.stats.outliers_influence import variance_inflation_factor as vif\nvifs = {X_train.columns[i]:round(vif(X_train.values, i), 2) for i in range(len(X_train.columns))}\ndisplay(vifs)\n\n#list variables with VIF > 5 to remove from the model:\n{k for (k,v) in vifs.items() if v > 5}\n\ncols = ['BPR_roll_median3_lag_1','NRc',\n 'NRc_roll_median3_lag_1',\n 'NRf_diff',\n 'NRf_diff_roll_median3_lag_1',\n 'Nf_diff',\n 'Nf_diff_roll_median3_lag_1',\n 'P30_roll_median3_lag_1',\n 'Ps30',\n 'Ps30_roll_median3_lag_1',\n 'T50_roll_median3_lag_1',\n 'W31_roll_median3_lag_1',\n 'W32_roll_median3_lag_1',\n 'phi',\n 'phi_roll_median3_lag_1']\nx_train = X_train.drop(cols,axis=1,inplace=True)\nx_test = X_test.drop(cols,axis=1,inplace=True)\n\nvifs = {X_train.columns[i]:round(vif(X_train.values, i), 2) for i in range(len(X_train.columns))}\ndisplay(vifs)\n\nmodel_lr_1 = sm.OLS(y_train,X_train)\nresults = model_lr_1.fit()\nprint(results.summary())\n\n# +\n#model lr again to see if we've improved over baseline since removing multicollinearity\nmodel_lr_2= LinearRegression()\nmodel_lr_2.fit(X_train,y_train)\n\nmy_regression_results(model_lr_2)\n# -\n\n# ### Multicollinearity Cleanup Results\n\nd = {'Algorithm' : ['Linear Regression' ]\n ,'Data Transformations':['Addressing Multicollinearity']\n ,'Train R-squared':[round(model_lr_2.score(X_train,y_train),2)]\n ,'Test R-squared':[round(my_short_regression_results(model_lr_2)[0],2)]\n ,'Test Mean Squared Error':[round(my_short_regression_results(model_lr_2)[1],2)]\n ,'Test Root Mean Squared Error':[round(my_short_regression_results(model_lr_2)[2],2)]}\ndf = pd.DataFrame(data=d)\ndf\n\n# ##### Proposal 3: Tune the Hyperparameters on the Tree-based Models\n\n# Due to the fact we now have a large number of variables to contend with, use a Random Search CV process to tune hyperparameters of both the random forest regression and xgboost models. I'll use the following sources as a guide to implementation:\n# * Prescriptive Analytics, Project 2 Hyperparameter Optimization Project P\n# * https://towardsdatascience.com/hyperparameter-tuning-the-random-forest-in-python-using-scikit-learn-28d2aa77dd74\n# * https://www.kaggle.com/jnikhilsai/cross-validation-with-linear-regression\n#\n# Our most useful models have been from the tree-based models run on the dataset with the 10 lags and rolling aggregates. What would happen if we tuned the hyperparmeters? For a direct comparison to past approaches, we must stay consistent with the same X train and X test transformations we had last time we trained these models. \n#\n\nX_train.head()\n\nX_test.head()\n\n#from pprint import pprint\npprint(rf_model.get_params())\n\n# +\n# RandomizedSearchCV for Random Forest Model\n\n# Number of trees in random forest\nn_estimators = [int(x) for x in np.linspace(start = 200, stop = 2000, num = 10)]\n# Number of features to consider at every split\nmax_features = ['auto', 'sqrt']\n# Maximum number of levels in tree\nmax_depth = [int(x) for x in np.linspace(10, 110, num = 11)]\nmax_depth.append(None)\n# Minimum number of samples required to split a node\nmin_samples_split = [2, 5, 10]\n# Minimum number of samples required at each leaf node\nmin_samples_leaf = [1, 2, 4]\n# Method of selecting samples for training each tree\nbootstrap = [True, False]\n\nparams = {\n 'n_estimators': n_estimators,\n 'max_features': max_features,\n 'max_depth': max_depth,\n 'min_samples_split': min_samples_split,\n 'min_samples_leaf': min_samples_leaf,\n 'bootstrap': bootstrap}\n\n\nrandom_search_rf = RandomizedSearchCV(\n rf_model,\n param_distributions=params,\n random_state=8675309,\n n_iter=10,\n cv=5,\n verbose=20,\n n_jobs=1,\n return_train_score=True)\n\nrandom_search_rf.fit(X_train, y_train)\n# -\n\nrandom_search_rf.best_params_\n\nmy_regression_results(random_search_rf)\n\n#from pprint import pprint\npprint(xgbr_model.get_xgb_params())\n\n# +\n# RandomizedSearchCV for XGBoost Re\n\nparams = {\n \"learning_rate\": [0.001, 0.01, 0.1, 0.5, 1.],\n \"max_depth\": randint(1, 10),\n \"n_estimators\": randint(10, 150),\n \"subsample\": uniform(0.05, 0.95), # so uniform on [.05,.05+.95] = [.05,1.]\n \"min_child_weight\": randint(1, 20),\n \"reg_alpha\": uniform(0, 5),\n \"reg_lambda\": uniform(0, 5)\n}\n\nrandom_search_xgb = RandomizedSearchCV(\n xgbr_model,\n param_distributions=params,\n random_state=8675309,\n n_iter=25,\n cv=5,\n verbose=5,\n n_jobs=1,\n return_train_score=True)\n\nrandom_search_xgb.fit(X_train, y_train)\n# -\n\nrandom_search_xgb.best_params_\n\nmy_regression_results(random_search_xgb)\n\n# +\nxgbr_model_optimal = xgb.XGBRegressor(\n learning_rate= 0.1,\n max_depth = 2,\n min_child_weight = 2,\n n_estimators= 115,\n reg_alpha= 1.1298003538030903,\n reg_lambda= 4.607840214514044,\n subsample= 0.7428130082444454,\n objective ='reg:squarederror')\n\nxgbr_model_optimal.fit(X_train,y_train)\n\nmy_regression_results(xgbr_model_optimal)\n# -\n\nxgb.plot_importance(xgbr_model_optimal._Booster,max_num_features=10)\nplt.title(\"xgboost.plot_importance(model)\")\nplt.savefig('model_feature_importance.png')\nplt.show()\n\n\n# +\nfrom xgboost import plot_tree\n\nplot_tree(xgbr_model_optimal._Booster)\n\n# +\n#Use grid search for our Xgboost regression model \n# define the grid\nparams = {\n \"learning_rate\": [0.01, 0.1],\n \"max_depth\": [2, 4, 6],\n \"n_estimators\": [10, 100,150],\n \"subsample\": [0.8, 1],\n \"min_child_weight\": [1, 3],\n \"reg_lambda\": [1, 3],\n \"reg_alpha\": [1, 3]\n}\n\n# setup the grid search\ngrid_search_xgb = GridSearchCV(xgbr_model,\n param_grid=params,\n cv=5,\n verbose=1,\n n_jobs=1,\n return_train_score=True)\n\ngrid_search_xgb.fit(X_train, y_train)\n\n# -\n\ngrid_search_xgb.best_params_\n\nmy_regression_results(grid_search_xgb)\n\n# #### Results following Tree Hyperparameter Tuning\n# Our most useful models have been from the tree-based models run on the dataset with the 10 lags and rolling aggregates. What would happen if we tuned the hyperparmeters? For a direct comparison to past approaches, we must stay consistent with the same X train and X test transformations we had last time we trained these models. \n\nd = {'Algorithm' : ['XGBoost Regression']\n ,'Data Transformations':['Random Search Hyperparameter Tuning']\n ,'Train R-squared':[round(random_search_xgb.score(X_train,y_train),2)]\n ,'Test R-squared':[round(my_short_regression_results(random_search_xgb)[0],2)]\n ,'Test Mean Squared Error':[round(my_short_regression_results(random_search_xgb)[1],2)]\n ,'Test Root Mean Squared Error':[round(my_short_regression_results(random_search_xgb)[2],2)]}\ndf = pd.DataFrame(data=d)\ndf\n","repo_name":"melperry123/Predictive-Maintenance-Example","sub_path":"Predictive_Maintenance_Machine_Learning-Improvements.ipynb","file_name":"Predictive_Maintenance_Machine_Learning-Improvements.ipynb","file_ext":"py","file_size_in_byte":25273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"21"} +{"seq_id":"22730373964","text":"# # Homework Assignment 8 - Evan Callaghan\n#\n# ### 1. Why is feature scaling important for the k-means algorithm?\n#\n# #### Feature scaling is important for the k-means algorithm because it relies on the Euclidean distance. Without scaling, the distance would be dominated by variables with a large range of values. Therefore, variables must be on the same scale to ensure that all features recieve equal weighting in the clustering analysis. \n#\n# ### 2. How can clustering be used to improve the performance of a linear model?\n#\n# #### E. Clustering can be used for: creating different models for different cluster groups, creating an input feature for cluster ids as dummy variables, creating an input feature for cluster centroids as a continuous variable, and creating an input feature for cluster size as a continuous variable.\n#\n# ### 3. What are the risks of initial random cluster centroids assignments in k-means?\n#\n# #### Randomly assigning cluster centroids risks a slow convergence speed and a suboptimal solution. For that reason, k-means++ offers an improved method for cluster centroid selection that is is proven to increase the effectiveness of the model. \n\n# +\nimport boto3\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.cluster import KMeans\nfrom sklearn.metrics import calinski_harabasz_score, davies_bouldin_score, silhouette_score\n\n## Defining the bucket\ns3 = boto3.resource('s3')\nbucket_name = 'data-445-bucket-callaghan'\nbucket = s3.Bucket(bucket_name)\n\n## Defining the csv file\nfile_key = 'Mall_Customers.csv'\n\nbucket_object = bucket.Object(file_key)\nfile_object = bucket_object.get()\nfile_content_stream = file_object.get('Body')\n\n\n## 4. a) Using the pandas library to read the csv data file and create a data-frame called customers\n\ncustomers = pd.read_csv(file_content_stream)\n\n## Removing the observations with missing values\ncustomers = customers.dropna()\n\ncustomers.head()\n\n# +\n## b) Using the appropriate Python commands to put Gender, Age and Annual Income (k$) in the same scale\n\ncustomers['Gender'] = np.where(customers['Gender'] == 'Female', 0, 1)\n\nscaler = MinMaxScaler(feature_range = (0,1))\n\ncustomers[['Age_0_1', 'Annual_Income_0_1']] = scaler.fit_transform(customers[['Age', 'Annual Income (k$)']])\n\n# +\n## c) Estimating the number of clusters for this dataset using the Calinski-Harabasz, Davies-Bouldin, \n## and Silhouette scores\n\n## Defining the input data\nX = customers[['Gender', 'Age_0_1', 'Annual_Income_0_1']]\n\n## Defining empty lists to store results\nch_score = []\ndb_score = []\nsil_score = []\n\n## Defining list of clusters to consider\nnum_clusters = [2, 3, 4, 5, 6, 7, 8, 9, 10]\n\nfor i in num_clusters:\n \n ## Fitting the k-means model\n kmeans_md = KMeans(n_clusters = i, init = 'k-means++', n_init = 20).fit(X)\n \n ## Computing and storing the Ch score\n ch_score.append(calinski_harabasz_score(X, kmeans_md.labels_))\n \n ## Computing and storing the DB score\n db_score.append(davies_bouldin_score(X, kmeans_md.labels_))\n \n ## Computing and storing the Silhouette score\n sil_score.append(silhouette_score(X, kmeans_md.labels_))\n\n## Visualizing the Calinski-Harabasz, Davies-Bouldin, and Silhouette scores.\nfig, axs = plt.subplots(1, 3, figsize = (15, 6))\naxs[0].plot(num_clusters, ch_score)\naxs[0].set_xlabel('Number of Clusters')\naxs[0].set_ylabel('CH-Score')\naxs[0].grid()\n\naxs[1].plot(num_clusters, db_score)\naxs[1].set_xlabel('Number of Clusters')\naxs[1].set_ylabel('DB-Score')\naxs[1].grid()\n\naxs[2].plot(num_clusters, sil_score)\naxs[2].set_xlabel('Number of Clusters')\naxs[2].set_ylabel('Silhouette-Score')\naxs[2].grid()\n\n## The CH-Score, DB-Score, and Silhouette-Score each indicate that two clusters in the optimal number to consider.\n## Therefore, we will cluster the data into two clusters.\n\n# +\n## d) Using the results from part (c) to cluster the data into two clusters\n\n## Fitting the k-means model\nkmeans_md = KMeans(n_clusters = 2, init = 'k-means++', n_init = 20).fit(X)\n\n## Appending cluster labels to the data\ncustomers['Cluster'] = kmeans_md.labels_\n\n# +\n## e) Describing each of the clusters\n\n## Cluster 1\n\ncluster_1 = customers[customers['Cluster'] == 0]\ncluster_1.describe()\n\n## All customers in this cluster are males. The average age is around 40 years old with an average income\n## of around $62,000.\n\n# +\n## Cluster 2\n\ncluster_2 = customers[customers['Cluster'] == 1]\ncluster_2.describe()\n\n## All customers in this cluster are females. The average age is around 38 years old with an average income\n## of around $59,000. This cluster also has a spending score that is, on average, three points higher compared\n## to Cluster 1.\n\n## I think the clustering result does make sense because it perfectly split the two genders presented\n## in the data set and the two clusters have distinct differences.\n","repo_name":"Evan-Callaghan/DATA-445-Machine-Learning","sub_path":"Homework Assignments/Homework Assignment 8.ipynb","file_name":"Homework Assignment 8.ipynb","file_ext":"py","file_size_in_byte":4888,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"21"} +{"seq_id":"24183248260","text":"# # Chronic Absenteeism Rate Prediction (CARP) Model Evaluation (ME)\n#\n# ### Make preparations specific to IBM Watson Studio: import and configure project utilities, define function to download project assets\n\n# +\n# The code was removed by Watson Studio for sharing.\n# -\n\n# function to retrieve project assets \ndef download(project_file_name,project=None): \n # get the file\n print(\"Attempting to get file {}\".format(project_file_name))\n _bytes = project.get_file(project_file_name).read()\n \n # download the file\n print(\"Downloading...\")\n \n with open(project_file_name, 'wb') as f: \n f.write(bytearray(_bytes))\n print(\"Completed writing out file\")\n \n return 0\n\n\n# ### Import required modules\n\n# +\nimport numpy as np\nimport pandas as pd\n\nimport re\n\nimport pickle\n\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\n\nimport seaborn as sns\n# -\n\n# ### Download, standardize, and verify model results datasets created by CARP-NN (Neural Network) and CARP-DTE (Decision Tree Ensemble)\n\n# +\nnn_results_file_name = 'nn_results.p'\ndownload(nn_results_file_name,project)\nnn_results = pickle.load(open(nn_results_file_name,'rb'))\n\ndte_results_file_name = 'dte_results.p'\ndownload(dte_results_file_name,project)\ndte_results = pickle.load(open(dte_results_file_name,'rb'))\nprint('\\nNeural Network Results:\\t\\t', nn_results.keys(),'\\nDecision Tree Ensemble Results:\\t', dte_results.keys())\n\n### Standardize and verify Consistency of data, especially since neural network data has been scaled and then inverse scaled in CARP-DNN data\n\niterations = len(dte_results['test_scores'])\n# Should print \"True\" (2 * iterations) times\nfor i in range(iterations):\n dte_results['X_tests'][i] = dte_results['X_tests'][i].values[:,:25]\n dte_results['y_tests'][i] = dte_results['y_tests'][i].values.reshape(-1,1)\n nn_results['y_tests'][i] = nn_results['y_tests'][i].reshape(-1,1)\n print(np.allclose(dte_results['X_tests'][i],nn_results['X_tests'][i]))\n print(np.allclose(dte_results['y_tests'][i],nn_results['y_tests'][i]))\n# -\n\n# ### Compare coefficient of determination for each iteration\n\n# +\nnn_r2_scores = nn_results['test_scores']\ndte_r2_scores = dte_results['test_scores']\n\nfig, ax = plt.subplots(figsize=(12,12))\nsns.set(style=\"whitegrid\", color_codes=True, font_scale=1.5)\nax.xaxis.set_major_locator(ticker.MultipleLocator(1))\nax.xaxis.set_major_formatter(ticker.ScalarFormatter())\n\niterations = list(range(1,6))\n# data\ndf=pd.DataFrame({'x': iterations, 'nn_r2': nn_r2_scores, 'dte_r2': dte_r2_scores })\n# plot\nplt.plot( 'x','nn_r2', data=df, color = 'red', label='Neural Network', linestyle='-', marker='o')\nplt.plot( 'x','dte_r2', data=df, color = 'blue', label='Decision Tree Ensemble', linestyle='-', marker='o')\n\nplt.ylabel('R-Squared Score (Perfect Prediction = 1.0)')\nplt.xlabel('Iteration')\n\nax.set_title('Chronic Absenteeism Prediction\\nR-Squared Scores by Model Type',\n fontdict={'fontsize': '30',\n 'fontweight' : '99'})\nplt.legend()\nplt.show()\n\nplt.show()\n# -\n\n# ### Select results with median test scores from better-performing prediction to avoid outlying performances\n\n# +\n#TODO Add logic for even number of iterations: One solution would be to append negative infinity as a test score to make the median equal to an array entry. \n# This entry would be less than the actual median, and therefore a conservative selection. \n\ndte_median = np.median(dte_results['test_scores'])\n\ndte_median_tuple = np.where(dte_results['test_scores'] == dte_median)\n\nmedian_index = dte_median_tuple[0][0]\n\ndte_y_test = dte_results['y_tests'][median_index]\ndte_y_test_pred = dte_results['y_test_preds'][median_index].reshape(-1,1)\n\nnn_y_test = nn_results['y_tests'][median_index]\nnn_y_test_pred = nn_results['y_test_preds'][median_index].reshape(-1,1)\n\n# -\n\n# ### Compute and visualize residuals\n\n# +\nnn_residuals=abs(nn_y_test - nn_y_test_pred)\ndte_residuals=abs(dte_y_test - dte_y_test_pred)\nfig, ax = plt.subplots(figsize=(12,12))\nsns.set(style=\"ticks\", color_codes=True, font_scale=1.5)\nbins = range(0, 16)\nsns.distplot(nn_residuals[:,0], ax=ax,kde=False, color=\"pink\", bins=bins, label=\"Neural Network Residuals\")\nsns.distplot(dte_residuals[:,0], ax=ax, kde = False, color=\"skyblue\", bins=bins, label=\"Decision Tree Ensemble Residuals\")\n\n\nax.set_title('Chronic Absenteeism Prediction Residuals',\n fontdict={'fontsize': '30',\n 'fontweight' : '99'})\n\n_ = ax.annotate('Source: Median-performing Decision Tree Ensemble iteration\\nwith Neural Network predictions from same iteration',\n xy=(2.5, 110),\n horizontalalignment='left', verticalalignment='top',\n fontsize=16, color='#555555')\n_ = plt.xlabel('|Predicted Percentage - Ground Truth|')\n_ = plt.ylabel('Number of Test Predictions')\n_ = ax.legend()\n# -\n\n# ### Visualize and compare prediction accuracy using a scatter plot with identity and +/- 5% lines \n\n# +\nfig, ax = plt.subplots(figsize=(12,12))\nsns.set(style=\"whitegrid\", color_codes=True, font_scale=1.4)\nax.xaxis.set_major_locator(ticker.MultipleLocator(1))\n#ax.xaxis.set_major_formatter(ticker.ScalarFormatter())\nax.yaxis.set_major_locator(ticker.MultipleLocator(1))\n#ax.yaxis.set_major_formatter(ticker.ScalarFormatter())\n\n# data\n#d = {'x': dte_y_test, 'nn_pred': nn_y_test_pred, 'dte_pred': dte_y_test_pred }\n\npredictions = pd.DataFrame({'x': dte_y_test[:,0], 'nn_pred': nn_y_test_pred[:,0], 'dte_pred': dte_y_test_pred[:,0] }, index=range(len(dte_y_test))).astype(float)\n# plot\nplt.scatter( 'x','nn_pred', data=predictions, color = 'red', label='Neural Network',s=12)\nplt.scatter( 'x','dte_pred', data=predictions, color = 'blue', label='Decision Tree Ensemble', s=12)\n\nplt.plot([0,21],[0,21], ls='--', c='.4')\nplt.plot([0,21],[5,26], ls='--', c='.4')\nplt.plot([5,21],[0,16], ls='--', c='.4')\n\nplt.ylabel('Model Prediction Percentage')\nplt.xlabel('Ground Truth Percentage')\n\nax.set_title('Chronic Absenteeism Predictions\\nBy Model Type',\n fontdict={'fontsize': '30',\n 'fontweight' : '99'})\nplt.legend()\nplt.show()\n\nplt.show()\n# -\n\n\n","repo_name":"IverBand/carp","sub_path":"CARP-ME.ipynb","file_name":"CARP-ME.ipynb","file_ext":"py","file_size_in_byte":6147,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"21"} +{"seq_id":"9589584089","text":"# + [markdown] id=\"SBISmwy0Ds2l\"\n# # Advanced Machine Learning Lesson : Materials Science\n# > Advanced Machine Learning (advanced linear regression)\n# > Author: Raunak Mondal\n# - toc: true\n# - categories: []\n# - type: pbl\n# - week: 18\n\n# + [markdown] id=\"mw4xLMK52Cvy\"\n# #**Lesson: Exploring Materials Project Data and Predicting Material Properties**\n# ##**Step 1: Importing Libraries**\n# In this lesson, we'll explore materials project data and perform various data analysis tasks using Python. First, we need to import the necessary libraries to work with data, visualize it, and perform machine learning.\n\n# + id=\"8fe494ff-25f5-44ef-9723-0af63daa6196\"\nfrom mp_api.client import MPRester\nimport pandas as pd\nfrom pymatgen.core import Composition\nimport datetime\nfrom math import inf\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import cross_val_predict, cross_validate, KFold\nfrom sklearn import linear_model\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error\nimport seaborn as sns\n\n#from sklearn.model_selection import train_test_split\n#from sklearn.model_selection import cross_val_predict, cross_validate, KFold\n#from sklearn.metrics import r2_score\n#from sklearn.cluster import KMeans\n#from sklearn.discriminant_analysis import LinearDiscriminantAnalysis, QuadraticDiscriminantAnalysis\n#from sklearn.linear_model import LogisticRegression\n#from sklearn.cluster import DBSCAN\n\n# + [markdown] id=\"V5HC-1r62qGL\"\n# ##**Step 2: Accessing Materials Project Data**\n# The Materials Project is a database containing materials properties data. We'll use the MPRester library to access materials project data related to ABO3 compounds. We'll fetch properties like material_id, formula_pretty, nsites, band_gap, formation_energy_per_atom, theoretical, and energy_above_hull for all ABO3 compounds.\n\n# + id=\"8174196a-5bea-4896-9710-0230cf95c6cc\"\nmpr = MPRester(api_key=\"PT7C2S6MEfO67wSwPtB3KlVvUu7ZI166\")\n\n# + colab={\"referenced_widgets\": [\"f68dbe928b424e3a8e9984032fa77110\"]} id=\"b30a8c0f-00a4-447e-b180-0c72eab8bead\" outputId=\"e785469c-7602-4d53-9bca-a32336a476cf\"\nABO3 = mpr.summary.search(formula=\"**O3\", fields=[\"material_id\", \"formula_pretty\", \"nsites\", \"band_gap\", \"formation_energy_per_atom\", \"theoretical\", \"energy_above_hull\"])\n\n# + id=\"d79f439b-a49e-4c5c-84a5-945474ac473a\"\nABO3_dicts = [i.dict() for i in ABO3]\n\n# + id=\"626f99aa-4b38-40a3-9512-02a31792eec3\"\nmp_database = pd.DataFrame(data=ABO3_dicts)\n\n# + [markdown] id=\"2-Mxskxc2xLb\"\n# ## **Step 3: Data Manipulation and Cleaning**\n# Now that we have the materials project data in a DataFrame named 'mp_database,' let's clean and manipulate the data to make it more suitable for analysis.\n#\n\n# + id=\"954980dd-dd3d-48c8-b089-6a487ae29f04\"\nmp_database = mp_database.drop(\"fields_not_requested\", axis=1)\n\n# + id=\"9006a094-71a2-43ed-a403-5d9b6facba34\" outputId=\"f6fd7d67-35fd-4711-d0df-44ae3d131cb9\"\nlen(mp_database)\n\n# + id=\"9eba5658-e43a-409d-9f4d-3c0e0dbcc25b\"\ngrouped = mp_database.groupby('formula_pretty').size()\n\n# + id=\"3e5c5fd7-15df-4207-bb53-9cbd8743e587\" outputId=\"81e9a052-c290-4c9b-b3d1-0bb96014858b\"\ngrouped.mean()\n\n# + id=\"2e5d2631-dc11-4e4b-a8ae-9726cb574de2\" outputId=\"0bc5d184-0769-4629-9da0-4d8fa264fcc0\"\nmp_database.nunique()\n\n# + id=\"1d9c0b6b-58c4-43fe-8c4a-511448721828\" outputId=\"56e47e0c-4045-4984-8078-f35cc4fc145e\"\nmp_database\n\n# + id=\"e1d9fa0a-9d57-40e0-adc2-65a91f48a835\" outputId=\"0f27cdb4-1a67-4577-ffc9-10631dedc50b\"\nmp_database['theoretical'].value_counts()[False]\n\n# + id=\"8860dd87-ad6f-4e3e-b492-1c8e7cb6ac8e\"\nmp_database['formation_energy_per_atom_ev_mol'] = mp_database['formation_energy_per_atom'] * 96491.5666\n\n# + id=\"6f5e2c8f-785d-49fd-8fb4-f5120f50c2d9\" outputId=\"c9868207-c24a-45d5-bf0b-b56fd57a8e67\"\nmp_database\n\n\n# + [markdown] id=\"KBWfQRoY3Wf8\"\n# ##**Step 4: Classifying Materials**\n# Let's classify the materials based on their stability and band gap properties. We'll define two functions, 'stability_category' and 'bandgap_category,' to perform the classification.\n\n# + id=\"207d4577-85b9-4399-beed-5fc720d93752\" outputId=\"1fad7d65-74b6-4731-ee86-86718c34d1c2\"\n# Assuming you already have a pandas DataFrame named 'mp_database' with columns 'energy_above_hull' and 'band_gap'\n\n# Function to classify materials based on energy_above_hull\ndef stability_category(energy):\n if energy > 0.03:\n return 'unstable'\n else:\n return 'potentially_stable'\n\n# Function to classify materials based on band_gap\ndef bandgap_category(band_gap):\n if band_gap == 0:\n return 'metal'\n elif 0 < band_gap <= 1:\n return 'small_bandgap'\n else:\n return 'large_bandgap'\n\n# Apply the classification functions to the DataFrame\nmp_database['stability'] = mp_database['energy_above_hull'].apply(stability_category)\nmp_database['bandgap_type'] = mp_database['band_gap'].apply(bandgap_category)\n\n# Create a pivot table to get the desired table structure\nnew_table = pd.pivot_table(mp_database, index='stability', columns='bandgap_type', aggfunc='size', fill_value=0)\n\n# Reorder the columns to match the desired order\nnew_table = new_table[['metal', 'small_bandgap', 'large_bandgap']]\n\nprint(new_table)\n\n# + id=\"7d1ccf91-cc03-4062-a5f4-1c8e9551b36f\" outputId=\"067879ce-4fa9-4313-c4d2-a1226313fbee\"\nmp_database\n\n# + [markdown] id=\"KNfX7ACJ3lsh\"\n# ##**Step 5: Data Visualization - Formation Energy Distribution**\n# Visualizing data is crucial for understanding its distribution and characteristics. Let's create a histogram to visualize the distribution of formation energies per atom.\n\n# + id=\"e78a2cb7-42e1-4d22-8e40-9f8673c6773a\" outputId=\"75be83a3-5bb9-4cbf-eb71-4219e1516f54\"\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# Assuming you have a pandas DataFrame named 'mp_database' with the 'formation_energies_per_atom' column\n\n# Calculate the average and standard deviation\naverage_energy = mp_database['formation_energy_per_atom'].mean()\nstd_deviation = mp_database['formation_energy_per_atom'].std()\n\n# Plot the distribution of the column\nplt.figure(figsize=(10, 6))\nplt.hist(mp_database['formation_energy_per_atom'], bins=30, edgecolor='black', alpha=0.7)\n\n# Add labels and title to the plot\nplt.xlabel('Formation Energies per Atom')\nplt.ylabel('Frequency')\nplt.title('Distribution of Formation Energies per Atom')\n\n# Annotate the plot with average and standard deviation\nplt.axvline(average_energy, color='red', linestyle='dashed', linewidth=2, label='Average')\nplt.axvline(average_energy + std_deviation, color='orange', linestyle='dashed', linewidth=2, label='Standard Deviation')\nplt.axvline(average_energy - std_deviation, color='orange', linestyle='dashed', linewidth=2)\nplt.annotate(f'Average: {average_energy:.2f}', xy=(average_energy, 300), xytext=(average_energy + 0.5, 400),\n arrowprops=dict(facecolor='black', shrink=0.05), fontsize=12)\nplt.annotate(f'Standard Deviation: {std_deviation:.2f}', xy=(average_energy + std_deviation, 250),\n xytext=(average_energy + std_deviation + 1, 350), arrowprops=dict(facecolor='black', shrink=0.05),\n fontsize=12)\n\n# Show legend\nplt.legend()\n\n# Display the plot\nplt.show()\n\n# + [markdown] id=\"Xwj2-ZQU30IE\"\n# ##**Step 6: Filtering and Preparing Data for Analysis**\n# Next, we'll filter the data to keep only the most relevant materials. We'll sort the data based on formation energy and remove duplicate formulas to keep only the materials with the lowest formation energy for each formula.\n\n# + id=\"fb7f1278-5a60-4d8a-ae40-ab32e9699268\"\norig_data = pd.read_csv(\"data2022.csv\", na_filter=False)\n\n# + id=\"a1bd639c-b300-4482-927a-b60d39b4cd85\" outputId=\"2d90bfbc-54dd-453d-fb32-c1f0dadd9ed6\"\nlen(orig_data)\n\n# + id=\"434df026-7169-40da-a327-6ebbba30688f\" outputId=\"7eb7cfb7-6881-4d8d-981c-712f6ad1c1c1\"\norig_data\n\n# + id=\"4e0d2db7-39f6-4211-8a9a-f134ea835e65\" outputId=\"0025bc0d-9c87-45af-c40e-63039d9a8bcf\"\nimport pandas as pd\n\n# Assuming you have a pandas DataFrame named 'orig_data' with 'formation_energy_per_atom' and 'formula' columns\n\n# Sort the DataFrame by 'formation_energy_per_atom' in ascending order\norig_data.sort_values(by='formation_energy_per_atom', ascending=True, inplace=True)\n\n# Drop duplicates based on the 'formula' column and keep the first occurrence (smallest formation_energy_per_atom)\nfiltered_data = orig_data.drop_duplicates(subset='formula', keep='first')\n\n# Display the resulting DataFrame\nfiltered_data\n\n# + id=\"83c0a81b-6fcc-4dd0-8c97-777b0996e1a2\"\nfiltered_data = filtered_data[filtered_data[\"formation_energy_per_atom\"] < 0]\n\n# + id=\"61b9e1f6-9a55-4ff0-96a8-d74a887905a7\" outputId=\"e98f7a6b-9880-4e66-cdc7-adfd89778e89\"\nfiltered_data\n\n# + [markdown] id=\"q0F8n4484Ly0\"\n# ## **Step 7: Calculating Composition-Averaged Properties**\n# We will now calculate the composition-averaged atomic radius for each material in 'filtered_data' using the element properties data available in 'element_data' DataFrame.\n\n# + id=\"f3a67731-07bd-4ee8-92c3-b56703c93871\"\nelement_data = pd.read_csv(\"element_properties.csv\", index_col=0)\n\n# + id=\"78a1c3f1-897e-45c3-bdd4-eee2626e5ba2\" outputId=\"29bbd487-6da6-43c4-a009-b8a164444286\"\nelement_data\n\n# + id=\"cb7d478b-7f6b-4b27-b30e-0ba91f9d5106\" outputId=\"99d91974-1679-4760-f547-0dc55efe0f55\"\ntype(element_data[\"AtomicRadius\"][1])\n\n# + id=\"dd3444d1-fea3-428c-b86e-dc2bdef9ea3a\"\ncomp = Composition('Al2O3')\n\n# + id=\"bf9cd46f-906c-4ed7-b08d-5b71959b0df5\" outputId=\"b4069b33-9039-4573-ec2b-bafb3a473716\"\nprint(comp.elements)\n\n# + id=\"e96d693a-32ab-40ff-87e1-404a2db3db5b\" outputId=\"a062368d-1aa8-414a-ae01-60a465cd5372\"\nprint(comp.to_data_dict['unit_cell_composition'])\n\n# + id=\"d3632172-76c2-485c-8561-8df0aeae6b8d\"\nimport numpy as np\n\ncount = 0\ncolumn_nans = {}\nfor column in element_data.columns:\n for element in element_data[column]:\n if np.isnan(element):\n count += 1\n column_nans[column] = count\n count = 0\n\n# + id=\"bd8c7420-005b-431d-86bd-9aed778655fe\" outputId=\"41f3f7cf-93fb-4b94-a8f3-83093e7ed23e\"\ncolumn_nans\n\n# + id=\"b6b0c776-0edb-4bf9-a0da-312704f5b6b7\" outputId=\"e8545026-8089-4f84-9d5d-a2ad2209e054\"\n# Set of commands to compute the mean value for each column, replace the NaNs by the mean and output the updated data set\nfor i in element_data.columns:\n col_mean = element_data[i].mean(skipna=True)\n element_data[i] = element_data[i].fillna(col_mean)\nelement_data\n\n# + id=\"0a40ccc5-9cbe-4e52-86b6-8c367c91c47e\" outputId=\"cfcadfd0-4739-42ab-812a-6979728c3fc8\"\n# Set of commands to compute and output the composition-averaged Atomic Radius for all materials\nbegin_time = datetime.datetime.now()\natomic_radius = pd.DataFrame()\nfiltered_data[\"composition_dict\"] = [Composition(i).as_dict() for i in filtered_data.formula]\natomic_radius[\"formula\"] = filtered_data.formula\natomic_radius[\"atomic_radius_avg\"] = [np.average([element_data.loc[[el]][\"AtomicRadius\"][0] for el in comp], weights=[comp[el] for el in comp]) for comp in filtered_data.composition_dict]\nprint(datetime.datetime.now() - begin_time)\natomic_radius\n\n# + id=\"efecf56c-4571-4b66-8bfb-237f224cc603\"\natomic_radius_2 = pd.DataFrame()\natomic_radius_2[\"formula\"] = filtered_data.formula\natomic_radius_2[\"composition_dict\"] = filtered_data.composition_dict\ncomposition_averaged_list = []\nfor composition in atomic_radius_2[\"composition_dict\"]:\n total_atoms_in_formula = 0\n element_radius_weighted = 0\n for element in composition:\n total_atoms_in_formula += composition[element]\n element_radius_weighted += element_data.loc[element][\"AtomicRadius\"] * composition[element]\n average = element_radius_weighted / total_atoms_in_formula\n composition_averaged_list.append(average)\natomic_radius_2[\"atomic_radius_avg\"] = composition_averaged_list\n\n# + id=\"9356c706-4396-4494-98e7-ca598a5a58b1\" outputId=\"c1b9d4af-5ac5-4643-d6af-84f71ffc4219\"\natomic_radius_2\n\n# + id=\"e0f95828-baf8-4940-ada8-d899a65c4569\"\naverage_properties = pd.DataFrame()\naverage_properties[\"formula\"] = filtered_data.formula\naverage_properties[\"composition_dict\"] = filtered_data.composition_dict\nfor prop in element_data.columns:\n composition_averaged_list = []\n for composition in average_properties[\"composition_dict\"]:\n total_atoms_in_formula = 0\n element_property_weighted = 0\n for element in composition:\n total_atoms_in_formula += composition[element]\n element_property_weighted += element_data.loc[element][prop] * composition[element]\n average = element_property_weighted / total_atoms_in_formula\n composition_averaged_list.append(average)\n average_properties[prop] = composition_averaged_list\n\n# + id=\"1414ba67-8f46-4f61-800a-3fb20954be92\" outputId=\"a497f15b-851b-4d36-c305-bbb49f35622a\"\naverage_properties\n\n# + id=\"d0fc87c9-674d-4175-bf60-4e400edca4d6\"\nmax_properties = pd.DataFrame()\nmax_properties[\"formula\"] = filtered_data.formula\nmax_properties[\"composition_dict\"] = filtered_data.composition_dict\nfor prop in element_data.columns:\n composition_max_list = []\n max_property = 0\n for composition in max_properties[\"composition_dict\"]:\n for element in composition:\n if element_data.loc[element][prop] > max_property:\n max_property = element_data.loc[element][prop]\n composition_max_list.append(max_property)\n max_properties[prop] = composition_max_list\n\n# + id=\"cceaa45d-7f36-4121-a2d2-fae0cc65d4ff\" outputId=\"f21a1a73-3789-4766-9dc2-9e638bb2b07d\"\nmax_properties\n\n# + id=\"18b88751-fd47-43a4-bfd3-fb8b72e0dc66\"\nmin_properties = pd.DataFrame()\nmin_properties[\"formula\"] = filtered_data.formula\nmin_properties[\"composition_dict\"] = filtered_data.composition_dict\nfor prop in element_data.columns:\n composition_min_list = []\n min_property = inf\n for composition in min_properties[\"composition_dict\"]:\n for element in composition:\n if element_data.loc[element][prop] < min_property:\n min_property = element_data.loc[element][prop]\n composition_min_list.append(min_property)\n min_properties[prop] = composition_min_list\n\n# + id=\"92311cfb-ff99-4b83-95a6-c74a5ef42438\" outputId=\"b2314807-5c41-4f1e-ad33-4e4c8c1f68e4\"\nmin_properties\n\n# + id=\"ee826dae-4a9f-4d64-92f2-083a8c4cb7dc\"\naverage_properties = average_properties.drop(\"composition_dict\", axis=1)\naverage_properties = average_properties.drop(\"formula\", axis=1)\nmax_properties = max_properties.drop(\"composition_dict\", axis=1)\nmax_properties = max_properties.drop(\"formula\", axis=1)\nmin_properties = min_properties.drop(\"composition_dict\", axis=1)\nmin_properties = min_properties.drop(\"formula\", axis=1)\n\n# + [markdown] id=\"x-kGAr_34Wcd\"\n# ## **Step 8: Combining Property Data**\n# Next, we'll combine the composition-averaged, maximum, and minimum property DataFrames ('average_properties', 'max_properties', and 'min_properties') into a single design matrix DataFrame named 'design_matrix'.\n#\n\n# + id=\"14dbe079-62ee-4129-9caa-14edbb450404\"\ndesign_matrix = pd.concat([average_properties, max_properties, min_properties], axis=1)\n\n# + [markdown] id=\"q-PKbCN24i05\"\n# ## **Step 9: Splitting Data for Machine Learning**\n# To train and evaluate our machine learning model, we need to split the data into training and testing sets.\n\n# + id=\"17acd917-521b-47d2-bd8b-3085d417898c\"\ntargets = filtered_data[[\"band_gap\", \"formation_energy_per_atom\"]]\ntargets.index = filtered_data.formula\n\n# + id=\"f8cd2e51-a50b-410a-a90c-217179493bf5\" outputId=\"67bbe612-d483-4081-9462-a640b869d722\"\ntargets\n\n# + id=\"90db3a86-10eb-4f27-9330-526ca60c1efc\"\ntrain_X, test_X, train_y, test_y = train_test_split(design_matrix, targets, test_size=0.10, random_state=42)\n\n# + [markdown] id=\"5zd_bsNd4rXI\"\n# ## **Step 10: Data Normalization**\n# Normalization is an essential preprocessing step in machine learning. We'll normalize the training data by subtracting the mean and dividing by the standard deviation.\n\n# + id=\"36574e93-187a-4ff1-ba19-923ab4742cf6\"\n# Set of commands to obtain the mean and standard deviation of train_X\ntrain_mean = train_X.mean()\ntrain_std = train_X.std()\n\n# Set of commands to obtain the new normalized train and test data sets\nnorm_train_X = (train_X - train_mean) / (train_std)\nnorm_test_X = (test_X - train_mean) / (train_std)\n\n# + [markdown] id=\"RkXNx-TO48nb\"\n# ## **Step 11: Cross-Validated Linear Regression**\n# We'll perform linear regression using scikit-learn and apply cross-validation to evaluate the model's performance.\n\n# + id=\"cb69a28c-1ce6-4158-a6ac-0f99edd7b57d\" outputId=\"725f1f7c-71eb-4401-a54d-28a709f95880\"\n# Set of commands to run the 5-fold cross-validation on the training set, pick the best-scoring model, and apply it to the test set\nkfold = KFold(n_splits=5, shuffle=True, random_state=42)\nmlr = linear_model.LinearRegression()\nmlr.fit(train_X, train_y[\"formation_energy_per_atom\"])\ncross_val = cross_validate(mlr, train_X, train_y[\"formation_energy_per_atom\"], cv=kfold, return_estimator=True)\ncv_mlr = cross_val[\"estimator\"][np.argmax(cross_val[\"test_score\"])]\ncv_mlr.fit(test_X, test_y[\"formation_energy_per_atom\"])\nyhat = cv_mlr.predict(test_X)\n\n# Set of commands to obtain the RMSE and MAE\nMAE = mean_absolute_error(test_y[\"formation_energy_per_atom\"], yhat)\nRMSE = mean_squared_error(test_y[\"formation_energy_per_atom\"], yhat, squared=False)\nprint(\"The mean absolute error for this cross-validated linear model is \" + str(MAE))\nprint(\"The root mean squared error for this cross-validated linear model is \" + str(RMSE))\n\n# + [markdown] id=\"bteEcOyy5GOs\"\n# ## **Step 12: Data Visualization - Pairplot**\n# Finally, we'll use seaborn to create a pairplot to visualize the relationships between different element properties.\n\n# + id=\"9c83cf9a-13c6-4bc9-8ed2-86e9503f89e4\" outputId=\"29a6ed8e-d7f8-4040-80e8-cdaefed5b1b0\"\nfeatures = [c for c in element_data.columns]\ngrid = sns.pairplot(element_data[features])\n\n# + id=\"71324787-e8df-4e08-9047-f02424bf4d9e\" outputId=\"0ef45526-b81c-4443-f07d-3dcfe6671003\"\ntrain_y\n\n# + [markdown] id=\"K4XXmr1h5NJz\"\n# ## **Conclusion**\n# Congratulations! You have completed the lesson on exploring materials project data and predicting material properties. We covered data access, cleaning, manipulation, visualization, and machine learning using Python and various libraries.\n#\n# Keep exploring and experimenting with different data analysis techniques and machine learning models to gain deeper insights into materials science and make accurate predictions for material properties.\n","repo_name":"nighthawkcoders/teacher_portfolio","sub_path":"_notebooks/2023-07-15-machine_learning.ipynb","file_name":"2023-07-15-machine_learning.ipynb","file_ext":"py","file_size_in_byte":18384,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"21"} +{"seq_id":"10369076060","text":"# +\nfrom utils import load_caption, load_vocab, decode_caption, load_annotations\nfrom nltk.translate import bleu_score\nimport os\nfrom tqdm import tqdm\nimport pickle\n\nimport numpy as np\n\nfrom matplotlib import pyplot as plt\n# %matplotlib inline\nplt.style.use('ggplot')\n# -\n\nvocab = load_vocab('/home/spb61/coco2014_vocab.json')\nimage_id_to_index, index_to_image_id, annotations_dict = load_annotations(annotations_dir='/home/spb61/annotations',\n annotations_file='captions_val2014.json',\n map_file = '/home/spb61/val_image_id_to_idx.csv')\n\n\ndef get_annotations(image_id):\n return [' '.join(cap) for cap in annotations_dict[image_id]]\n\n\ndef save_beams_to_pickle(k):\n captions = {}\n image_dir = \"/datadrive/val_beam_{}_states/\".format(k)\n for image in tqdm(sorted(os.listdir(image_dir))):\n caption_object = load_caption(image, image_dir=image_dir)\n captions[caption_object['image_id']] = [{\n 'score': cap['score'],\n 'sentence': cap['sentence']\n } for cap in caption_object['captions']]\n print(\"Images found: {}\".format(len(captions)))\n pickle.dump(captions, open(\"/datadrive/beams_{}.pickle\".format(k), 'wb'))\n\n\n# +\nbeam_caps = []\nreferences = []\n\nimage_dir = \"/datadrive/val_beam_{}_states/\".format(1)\nfor image in tqdm(sorted(os.listdir(image_dir))):\n image_id = int(image.split(\".\")[0])\n caption_object = load_caption(image, image_dir=image_dir)\n caption = ' '.join(decode_caption(caption_object['captions'][0]['sentence'], vocab))\n beam_caps.append(caption)\n annotations = [' '.join(c) for c in annotations_dict[image_id]]\n references.append(annotations)\n# -\n\n# cat /datadrive/val_beam_10_states/1.json\n\nfrom nltk.translate import bleu_score\nbleu_score.corpus_bleu(references, beam_caps)\n\n\n\nsave_beams_to_pickle(100)\n\n# %ls -lh /datadrive\ncaptions = pickle.load(open(\"/datadrive/beams_{}.pickle\".format(10), 'rb'))\n\ncaptions\n\n\n","repo_name":"seb5666/image_captions","sub_path":"evaluation/Beam-Blue correlation.ipynb","file_name":"Beam-Blue correlation.ipynb","file_ext":"py","file_size_in_byte":2053,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"21"} +{"seq_id":"44198970666","text":"# a mapping\ndef function1(x):\n return 2*x\n\n\na = function1(2)\n\nprint(\"Value of a: \"+str(a))\n\n# +\n# BMI Calculator\nname1 = \"Ashmi\"\nheight_m1 = 2\nweight_kg1 = 100\n\nname2 = \"Piyali\"\nheight_m2 = 1.8\nweight_kg2 = 70\n\nname3 = \"Mansi\"\nheight_m3 = 2.5\nweight_kg3 = 160\n\n\n# -\n\ndef bmi_calculator(name, height_m, weight_kg):\n bmi = weight_kg/ (height_m ** 2)\n print(\"BMI\"+str(bmi))\n if(bmi < 25):\n return name + \" is not overweight\"\n else:\n return name + \" is overweight\"\n\n\nresult1 = bmi_calculator(name1, height_m1, weight_kg1)\nresult2 = bmi_calculator(name2, height_m2, weight_kg2)\nresult3 = bmi_calculator(name3, height_m3, weight_kg3)\n\nprint(result1)\nprint(result2)\nprint(result3)\n","repo_name":"ashmichheda/MITx-6.00.1x-python-programming","sub_path":"Jupyter_Notebook_PyFiles/What are functions.ipynb","file_name":"What are functions.ipynb","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-jupyter-script","pt":"21"} +{"seq_id":"37487821477","text":"# \"Kaggle\"\n\n# + _cell_guid=\"b1076dfc-b9ad-4769-8c92-a6c4dae69d19\" _uuid=\"8f2839f25d086af736a60e9eeb907d3b93b6e0e5\" papermill={\"duration\": 12.966312, \"end_time\": \"2022-09-05T05:57:07.222563\", \"exception\": false, \"start_time\": \"2022-09-05T05:56:54.256251\", \"status\": \"completed\"}\nimport pandas as pd\n\n# 데이터 경로\ndata_path = '/kaggle/input/porto-seguro-safe-driver-prediction/'\n\ntrain = pd.read_csv(data_path + 'train.csv', index_col='id')\ntest = pd.read_csv(data_path + 'test.csv', index_col='id')\nsubmission = pd.read_csv(data_path + 'sample_submission.csv', index_col='id')\n\n# + [markdown] papermill={\"duration\": 0.009311, \"end_time\": \"2022-09-05T05:57:07.250867\", \"exception\": false, \"start_time\": \"2022-09-05T05:57:07.241556\", \"status\": \"completed\"}\n# ## 8.4.1 피처 엔지니어링\n# * 데이터 합치기\n\n# + papermill={\"duration\": 1.678836, \"end_time\": \"2022-09-05T05:57:08.939284\", \"exception\": false, \"start_time\": \"2022-09-05T05:57:07.260448\", \"status\": \"completed\"}\nall_data = pd.concat([train, test], ignore_index=True)\nall_data = all_data.drop('target', axis=1) # 타겟값 제거\n\nall_features = all_data.columns # 전체 피처\n\n# + [markdown] papermill={\"duration\": 0.010628, \"end_time\": \"2022-09-05T05:57:08.959634\", \"exception\": false, \"start_time\": \"2022-09-05T05:57:08.949006\", \"status\": \"completed\"}\n# * 명목형 피처 원-핫 인코딩\n\n# + papermill={\"duration\": 4.570068, \"end_time\": \"2022-09-05T05:57:13.539739\", \"exception\": false, \"start_time\": \"2022-09-05T05:57:08.969671\", \"status\": \"completed\"}\nfrom sklearn.preprocessing import OneHotEncoder\n\n# 명목형 피처\ncat_features = [feature for feature in all_features if 'cat' in feature]\n\n# 원-핫 인코딩 적용\nonehot_encoder = OneHotEncoder()\nencoded_cat_matrix = onehot_encoder.fit_transform(all_data[cat_features])\n\n# + papermill={\"duration\": 0.258586, \"end_time\": \"2022-09-05T05:57:13.809278\", \"exception\": false, \"start_time\": \"2022-09-05T05:57:13.550692\", \"status\": \"completed\"}\n# '데이터 하나당 결측값 개수'를 파생 피처로 추가\nall_data['num_missing'] = (all_data==-1).sum(axis=1)\n\n# + papermill={\"duration\": 0.019486, \"end_time\": \"2022-09-05T05:57:13.837227\", \"exception\": false, \"start_time\": \"2022-09-05T05:57:13.817741\", \"status\": \"completed\"}\n# 명목형 피처, calc 분류의 피처를 제외한 피처\nremaining_features = [feature for feature in all_features\n if ('cat' not in feature and 'calc' not in feature)]\n\n# num_missing을 remaining_features에 추가\nremaining_features.append('num_missing')\n\n# + [markdown] papermill={\"duration\": 0.008142, \"end_time\": \"2022-09-05T05:57:13.856619\", \"exception\": false, \"start_time\": \"2022-09-05T05:57:13.848477\", \"status\": \"completed\"}\n# * 파생 피처 만들기\n\n# + papermill={\"duration\": 22.296664, \"end_time\": \"2022-09-05T05:57:36.161582\", \"exception\": false, \"start_time\": \"2022-09-05T05:57:13.864918\", \"status\": \"completed\"}\n# mix_ind 만들기 -> ind 피처들을 하나로 뭉치기\n\n# 분류가 ind인 피처\nind_features = [feature for feature in all_features if 'ind' in feature]\n\nis_first_feature = True\nfor ind_feature in ind_features:\n if is_first_feature:\n all_data['mix_ind'] = all_data[ind_feature].astype(str) + '_'\n is_first_feature = False\n else:\n all_data['mix_ind'] += all_data[ind_feature].astype(str) + '_'\n\n# + [markdown] papermill={\"duration\": 0.00799, \"end_time\": \"2022-09-05T05:57:36.178278\", \"exception\": false, \"start_time\": \"2022-09-05T05:57:36.170288\", \"status\": \"completed\"}\n# * 고윳값별 개수를 새로운 피처로 추가\n\n# + papermill={\"duration\": 0.037818, \"end_time\": \"2022-09-05T05:57:36.224691\", \"exception\": false, \"start_time\": \"2022-09-05T05:57:36.186873\", \"status\": \"completed\"}\nall_data['ps_ind_02_cat'].value_counts().to_dict()\n\n# + papermill={\"duration\": 9.457999, \"end_time\": \"2022-09-05T05:57:45.691586\", \"exception\": false, \"start_time\": \"2022-09-05T05:57:36.233587\", \"status\": \"completed\"}\ncat_count_features = []\nfor feature in cat_features+['mix_ind']:\n val_counts_dict = all_data[feature].value_counts().to_dict()\n all_data[f'{feature}_count'] = all_data[feature].apply(lambda x:\n val_counts_dict[x])\n cat_count_features.append(f'{feature}_count')\n\n# + papermill={\"duration\": 0.018485, \"end_time\": \"2022-09-05T05:57:45.718776\", \"exception\": false, \"start_time\": \"2022-09-05T05:57:45.700291\", \"status\": \"completed\"}\ncat_count_features\n\n# + [markdown] papermill={\"duration\": 0.00868, \"end_time\": \"2022-09-05T05:57:45.736397\", \"exception\": false, \"start_time\": \"2022-09-05T05:57:45.727717\", \"status\": \"completed\"}\n# * 필요없는 피처 제거 \n# 지금까지 만든 피처들 \n# encoded_cat_matrix : 원-핫 인코딩된 명목형 피처 \n# remaining_features : 명목형 피처와 calc 분류의 피처를 제외한 피처들 (+num_missing) \n# cat_count_features : mix_ind를 포함한 명목형 피처의 고윳값별 개수 파생 피처\n\n# + papermill={\"duration\": 6.413168, \"end_time\": \"2022-09-05T05:57:52.158334\", \"exception\": false, \"start_time\": \"2022-09-05T05:57:45.745166\", \"status\": \"completed\"}\nfrom scipy import sparse\n# 필요없는 피처들\ndrop_features = ['ps_ind_14', 'ps_ind_10_bin', 'ps_ind_11_bin',\n 'ps_ind_12_bin', 'ps_ind_13_bin', 'ps_car_14']\n\n# remaining_features, cat_count_features에서 drop_features를 제거한 데이터\nall_data_remaining = all_data[remaining_features+cat_count_features].drop(drop_features, axis=1)\n\n# 데이터 합치기\nall_data_sprs = sparse.hstack([sparse.csr_matrix(all_data_remaining),\n encoded_cat_matrix],\n format='csr')\n\n# + [markdown] papermill={\"duration\": 0.008089, \"end_time\": \"2022-09-05T05:57:52.175003\", \"exception\": false, \"start_time\": \"2022-09-05T05:57:52.166914\", \"status\": \"completed\"}\n# * 데이터 나누기\n\n# + papermill={\"duration\": 1.440995, \"end_time\": \"2022-09-05T05:57:53.624249\", \"exception\": false, \"start_time\": \"2022-09-05T05:57:52.183254\", \"status\": \"completed\"}\nnum_train = len(train) # 훈련 데이터 개수\n\n# 훈련 데이터와 테스트 데이터 나누기\nX = all_data_sprs[:num_train]\nX_test = all_data_sprs[num_train:]\n\ny = train['target'].values\n\n# + [markdown] papermill={\"duration\": 0.008443, \"end_time\": \"2022-09-05T05:57:53.641973\", \"exception\": false, \"start_time\": \"2022-09-05T05:57:53.63353\", \"status\": \"completed\"}\n# ## 8.4.2 하이퍼파라미터 최적화\n\n# + [markdown] papermill={\"duration\": 0.008159, \"end_time\": \"2022-09-05T05:57:53.658758\", \"exception\": false, \"start_time\": \"2022-09-05T05:57:53.650599\", \"status\": \"completed\"}\n# * 데이터셋\n\n# + papermill={\"duration\": 1.094614, \"end_time\": \"2022-09-05T05:57:54.761789\", \"exception\": false, \"start_time\": \"2022-09-05T05:57:53.667175\", \"status\": \"completed\"}\nimport lightgbm as lgb\nfrom sklearn.model_selection import train_test_split\n\n# 8:2 비율로 훈련 데이터, 검증 데이터 분리 (베이지안 최적화 수행용)\nX_train, X_valid, y_train, y_valid = train_test_split(X, y,\n test_size=0.2,\n random_state=0)\n\n# 베이지안 최적화용 데이터셋\nbayes_dtrain = lgb.Dataset(X_train, y_train)\nbayes_dvalid = lgb.Dataset(X_valid, y_valid)\n\n# + [markdown] papermill={\"duration\": 0.008254, \"end_time\": \"2022-09-05T05:57:54.779192\", \"exception\": false, \"start_time\": \"2022-09-05T05:57:54.770938\", \"status\": \"completed\"}\n# * 하이퍼파라미터 범위설정\n\n# + papermill={\"duration\": 0.018282, \"end_time\": \"2022-09-05T05:57:54.806164\", \"exception\": false, \"start_time\": \"2022-09-05T05:57:54.787882\", \"status\": \"completed\"}\n# 베이지안 최적화를 위한 하이퍼파라미터 범위\nparam_bounds = {'num_leaves': (30, 40),\n 'lambda_l1': (0.7, 0.9),\n 'lambda_l2': (0.9, 1),\n 'feature_fraction': (0.6, 0.7),\n 'bagging_fraction': (0.6, 0.9),\n 'min_child_samples': (6, 10),\n 'min_child_weight': (10, 40)}\n\n# 값이 고정된 하이퍼파라미터\nfixed_params = {'objective': 'binary', # 이진분류 문제기 때문에 binary설정\n 'learning_rate': 0.005, # 학습률은 보통 0.01 ~ 0.001 사이의 값으로 설정함\n 'bagging_freq': 1, # learning_rate, bagging_freq는 범위로 해도되고 변경하면서 최적을 찾아도 됨\n 'force_row_wise': True, # 경고문구 제거를 위해\n 'random_state': 1993} # 동일한 결과를 위해 값 고정\n\n# + papermill={\"duration\": 0.019323, \"end_time\": \"2022-09-05T05:57:54.834529\", \"exception\": false, \"start_time\": \"2022-09-05T05:57:54.815206\", \"status\": \"completed\"}\nimport numpy as np\n\ndef eval_gini(y_true, y_pred):\n # 실제값과 예측값의 크기가 서로 같은지 확인 (값이 다르면 오류 발생)\n assert y_true.shape == y_pred.shape\n \n n_samples = y_true.shape[0] # 데이터 개수\n L_mid = np.linspace(1 / n_samples, 1, n_samples) # 대각선 값\n \n # 1) 예측값에 대한 지니계수\n pred_order = y_true[y_pred.argsort()] # y_pred 크기 순으로 y_true 값 정렬\n L_pred = np.cumsum(pred_order) / np.sum(pred_order) # 로렌츠 곡선\n G_pred = np.sum(L_mid - L_pred) # 예측값에 대한 지니계수\n \n # 2) 예측이 완벽할 때 지니계수\n true_order = y_true[y_true.argsort()] # y_true 크기 순으로 y_true값 정렬\n L_true = np.cumsum(true_order) / np.sum(true_order) # 로렌츠 곡선\n G_true = np.sum(L_mid - L_true) # 예측이 완벽할 때 지니계수\n \n # 정규화된 지니계수\n return G_pred / G_true\n\n\n# + papermill={\"duration\": 0.017664, \"end_time\": \"2022-09-05T05:57:54.860925\", \"exception\": false, \"start_time\": \"2022-09-05T05:57:54.843261\", \"status\": \"completed\"}\n# LightGBM용 gini() 함수\ndef gini(preds, dtrain):\n labels = dtrain.get_label() # 데이터셋의 타겟값을 반환함\n return 'gini', eval_gini(labels, preds), True # 평가지표 이름, 평가점수, 평가점수가 높을수록 좋은지 여부\n\n\n# + [markdown] papermill={\"duration\": 0.008636, \"end_time\": \"2022-09-05T05:57:54.878639\", \"exception\": false, \"start_time\": \"2022-09-05T05:57:54.870003\", \"status\": \"completed\"}\n# 베이지안 최적화용 평가지표 계산 함수 작성\n\n# + papermill={\"duration\": 0.020751, \"end_time\": \"2022-09-05T05:57:54.908044\", \"exception\": false, \"start_time\": \"2022-09-05T05:57:54.887293\", \"status\": \"completed\"}\ndef eval_function(num_leaves, lambda_l1, lambda_l2, feature_fraction, \n bagging_fraction, min_child_samples, min_child_weight):\n '''최적화하려는 평가지표(지니계수) 계산 함수'''\n \n # 베이지안 최적화를 수행할 하이퍼파라미터\n params = {'num_leaves': int(round(num_leaves)),\n 'lambda_l1': lambda_l1,\n 'lambda_l2': lambda_l2,\n 'feature_fraction': feature_fraction,\n 'bagging_fraction': bagging_fraction,\n 'min_child_samples': int(round(min_child_samples)),\n 'min_child_weight': min_child_weight,\n 'feature_pre_filter': False}\n \n # 고정된 하이퍼파라미터도 추가\n params.update(fixed_params)\n \n print('하이퍼파라미터:', params)\n \n # LightGBM 모델 훈련\n lgb_model = lgb.train(params=params,\n train_set=bayes_dtrain,\n num_boost_round=2500,\n valid_sets=bayes_dvalid,\n feval=gini,\n early_stopping_rounds=300,\n verbose_eval=False)\n # 검증 데이터로 예측 수행\n preds = lgb_model.predict(X_valid)\n # 지니계수 계산\n gini_score = eval_gini(y_valid, preds)\n print(f'지니계수 : {gini_score}\\n')\n \n return gini_score\n\n\n# + [markdown] papermill={\"duration\": 0.008591, \"end_time\": \"2022-09-05T05:57:54.925612\", \"exception\": false, \"start_time\": \"2022-09-05T05:57:54.917021\", \"status\": \"completed\"}\n# * 최적화 수행\n\n# + papermill={\"duration\": 0.036471, \"end_time\": \"2022-09-05T05:57:54.970948\", \"exception\": false, \"start_time\": \"2022-09-05T05:57:54.934477\", \"status\": \"completed\"}\nfrom bayes_opt import BayesianOptimization\n\n# 베이지안 최적화 객체 생성\noptimizer = BayesianOptimization(f=eval_function, # 평가지표 계산 함수\n pbounds=param_bounds, # 하이퍼파라미터 범위\n random_state=0)\n\n# + papermill={\"duration\": 1791.181267, \"end_time\": \"2022-09-05T06:27:46.161083\", \"exception\": false, \"start_time\": \"2022-09-05T05:57:54.979816\", \"status\": \"completed\"}\n# 베이지안 최적화 수행\n'''init_points와 n_iter를 더한 값만큼 반복함'''\noptimizer.maximize(init_points=3, # 무작위로 하이퍼파라미터를 탐색하는 횟수 \n n_iter=6) # 베이지안 최적화 반복횟수\n\n# + [markdown] papermill={\"duration\": 0.010019, \"end_time\": \"2022-09-05T06:27:46.181393\", \"exception\": false, \"start_time\": \"2022-09-05T06:27:46.171374\", \"status\": \"completed\"}\n# * 결과 확인\n\n# + papermill={\"duration\": 0.022122, \"end_time\": \"2022-09-05T06:27:46.213631\", \"exception\": false, \"start_time\": \"2022-09-05T06:27:46.191509\", \"status\": \"completed\"}\n# 평가함수 점수가 최대일 때 하이퍼파라미터\nmax_params = optimizer.max['params']\nmax_params\n\n# + papermill={\"duration\": 0.020726, \"end_time\": \"2022-09-05T06:27:46.24491\", \"exception\": false, \"start_time\": \"2022-09-05T06:27:46.224184\", \"status\": \"completed\"}\n# 정수형 하이퍼파라미터 변환\nmax_params['num_leaves'] = int(round(max_params['num_leaves']))\nmax_params['min_child_samples'] = int(round(max_params['min_child_samples']))\n\n# + papermill={\"duration\": 0.018961, \"end_time\": \"2022-09-05T06:27:46.274713\", \"exception\": false, \"start_time\": \"2022-09-05T06:27:46.255752\", \"status\": \"completed\"}\n# 값이 고정된 하이퍼파라미터 추가\nmax_params.update(fixed_params)\n\n# + papermill={\"duration\": 0.021541, \"end_time\": \"2022-09-05T06:27:46.3072\", \"exception\": false, \"start_time\": \"2022-09-05T06:27:46.285659\", \"status\": \"completed\"}\nmax_params\n\n# + [markdown] papermill={\"duration\": 0.010498, \"end_time\": \"2022-09-05T06:27:46.32867\", \"exception\": false, \"start_time\": \"2022-09-05T06:27:46.318172\", \"status\": \"completed\"}\n# ## 8.4.3 모델 훈련 및 성능 검증\n\n# + papermill={\"duration\": 1231.254349, \"end_time\": \"2022-09-05T06:48:17.593713\", \"exception\": false, \"start_time\": \"2022-09-05T06:27:46.339364\", \"status\": \"completed\"}\nfrom sklearn.model_selection import StratifiedKFold\n\n# 층화 K폴드 교차 검증기 생성\nfolds = StratifiedKFold(n_splits=5, shuffle=True, random_state=1993)\n\n# OOF 방식으로 훈련된 모델로 검증 데이터 타겟값을 예측한 확률을 담을 1차원 배열\noof_val_preds = np.zeros(X.shape[0])\n# OOF 방식으로 훈련된 모델로 테스트 데이터 타겟값을 예측한 확률을 담을 1차원 배열\noof_test_preds = np.zeros(X_test.shape[0])\n\n# OOF 방식으로 모델 훈련, 검증, 예측\nfor idx, (train_idx, valid_idx) in enumerate(folds.split(X, y)):\n # 각 폴드를 구분하는 문구 출력\n print('#'*40, f'폴드 {idx+1} / 폴드 {folds.n_splits}', '#'*40)\n \n # 훈련용 데이터, 검증용 데이터 설정\n X_train, y_train = X[train_idx], y[train_idx] # 훈련용 데이터\n X_valid, y_valid = X[valid_idx], y[valid_idx] # 검증용 데이터\n \n # LightGBM 전용 데이터셋 생성\n dtrain = lgb.Dataset(X_train, y_train) # LightGBM 전용 훈련 데이터셋\n dvalid = lgb.Dataset(X_valid, y_valid) # LightGBM 전용 검증 데이터셋\n \n # LightGBM 모델 훈련\n lgb_model = lgb.train(params=max_params, # 최적 하이퍼파라미터\n train_set=dtrain, # 훈련 데이터셋\n num_boost_round=2500, # 부스팅 반복 횟수\n valid_sets=dvalid, # 성능 평가용 검증 데이터\n feval=gini, # 검증용 평가지표\n early_stopping_rounds=300, # 조기종료 조건\n verbose_eval=100) # 100번째마다 점수 출력\n \n # 테스트 데이터를 활용해 OOF 예측\n oof_test_preds += lgb_model.predict(X_test)/folds.n_splits\n # 모델 성능 평가를 위한 검증 데이터 타겟값 예측\n oof_val_preds[valid_idx] += lgb_model.predict(X_valid)\n \n # 검증 데이터 예측 확률에 대한 정규화 지니계수\n gini_score = eval_gini(y_valid, oof_val_preds[valid_idx])\n print(f'폴드 {idx+1} 지니계수 : {gini_score}\\n')\n\n# + papermill={\"duration\": 0.129162, \"end_time\": \"2022-09-05T06:48:17.740886\", \"exception\": false, \"start_time\": \"2022-09-05T06:48:17.611724\", \"status\": \"completed\"}\nprint('OOF 검증 데이터 지니계수 :', eval_gini(y, oof_val_preds))\n\n# + [markdown] papermill={\"duration\": 0.017462, \"end_time\": \"2022-09-05T06:48:17.776959\", \"exception\": false, \"start_time\": \"2022-09-05T06:48:17.759497\", \"status\": \"completed\"}\n# ## 8.4.4 예측 및 결과 제출\n\n# + papermill={\"duration\": 2.224136, \"end_time\": \"2022-09-05T06:48:20.019217\", \"exception\": false, \"start_time\": \"2022-09-05T06:48:17.795081\", \"status\": \"completed\"}\nsubmission['target'] = oof_test_preds\nsubmission.to_csv('submission.csv')\n\n# + papermill={\"duration\": 0.01764, \"end_time\": \"2022-09-05T06:48:20.054955\", \"exception\": false, \"start_time\": \"2022-09-05T06:48:20.037315\", \"status\": \"completed\"}\n\n","repo_name":"DrunkJin/Kaggle","sub_path":"Porto Seguro’s Safe Driver Prediction/safedriver-lightgbm-musthave-ch08.ipynb","file_name":"safedriver-lightgbm-musthave-ch08.ipynb","file_ext":"py","file_size_in_byte":18023,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"21"} +{"seq_id":"3015353173","text":"# + [markdown] colab_type=\"text\" id=\"view-in-github\"\n# \"Open\n\n# + [markdown] id=\"FwuJLBncbohe\"\n# ###QUESTION 1:\n#\n# In the problem posed at the beginning of the section, John invested his inheritance of 12,000 dollars in three different funds: part in a money-market fund paying 3% interest annually; part in municipal bonds paying 4% annually; and the rest in mutual funds paying 7% annually. John invested 4,000 dollars more in mutual funds than he invested in municipal bonds. The total interest earned in one year was 670 dollars. How much did he invest in each type of fund?\n#\n# $$\\left[\\begin{array}{ccc|c}\n# 1&1&1&12000\\\\\n# 0&-1&1&4000\\\\\n# 0.03&0.04&0.07&670\\\\\n# \\end{array}\\right] \\\\ _{\\text{(Standard bracketed form)}}$$\n#\n# $$\\begin{bmatrix}\n# 1&1&1\\\\\n# 0&-1&1\\\\\n# 0.03&0.04&0.07\\\\\n# \\end{bmatrix} \\cdot\n# \\begin{bmatrix}x\\\\y\\\\z\\\\\\end{bmatrix}=\n# \\begin{bmatrix}12000\\\\4000\\\\670\\\\\\end{bmatrix}\n# \\\\ _{\\text{(Linear Combination form)}}$$\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 575} id=\"Dl0kaTlizbOB\" outputId=\"468a3f89-caf5-425d-f2d9-0e7bafff31e5\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nX = np.array([[1, 1, 1],[0, -1, 1],[0.03, 0.04,0.07]],float)\nb = np.array([12000, 4000, 670],float)\n\nc = np.arange(-10,10,1)\nequation1 = X[0]\nequation2 = X[1]\nequation3 = X[2]\n\n\nfig = plt.figure(figsize = (15,10))\nax = fig.gca(projection='3d')\n\nplt.title('Equations')\n\nax.plot(c*equation1[0],c*equation1[1],c*equation1[2], label = \"Eq 1\")\nax.plot(c*equation2[0],c*equation2[1],c*equation2[2], label = \"Eq 2\")\nax.plot(c*equation3[0],c*equation3[1],c*equation3[2], label = \"Eq 3\")\n\nplt.grid()\nplt.legend()\nplt.show()\n\n\n# + id=\"c6wZrfIliR24\"\ndef gaussElim(X,b):\n n = len(b)\n v = np.empty(n)\n for k in range(0,n-1):\n if X[k, k] == 0:\n for j in range (n):\n X[k,j], X[k+1, j] = X[k+1, j], X[k,j]\n b[k], b[k+1] = b[k+1], b[k]\n for i in range(k+1, n):\n if X[i, k] != 0:\n fctr = X[k, k] / X[i, k]\n b[i] = b[k] - fctr*b[i]\n X[i,k+1:n] = X[k,k+1:n] - fctr*X[i,k+1:n]\n\n v[n-1] = b[n-1] / X[n-1, n-1]\n for i in range(n-2,-1,-1):\n v[i]= (b[i]- np.sum(X[i,i+1:n]*v[i+1:n]))/X[i,i]\n \n return v\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"hmJEeVXFsAE4\" outputId=\"c5488779-2c98-4eff-aca1-505b4f86698b\"\nX = np.array([[1, 1, 1],[0, -1, 1],[0.03, 0.04,0.07]],float)\nb = np.array([12000, 4000, 670],float)\ninvest = gaussElim(X,b)\n\nprint('Invested in money-market fund with an amount of: ${:.2f}'.format(float(invest[0])))\nprint('Invested in municipal bonds with an amount of: ${:.2f}'.format(float(invest[1])))\nprint('Invested in mutual funds with an amount of: ${:.2f}'.format(float(invest[2])))\n\n\n# + [markdown] id=\"7z1tiKuge6BU\"\n# ### References\n#\n# [1] Lumen Learning College Algebra (2021). [***Systems of Linear Equations: Three Variables***](https://courses.lumenlearning.com/collegealgebra2017/chapter/introduction-systems-of-linear-equations-three-variables/)\n#\n#\n#\n","repo_name":"RovilSurioJr/Numerical-Methods","sub_path":"Numerical Differentiation/.ipynb_checkpoints/Solving_System_of_linear_equation-checkpoint.ipynb","file_name":"Solving_System_of_linear_equation-checkpoint.ipynb","file_ext":"py","file_size_in_byte":3238,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"25"} +{"seq_id":"25967487815","text":"# + [markdown] id=\"v0-q2tblh19F\"\n# step 1) 데이터 불러서 한 행씩 출력하기\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 1000} id=\"Yd72V2aWhsn7\" executionInfo={\"status\": \"error\", \"timestamp\": 1623389615815, \"user_tz\": -540, \"elapsed\": 3867, \"user\": {\"displayName\": \"\\ub85c\\ubbf9\", \"photoUrl\": \"\", \"userId\": \"13072686141127167034\"}} outputId=\"e6681c76-850e-4177-a49c-0e24f490475c\"\nimport csv \n\nf = open(\"/content/seoul.csv\" , 'r', encoding='cp949')\n\ndata = csv.reader(f)\nheader = next(data) # 헤더 추출\n\nfor row in data :\n print(row)\n # 최고기온 데이터만 추출\n row[-1] = float(row[-1]) # float(row[4]) -> 제일 마지막 컬럼 -> -1로 인덱스\n\nf.close()\n\n# + [markdown] id=\"5ua8-uzmlX0K\"\n# step 2) 데이터 중 최고 기온을 실수로 변환하기\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"yH7SyTeOjt8g\" executionInfo={\"status\": \"ok\", \"timestamp\": 1623391548023, \"user_tz\": -540, \"elapsed\": 17481, \"user\": {\"displayName\": \"\\ub85c\\ubbf9\", \"photoUrl\": \"\", \"userId\": \"13072686141127167034\"}} outputId=\"14dc4b76-5c7e-4fdf-a3c6-914726ef51c4\"\nimport csv\n\nmax_temp = -999 # 최고 기온 값을 저장할 변수 -> 명확한 결과를 위해 극적인 값으로 셋팅\nmax_date = '' # 최고 기온이 가장 높았던 날짜를 저장하는 변수\n\nf = open(\"/content/seoul.csv\" , 'r', encoding='cp949')\n\ndata = csv.reader(f)\nheader = next(data) # 헤더 추출\n\nfor row in data :\n # 최고 기온 데이터 ''(결측치) 확인\n if row[-1] == '' :\n row[-1] = -999 # -999를 넣어서 빈 문자열('')이 있던 자리라고 표시\n\n # 최고 기온 데이터 \n row[-1] = float(row[-1]) # 기온 데이터 실수형으로 변환\n print(row[0], row[-1]) # 날짜 데이터와 같이 출력\n\nf.close()\n\n# + [markdown] id=\"QUYkpJ68rdwH\"\n# step 3) 최고 기온과 최고 기온이었던 날짜 찾기\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"ITQCT8twlXAn\" executionInfo={\"status\": \"ok\", \"timestamp\": 1623391884739, \"user_tz\": -540, \"elapsed\": 449, \"user\": {\"displayName\": \"\\ub85c\\ubbf9\", \"photoUrl\": \"\", \"userId\": \"13072686141127167034\"}} outputId=\"ced786c6-eed0-4b39-f1bf-d88335b0086c\"\nimport csv\n\nmax_temp = -999 # 최고 기온 값을 저장할 변수 -> 명확한 결과를 위해 극적인 값으로 셋팅\nmax_date = '' # 최고 기온이 가장 높았던 날짜를 저장하는 변수\n\nf = open(\"/content/seoul.csv\" , 'r', encoding='cp949')\n\ndata = csv.reader(f)\nheader = next(data) # 헤더 추출\n\nfor row in data :\n # 최고 기온 데이터 ''(결측치) 확인\n if row[-1] == '' :\n row[-1] = -999 # -999를 넣어서 빈 문자열('')이 있던 자리라고 표시\n\n # 최고 기온 데이터 \n row[-1] = float(row[-1]) # 기온 데이터 실수형으로 변환\n\n # 최고 기온 정보를 저장\n\n if max_temp < row[-1] :\n max_date = row[0]\n max_temp = row[-1]\n\nf.close()\n\nprint('기상 관측 이래 서울의 최고 기온이 가장 높았던 날은 ', max_date+'로 ', max_temp,'도 였습니다.' )\n\n# + [markdown] id=\"rSQrsPqksxck\"\n# step 4) 최저 기온과 최저 기온이었던 날짜 찾기\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"hSt9E8-qrp2m\" executionInfo={\"status\": \"ok\", \"timestamp\": 1623393931622, \"user_tz\": -540, \"elapsed\": 462, \"user\": {\"displayName\": \"\\ub85c\\ubbf9\", \"photoUrl\": \"\", \"userId\": \"13072686141127167034\"}} outputId=\"f0e4ec71-b732-4b34-b35f-6de8800bf475\"\nimport csv\n\nmin_temp = 999 # 최저 기온 값을 저장할 변수 -> 명확한 결과를 위해 극적인 값으로 셋팅\nmin_date = '' # 최저 기온이 가장 낮았던 날짜를 저장하는 변수\n\nf = open(\"/content/seoul.csv\" , 'r', encoding='cp949')\n\ndata = csv.reader(f)\nheader = next(data) # 헤더 추출\n\nfor row in data :\n # 최저 기온 데이터 ''(결측치) 확인\n if row[3] == '' :\n row[3] = 999 # 999를 넣어서 빈 문자열('')이 있던 자리라고 표시\n\n # 최저 기온 데이터 \n row[3] = float(row[3]) # 기온 데이터 실수형으로 변환\n\n # 최저 기온 정보를 저장\n\n if min_temp > row[3] :\n min_date = row[0]\n min_temp = row[3]\n\nf.close()\n\nprint('기상 관측 이래 서울의 최저 기온이 가장 낮았던 날은 ', min_date+'로 ', min_temp,'도 였습니다.' )\n\n# + [markdown] id=\"Z7SdEZ1-5KPI\"\n# plt.plot(데이터셋) 그래프 그리기\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 283} id=\"GgCSvjU3svhh\" executionInfo={\"status\": \"ok\", \"timestamp\": 1623395367808, \"user_tz\": -540, \"elapsed\": 615, \"user\": {\"displayName\": \"\\ub85c\\ubbf9\", \"photoUrl\": \"\", \"userId\": \"13072686141127167034\"}} outputId=\"fda769fb-d951-4311-a4f2-ef5d434f1607\"\nimport matplotlib.pyplot as plt\n\nplt.plot([10, 20, 30, 40]) # y 값이 주어지면, 자동으로 x 값을 0부터 1씩 증가함\nplt.show\n\n# + [markdown] id=\"c3v8xY6I6WFj\"\n# plt.plot(x,y) 그래프 그리기\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 299} id=\"pu3FB7PB53W7\" executionInfo={\"status\": \"ok\", \"timestamp\": 1623395706874, \"user_tz\": -540, \"elapsed\": 616, \"user\": {\"displayName\": \"\\ub85c\\ubbf9\", \"photoUrl\": \"\", \"userId\": \"13072686141127167034\"}} outputId=\"2e292df3-e8a0-4412-d6da-0fb6bc032fdb\"\nplt.title('plotting') # 타이틀 속성 추가\nplt.plot([1, 2, 3, 4],[12, 43, 33, 51]) # plt.plot(x ,y) 함수에 데이터 입력하기\nplt.show\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 299} id=\"BvQP1H8G6g2a\" executionInfo={\"status\": \"ok\", \"timestamp\": 1623396334539, \"user_tz\": -540, \"elapsed\": 551, \"user\": {\"displayName\": \"\\ub85c\\ubbf9\", \"photoUrl\": \"\", \"userId\": \"13072686141127167034\"}} outputId=\"06a48aff-10bb-4919-8b3d-54f854399893\"\nplt.title('plotting') # 타이틀 속성 추가\nplt.plot([10, 20, 30, 40], color='skyblue', label = 'asc') # 증가를 의미하는 asc 범례\nplt.plot([40, 30, 20, 10], 'pink', label = 'desc') # 감소를 의미하는 desc 범례\n\nplt.legend(loc=6) # 그래프에 범례 속성 추가\nplt.show\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 299} id=\"fPvRh6UQ75V6\" executionInfo={\"status\": \"ok\", \"timestamp\": 1623396649267, \"user_tz\": -540, \"elapsed\": 758, \"user\": {\"displayName\": \"\\ub85c\\ubbf9\", \"photoUrl\": \"\", \"userId\": \"13072686141127167034\"}} outputId=\"a9449800-0e0e-4229-afa8-cdb94d426619\"\nplt.title('plotting') # 타이틀 속성 추가\nplt.plot([10, 20, 30, 40], color='r', linestyle = '--', label = 'dash') # 기본 색상은 약어로 표시 가능\nplt.plot([40, 30, 20, 10], 'g', label = 'green')\n\nplt.legend(loc=6) # 그래프에 범례 속성 추가\nplt.show\n\n# + id=\"tEHxIVDK-wPF\"\n\n","repo_name":"Chromis07/dataStudy","sub_path":"python/data_analysis_for_everyone/unit03-서울이 가장 더웠던 날은 언제였을까.ipynb","file_name":"unit03-서울이 가장 더웠던 날은 언제였을까.ipynb","file_ext":"py","file_size_in_byte":6533,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-jupyter-script","pt":"25"} +{"seq_id":"29117830138","text":"# # Data Pre - Processing\n#\n# ### Importing Packages\n\n# +\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport itertools\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nimport matplotlib.pyplot as plt\n# %matplotlib inline \n# -\n\n# ### Loading Data\n\nvehicle = pd.read_csv(\"Group_99.csv\", encoding = \"unicode_escape\")# Loading the data using pandas function.\nprint(vehicle.shape)# gives the dimentions of the data frame.\nvehicle# Displays the data in the data frame.\n\nvehicle.isnull().sum()\n\nvehicle.describe(include = 'all')\n\n# ## Data Modelling\n\n# ### Data Preparation\n# Data is to be prepared for modelling as follows,\n\n# +\nclass_labels = ['Class']\n\nv_class = vehicle[class_labels]\nprint(v_class)\n\nv_levels = vehicle.drop(class_labels, axis = 1)\nnp.unique(vehicle[\"Class\"])\n# -\n\ncor = vehicle.corr()\ncor\n\nfrom sklearn import preprocessing\n\n# The data is not on an standard scale and need to be standardised.\n\nmin_max_scaler = preprocessing.MinMaxScaler()\nv_levels[:] = min_max_scaler.fit_transform(v_levels[:])\nv_levels\n\n# ### Feature Selection using Random forest Classifier\n\nfrom sklearn.ensemble import RandomForestClassifier\nforest = RandomForestClassifier(n_estimators = 100)\nforest.fit(v_levels, v_class.values.ravel())\n\n\n# ### Feature Importance Table based on CLASS\n\ndef feature_importance_report_tree(clf, features):\n feature_importances = zip(features, clf.feature_importances_)\n rows = []\n for f, imp in sorted(feature_importances, key = lambda x : x[1], reverse = True):\n rows.append([f, imp])\n v_rep = pd.DataFrame(rows, columns = ['Feature', 'Relative_Importance'])\n return v_rep\n\n\nClass_imp_for = feature_importance_report_tree(forest, v_levels.columns)\nClass_imp_for = Class_imp_for.rename(columns={\"Relative_Importance\": \"Class_Importance\"})\nClass_imp_for[\"Class_rank\"] = Class_imp_for[\"Class_Importance\"].rank(ascending = 0) \nClass_imp_for\n\n# +\n# %config InlineBackend.figure_format = 'retina'\nplt.style.use(\"ggplot\")\n\ndef plot_imp(best_features, scores, method_name):\n df = pd.DataFrame({'features' : best_features, 'importances' : scores})\n fig, ax = plt.subplots(figsize=(15, 5))\n g = sns.barplot(ax = ax, x = \"features\", y = \"importances\", data = df)\n g.set_xticklabels(ax.get_xticklabels(), rotation = 70)\n\n\n# -\n\nplot_imp(Class_imp_for[\"Feature\"], Class_imp_for[\"Class_Importance\"], 'Random Forest')\n\n# +\nfrom sklearn.model_selection import train_test_split\n\nX_train, x_test, \\\ny_train, y_test = train_test_split(v_levels.values, v_class.values.ravel(), \n test_size = 0.3, random_state = 999,\n stratify = v_class)\n\n# +\nfrom sklearn.model_selection import StratifiedKFold, GridSearchCV\nfrom sklearn import metrics\nfrom sklearn.metrics import precision_recall_curve, classification_report, confusion_matrix\nfrom sklearn.metrics import accuracy_score, make_scorer, recall_score, precision_score, roc_auc_score\n\nv_cross_val = StratifiedKFold(n_splits = 5, random_state = 999, shuffle = True)\n\n# +\nfrom sklearn.base import BaseEstimator, TransformerMixin\n\n# custom function for RFI feature selection inside a pipeline\n# here we use n_estimators=100\nclass RFIFeatureSelector(BaseEstimator, TransformerMixin):\n \n # class constructor \n # make sure class attributes end with a \"_\"\n # per scikit-learn convention to avoid errors\n def __init__(self, n_features_=10):\n self.n_features_ = n_features_\n self.fs_indices_ = None\n\n # override the fit function\n def fit(self, X, y):\n from sklearn.ensemble import RandomForestClassifier\n from numpy import argsort\n model_rfi = RandomForestClassifier(n_estimators=100)\n model_rfi.fit(X, y)\n self.fs_indices_ = argsort(model_rfi.feature_importances_)[::-1][0:self.n_features_] \n return self \n \n # override the transform function\n def transform(self, X, y=None):\n return X[:, self.fs_indices_]\n\n\n# +\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.neighbors import KNeighborsClassifier\n\npipe_KNN = Pipeline(steps=[('rfi_fs', RFIFeatureSelector()), \n ('knn', KNeighborsClassifier())])\n\nparams_pipe_KNN = {'rfi_fs__n_features_': [10, 18, X_train.shape[1]],\n 'knn__n_neighbors': [1, 5, 10, 15],\n 'knn__p': [1]}\n\ngs_pipe_KNN = GridSearchCV(estimator=pipe_KNN, \n param_grid=params_pipe_KNN, \n cv=v_cross_val,\n refit=True,\n #n_jobs=-2,\n n_jobs=None,\n pre_dispatch='2*n_jobs',\n #scoring='accuracy',\n verbose=1) \n# -\n\ngs_pipe_KNN.fit(X_train, y_train);\n\ngs_pipe_KNN.best_params_\n\ngs_pipe_KNN.best_score_\n\n\ndef get_search_results(gs):\n\n def model_result(scores, params):\n scores = {'mean_score': np.mean(scores),\n 'std_score': np.std(scores),\n 'min_score': np.min(scores),\n 'max_score': np.max(scores)}\n return pd.Series({**params,**scores})\n\n models = []\n scores = []\n\n for i in range(gs.n_splits_):\n key = f\"split{i}_test_score\"\n r = gs.cv_results_[key] \n scores.append(r.reshape(-1,1))\n\n all_scores = np.hstack(scores)\n for p, s in zip(gs.cv_results_['params'], all_scores):\n models.append((model_result(s, p)))\n\n pipe_results = pd.concat(models, axis=1).T.sort_values(['mean_score'], ascending=False)\n\n columns_first = ['mean_score', 'std_score', 'max_score', 'min_score']\n columns = columns_first + [c for c in pipe_results.columns if c not in columns_first]\n\n return pipe_results[columns]\n\n\nresults_KNN = get_search_results(gs_pipe_KNN)\nresults_KNN.head()\n\n# +\nresults_KNN_10_features = results_KNN[results_KNN['rfi_fs__n_features_'] == 10.0]\n\nfor i in results_KNN_10_features['knn__p'].unique():\n temp = results_KNN_10_features[results_KNN_10_features['knn__p'] == i]\n plt.plot(temp['knn__n_neighbors'], temp['mean_score'], marker = '.', label = i)\n \nplt.legend(title = \"p\")\nplt.xlabel('Number of Neighbors')\nplt.ylabel(\"AUC Score\")\nplt.title(\"KNN Performance Comparison with 10 Features\")\nplt.show()\n# -\n\n# # Naive Bayes\n\nfrom sklearn.preprocessing import PowerTransformer\nX_train_transformed = PowerTransformer().fit_transform(X_train)\n\n# +\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.model_selection import RandomizedSearchCV\n\npipe_NB = Pipeline([('rfi_fs', RFIFeatureSelector()), \n ('nb', GaussianNB())])\n\nparams_pipe_NB = {'rfi_fs__n_features_': [10, 15, X_train.shape[1]],\n 'nb__var_smoothing': np.logspace(1,-3, num=200)}\n\nn_iter_search = 20\n\ngs_pipe_NB = GridSearchCV(estimator=pipe_NB, \n param_grid=params_pipe_NB, \n cv=v_cross_val,\n refit=True,\n #n_jobs=-2,\n n_jobs=None,\n pre_dispatch='2*n_jobs',\n #scoring='accuracy',\n verbose=1) \n# -\n\ngs_pipe_NB.fit(X_train, y_train)\n\ngs_pipe_NB.best_params_\n\ngs_pipe_NB.best_score_\n\nresults_NB = get_search_results(gs_pipe_NB)\nresults_NB.head()\n\n# +\nresults_NB_10_features = results_NB[results_NB['rfi_fs__n_features_'] == 10.0].sort_values('nb__var_smoothing')\n\nplt.plot(results_NB_10_features['nb__var_smoothing'], results_NB_10_features['mean_score'], marker = '.', label = i) \nplt.xlabel('Var. Smoothing')\nplt.ylabel(\"AUC Score\")\nplt.title(\"NB Performance Comparison with 10 Features\")\nplt.show()\n# -\n\n# # SVC\n\nfrom sklearn.svm import SVC\n\n# +\npipe_SVM = Pipeline([('rfi_fs', RFIFeatureSelector()), \n ('SVM', SVC())])\n\nparams_pipe_SVM = {'rfi_fs__n_features_': [10, 15, X_train.shape[1]],\n 'SVM__C':[0.001,0.1,10,100,10e5], 'SVM__gamma':[0.1,0.01]}\n\nn_iter_search = 20\n\ngs_pipe_SVM = GridSearchCV(estimator=pipe_SVM, \n param_grid=params_pipe_SVM, \n cv=v_cross_val,\n refit=True,\n #n_jobs=-2,\n n_jobs=None,\n pre_dispatch='2*n_jobs',\n #scoring='accuracy',\n verbose=1) \n# -\n\ngs_pipe_SVM.fit(X_train, y_train)\n\ngs_pipe_SVM.best_params_\n\ngs_pipe_SVM.best_score_\n\nresults_SVM = get_search_results(gs_pipe_SVM)\nresults_SVM.head()\n\n# +\nresults_SVM_10_features = results_SVM[results_SVM['rfi_fs__n_features_'] == 10.0].sort_values('SVM__C')\n\nplt.plot(results_SVM_10_features['SVM__C'], results_SVM_10_features['mean_score'], marker = '.', label = i) \nplt.xlabel('Var. Smoothing')\nplt.ylabel(\"AUC Score\")\nplt.title(\"SVM Performance Comparison with 10 Features\")\nplt.show()\n# -\n\n# # Decision Tree\n\nfrom sklearn.tree import DecisionTreeClassifier\n\n# +\npipe_DT = Pipeline([('rfi_fs', RFIFeatureSelector()),\n ('dt', DecisionTreeClassifier(criterion='gini', random_state=111))])\n\nparams_pipe_DT = {'rfi_fs__n_features_': [10, 15, X_train.shape[1]],\n 'dt__max_depth': [3, 4, 5],\n 'dt__min_samples_split': [2, 5]}\n\ngs_pipe_DT = GridSearchCV(estimator=pipe_DT, \n param_grid=params_pipe_DT, \n cv=v_cross_val,\n refit=True,\n #n_jobs=-2,\n #n_jobs=None,\n pre_dispatch='2*n_jobs',\n #scoring='accuracy',\n verbose=1) \n# -\n\npipe_DT.get_params()\n\ngs_pipe_DT.fit(X_train, y_train);\n\ngs_pipe_DT.best_params_\n\ngs_pipe_DT.best_score_\n\n# +\nresults_DT = get_search_results(gs_pipe_DT)\nresults_DT_10_features = results_DT[results_DT['rfi_fs__n_features_'] == 10.0]\n\n\nfor i in results_DT_10_features['dt__max_depth'].unique():\n temp = results_DT_10_features[results_DT_10_features['dt__max_depth'] == i]\n plt.plot(temp['dt__min_samples_split'], temp['mean_score'], marker = '.', label = i)\n \nplt.legend(title = \"Max Depth\")\nplt.xlabel('Min Samples for Split')\nplt.ylabel(\"AUC Score\")\nplt.title(\"DT Performance Comparison with 10 Features\")\nplt.show()\n# -\n\n# ## Further tuning\n\n# +\nparams_pipe_DT2 = {'rfi_fs__n_features_': [10],\n 'dt__max_depth': [5, 10, 15],\n 'dt__min_samples_split': [5, 50, 100, 150]}\n\ngs_pipe_DT2 = GridSearchCV(estimator=pipe_DT, \n param_grid=params_pipe_DT2, \n cv=v_cross_val,\n refit=True,\n #n_jobs=-2,\n n_jobs=None,\n pre_dispatch='n_jobs',\n #scoring='accuracy',\n verbose=1) \n# -\n\ngs_pipe_DT2.fit(X_train, y_train);\n\ngs_pipe_DT2.best_params_\n\ngs_pipe_DT2.best_score_\n\nresults_DT = get_search_results(gs_pipe_DT2)\nresults_DT.head()\n\n# +\nresults_DT_10_features = results_DT[results_DT['rfi_fs__n_features_'] == 10.0].sort_values('dt__min_samples_split')\n\n\nfor i in results_DT_10_features['dt__max_depth'].unique():\n temp = results_DT_10_features[results_DT_10_features['dt__max_depth'] == i]\n plt.plot(temp['dt__min_samples_split'], temp['mean_score'], marker = '.', label = i)\n \nplt.legend(title = \"Max Depth\")\nplt.xlabel('Min Samples for Split')\nplt.ylabel(\"AUC Score\")\nplt.title(\"DT Performance Comparison with 10 Features - Extended\")\nplt.show()\n# -\n\nfrom sklearn.linear_model import LogisticRegression\n\n# +\npipe_LR = Pipeline([('rfi_fs', RFIFeatureSelector()),\n ('logistic', LogisticRegression())])\n\nparams_pipe_LR = {'rfi_fs__n_features_': [10, 15, X_train.shape[1]],\n 'logistic__C': np.logspace(-4, 4, 4)}\n\ngs_pipe_LR = GridSearchCV(estimator=pipe_LR, \n param_grid=params_pipe_LR, \n cv=v_cross_val,\n refit=True,\n #n_jobs=-2,\n n_jobs=None,\n pre_dispatch='2*n_jobs',\n #scoring='accuracy',\n verbose=1) \n# -\n\ngs_pipe_LR.fit(X_train, y_train);\n\ngs_pipe_LR.best_params_\n\ngs_pipe_LR.best_score_\n\nresults_LR = get_search_results(gs_pipe_LR)\nresults_LR.head()\n\n# # Performance Comparison\n\n# +\nfrom sklearn.model_selection import cross_val_score\n\ncv_method_ttest = StratifiedKFold(n_splits = 10)\n\ncv_results_KNN = cross_val_score(estimator = gs_pipe_KNN.best_estimator_,\n X = x_test,\n y = y_test, \n cv = v_cross_val)\ncv_results_KNN.mean()\n\n# +\nx_test_transformed = PowerTransformer().fit_transform(x_test)\n\ncv_results_NB = cross_val_score(estimator = gs_pipe_NB.best_estimator_,\n X = x_test_transformed,\n y = y_test, \n cv = v_cross_val)\ncv_results_NB.mean()\n# -\n\ncv_results_SVM = cross_val_score(estimator = gs_pipe_SVM.best_estimator_,\n X = x_test,\n y = y_test, \n cv = v_cross_val)\ncv_results_SVM.mean()\n\ncv_results_DT2 = cross_val_score(estimator = gs_pipe_DT2.best_estimator_,\n X = x_test,\n y = y_test, \n cv = v_cross_val)\ncv_results_DT2.mean()\n\ncv_results_LR = cross_val_score(estimator = gs_pipe_LR.best_estimator_,\n X = x_test,\n y = y_test, \n cv = v_cross_val)\ncv_results_LR.mean()\n\n# +\nfrom scipy import stats\n\nprint(stats.ttest_rel(cv_results_KNN, cv_results_NB))\nprint(stats.ttest_rel(cv_results_DT2, cv_results_KNN))\nprint(stats.ttest_rel(cv_results_KNN, cv_results_SVM))\nprint(stats.ttest_rel(cv_results_LR, cv_results_KNN))\nprint(stats.ttest_rel(cv_results_DT2, cv_results_SVM))\nprint(stats.ttest_rel(cv_results_DT2, cv_results_NB))\nprint(stats.ttest_rel(cv_results_DT2, cv_results_LR))\nprint(stats.ttest_rel(cv_results_SVM, cv_results_NB))\nprint(stats.ttest_rel(cv_results_SVM, cv_results_LR))\nprint(stats.ttest_rel(cv_results_NB, cv_results_LR))\n# -\n\nfrom sklearn.metrics import confusion_matrix, classification_report\n\n# +\nfrom sklearn import metrics\n\ndef run_classifier(clf, class_labels):\n \n y_pred = clf.predict(x_test)\n \n class_names = set(v_class[class_labels].values) \n \n print('Accuracy on Training data: ', round(clf.score(X_train, y_train), 2))\n \n print('Accuracy on Testing data: ', round(clf.score(x_test_transformed , y_test), 2))\n\n print('Recall value: ', round(metrics.recall_score(y_test, y_pred, average ='macro'), 2))\n\n print('Precision value: ', round(metrics.precision_score(y_test, y_pred, average ='macro'), 2))\n \n print('Classification Report: \\n', classification_report(y_test, y_pred))\n\n\n# -\n\nrun_classifier(gs_pipe_KNN, 'Class')\n\n# +\ny_pred = gs_pipe_NB.predict(x_test)\n \nclass_names = set(v_class['Class'].values) \nprint('Accuracy on Training data: ', round(gs_pipe_NB.score(X_train_transformed, y_train), 2))\nprint('Accuracy on Testing data: ', round(gs_pipe_NB.score(x_test_transformed , y_test), 2))\nprint('Recall value: ', round(metrics.recall_score(y_test, y_pred, average ='macro'), 2))\nprint('Precision value: ', round(metrics.precision_score(y_test, y_pred, average ='macro'), 2))\nprint('Classification Report: ', classification_report(y_test, y_pred))\n# -\n\nrun_classifier(gs_pipe_SVM, 'Class')\n\nrun_classifier(gs_pipe_DT2, 'Class')\n\nrun_classifier(gs_pipe_LR, 'Class')\n\n\ndef plot_confusion_matrix(clf, y_test, classes,\n title = 'Confusion matrix',\n cmap = plt.cm.Blues, normalize=True):\n \n y_pred = clf.predict(x_test)\n \n cm = confusion_matrix(y_test, y_pred)\n np.set_printoptions(precision = 2)\n\n plt.figure()\n fig, ax = plt.subplots(figsize = (9, 7.2))\n plt.rcParams.update({'font.size': 15})\n plt.imshow(cm, interpolation = 'nearest', cmap = cmap)\n plt.title(title)\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation = 45)\n plt.yticks(tick_marks, classes)\n cm = cm.astype('float') / cm.sum(axis = 1)[:, np.newaxis]\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, \"{0:.3f}\".format(cm[i, j]),\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n \n plt.show()\n \n classification_error_rate = 1.0 * sum(1 for (x, y) in zip(y_test, y_pred) if x != y) / len(list(y_test))\n print('Classification Error Rate: ', classification_error_rate)\n\n\nplot_confusion_matrix(gs_pipe_KNN, y_test, np.unique(v_class))\n\nplot_confusion_matrix(gs_pipe_NB, y_test, np.unique(v_class))\n\nplot_confusion_matrix(gs_pipe_SVM, y_test, np.unique(v_class))\n\nplot_confusion_matrix(gs_pipe_DT2, y_test, np.unique(v_class))\n\nplot_confusion_matrix(gs_pipe_LR, y_test, np.unique(v_class))\n\n# +\nModel_Accuracy = pd.DataFrame({'Model' : [ 'Naive_Bayes', 'SVM', 'KNN', 'Decision_Tree', 'Logistic Regression'], \n 'Train_Accuracy' : [round(gs_pipe_NB.score(X_train_transformed, y_train)*100, 2),\n round(gs_pipe_SVM.score(X_train, y_train)*100, 2),\n round(gs_pipe_KNN.score(X_train, y_train)*100, 2),\n round(gs_pipe_DT2.score(X_train, y_train)*100, 2),\n round(gs_pipe_LR.score(X_train, y_train)*100, 2)],\n 'Test_Accuracy' : [round(gs_pipe_NB.score(x_test_transformed, y_test)*100, 2),\n round(gs_pipe_SVM.score(x_test, y_test)*100, 2),\n round(gs_pipe_KNN.score(x_test, y_test)*100, 2),\n round(gs_pipe_DT2.score(x_test, y_test)*100, 2),\n round(gs_pipe_LR.score(X_train, y_train)*100, 2)]})\n\nModel_Accuracy\n","repo_name":"VishalPatnaik/Vehicle-Type-Prediction-Using-Vehicle-Silhouettes","sub_path":".ipynb_checkpoints/Assignment 2-Copy-checkpoint.ipynb","file_name":"Assignment 2-Copy-checkpoint.ipynb","file_ext":"py","file_size_in_byte":18584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"25"} +{"seq_id":"33382811755","text":"# # LAB 6.01 Web Scraping Single Page\n\nfrom bs4 import BeautifulSoup\nimport requests\nimport pandas as pd\n\nurl = \"http://www.popvortex.com/music/netherlands/top-songs.php\"\n\nresponse = requests.get(url)\nresponse.status_code\n\nsoup = BeautifulSoup(response.content, \"html.parser\")\n\nsoup.select(\"#chart-position-1 > div.chart-content.col-xs-12.col-sm-8 > p > cite\")\n\nsoup.select(\"p > cite\")[1].get_text()\n\n# +\nsong = []\n\nnum_iter = len(soup.select(\"p > cite\"))\n\nfor i in range(num_iter):\n song.append(soup.select(\"p > cite\")[i].get_text())\n\nprint(song)\n\ntop100_song = pd.DataFrame({\"song\":song})\n# -\n\ntop100_song.head()\n\nsoup.select(\"#chart-position-1 > div.chart-content.col-xs-12.col-sm-8 > p > em\")\n\nsoup.select(\"p > em\")\n\nsoup.select(\"p > em\")[1].get_text()\n\n# +\nartist = []\n\nn_iter = len(soup.select(\"p > em\"))\n\nfor i in range(n_iter):\n artist.append(soup.select(\"p > em\")[i].get_text())\n\nprint(artist)\n\ntop100_artist = pd.DataFrame({\"artist\":artist})\n# -\n\ntop100_netherlands = pd.concat([top100_artist, top100_song], axis = 1)\ntop100_netherlands\n\n# # LAB 6.02 Web Scraping Multiple Page\n\n# +\nurl = 'http://www.popvortex.com/music/charts/top-100-songs.php'\n\nresponse = requests.get(url)\ndisplay(url,response.status_code)\n# -\n\nsoup = BeautifulSoup(response.content, \"html.parser\")\n\n# +\ntitles = []\nfor title in soup.select(\"cite.title\"):\n titles.append(title.get_text())\n \nartists = []\nfor artist in soup.select(\"em.artist\"):\n artists.append(artist.get_text())\n \ntop100_us = pd.DataFrame({'artist':artists,'title':titles})\ntop100_us.head(60)\n\n# +\n# songs since 00s\n\nurl2010 = 'http://tsort.info/music/ds2010.htm'\nurl2000 = 'http://tsort.info/music/ds2000.htm'\n# -\n\nfor url in [url2010, url2000]:\n response = requests.get(url)\n display(url,response.status_code)\n\nsoup2010 = BeautifulSoup(requests.get(url2010).content, \"html.parser\")\nsoup2000 = BeautifulSoup(requests.get(url2000).content, \"html.parser\")\n\n# +\nartists = []\ntitles = []\nyears = []\n\nfor artist in soup2000.select(\"td.art\"): #Artist\n artists.append(artist.get_text())\n \nfor title in soup2000.select(\"td.tit\"): #Title\n titles.append(title.get_text())\n \nfor year in soup2000.select(\"td.yer\"): #Year\n years.append(year.get_text())\n\nyear2000 = pd.DataFrame({'artist':artists, 'title':titles, 'year':years})\n\n# +\nartists = []\ntitles = []\nyears = []\n\nfor artist in soup2010.select(\"td.art\"): #Artist\n artists.append(artist.get_text())\n \nfor title in soup2010.select(\"td.tit\"): #Title\n titles.append(title.get_text())\n \nfor year in soup2010.select(\"td.yer\"): #Year\n years.append(year.get_text())\n\nyear2010 = pd.DataFrame({'artist':artists, 'title':titles, 'year':years})\n# -\n\ntop100_00s = pd.concat([year2000,year2010], axis = 0)\ntop100_00s\n\n# # Practices \n\n# ## Language\n\n# +\n# Display the top 10 languages by number of native speakers stored in a pandas dataframe\n\nl_url = 'https://en.wikipedia.org/wiki/List_of_languages_by_number_of_native_speakers'\n\nl_response = requests.get(l_url)\nl_response.status_code\n\n# +\n#mw-content-text > div.mw-parser-output > table:nth-child(15) > tbody > tr:nth-child(1) > td:nth-child(2)\n\nl_soup = BeautifulSoup(l_response.content, \"html.parser\")\n# -\n\nspeakers = l_soup.select(\"table.wikitable > tbody > tr > td\")\n\n# +\ncount = 0\n\nrank= []\nlang = []\nspeak = []\npercent = []\nfamily = []\nbranch = []\n\nwhile count < 100:\n rank.append(speakers[count][:-1])\n count = count + 1\n lang.append(speakers[count][:-1])\n count = count + 1\n speak.append(speakers[count][:-1])\n count = count + 1\n percent.append(speakers[count][:-1])\n count = count + 1\n family.append(speakers[count][:-1])\n count = count + 1\n branch.append(speakers[count][:-1])\n count = count + 1\n\n\n# +\nLanguage = []\n\nl_iter = len(l_soup.select(\"td:nth-child(2)\"))\n\nfor i in range(1, 11):\n Language.append(l_soup.select(\"td:nth-child(2)\")[i].get_text())\n\nprint(Language)\n\nl_name = pd.DataFrame({\"language\":Language})\n# -\n\nl_name\n\n# +\n#mw-content-text > div.mw-parser-output > table:nth-child(15) > tbody > tr:nth-child(1) > td:nth-child(3)\n\n# +\n#l_soup.select(\"td:nth-child(3)\")\n\n# +\nyear = []\n\nl_iter = len(l_soup.select(\"td:nth-child(3)\"))\n\nfor i in range(0, 10):\n Language.append(l_soup.select(\"td:nth-child(3)\")[i].get_text())\n\nprint(year)\n\nl_year = pd.DataFrame({\"year\":year})\n\n# +\n#mw-content-text > div.mw-parser-output > table:nth-child(15) > tbody > tr:nth-child(1) > td:nth-child(2)\n# -\n\n# # FBI \n\nurl = 'https://www.fbi.gov/wanted/topten'\nresponse = requests.get(url)\nresponse.status_code \n\nsoup = BeautifulSoup(response.content, \"html.parser\")\n\n# +\nwanted = []\nfor dude in soup.select(\"h3\"):\n wanted.append(dude.get_text().strip())\n\nwanted.pop(10)\nwanted.pop(10)\nwanted\n# -\n\nwanted_fbi = pd.DataFrame({'Names':wanted})\nwanted_fbi\n\n\n","repo_name":"Tekiniggemann/LAb-6.02-Web-Scraping-","sub_path":"LAB 6 Web Scraping.ipynb","file_name":"LAB 6 Web Scraping.ipynb","file_ext":"py","file_size_in_byte":4783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"25"} +{"seq_id":"24477927216","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport math\n\n\ndef fun(x):\n offset_rear = -1\n offset_front = 1\n mu_rear = np.array([-1,0])\n mu_front = np.array([1,0])\n sigmainv_rear = np.array([[1,0],[0,1]])\n sigmainv_front = np.array([[1,0],[0,1]])\n \n #front gauss value\n front = np.exp(-(x-mu_rear)@sigmainv_rear@(x-mu_rear))\n back = np.exp(-(x-mu_front)@sigmainv_front@(x-mu_front))\n return front - back\n\n\n# +\n\nnx = 30\nny = 30\nx = np.linspace(-6, 6, nx)\ny = np.linspace(-6, 6, ny)\nX, Y = np.meshgrid(x, y)\nxre = X.reshape(-1,)\nyre = Y.reshape(-1,)\n\nZvals = np.zeros((nx*ny,))\nfor idx in range(nx*ny):\n Zvals[idx]= fun(np.array([xre[idx], yre[idx]]))\nZ = Zvals.reshape(nx,ny)\nfig = plt.figure()\nax = plt.axes(projection='3d')\nax.contour3D(X, Y, Z, 50, cmap='viridis')\nax.set_xlabel('x')\nax.set_ylabel('y')\nax.set_zlabel('z')\n\nplt.show()\n\n# +\n\nprint(fun(np.array([1,2])))\n# -\n\nxre = X.reshape(-1,)\nXne = xre.reshape(30,30)\n\nXne\n\nX\n\n\n\n","repo_name":"epoxx-arch/mpcc-1","sub_path":"scripts/Notebooks/Untitled.ipynb","file_name":"Untitled.ipynb","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-jupyter-script","pt":"25"} +{"seq_id":"14809943476","text":"# # Adapted from [arXiv:2208.07621](https://arxiv.org/abs/2208.07621)\n\n# 1D Heisenberg Chain:\n# $$\n# H = \\sum_{i,j} J(X_iX_j + Y_iY_j + Z_iZ_j) + \\sum_i (J_x X_i + J_z Z_i)\n# $$\n#\n# Import the necessary tools:\n\nimport pennylane as qml\nimport pennylane.numpy as np\nimport matplotlib.pyplot as plt\nfrom itertools import product\nimport tqdm, scipy\n\n\n# Implement the Hamiltonian:\n\ndef heisenberg_chain_1D(nqubits: int, j: float, jx: float, jz: float) -> qml.Hamiltonian:\n \"\"\"\n 1D Heisenberg Chain with transverse fields\n\n .. math::\n\n H = \\sum_{i,j} J[X_iX_j + Y_iY_j + Z_iZ_j] + \\sum_i [J_x X_i + J_z Z_i]\n\n :param nqubit: number of qubits\n :param jx: J_x parameter\n :param jz: J_z parameter\n \"\"\"\n first_term = []\n first_term_coefs = []\n for nq in range(nqubits - 1):\n first_term.append(qml.PauliX(nq) @ qml.PauliX(nq + 1))\n first_term_coefs.append(j)\n first_term.append(qml.PauliY(nq) @ qml.PauliY(nq + 1))\n first_term_coefs.append(j)\n first_term.append(qml.PauliZ(nq) @ qml.PauliZ(nq + 1))\n first_term_coefs.append(j)\n\n second_term = []\n second_term_coefs = []\n for nq in range(nqubits):\n second_term.append(qml.PauliX(nq))\n second_term_coefs.append(jx)\n second_term.append(qml.PauliZ(nq))\n second_term_coefs.append(jz)\n\n return qml.Hamiltonian(first_term_coefs + second_term_coefs, first_term + second_term)\n\n\n# Fix initial constants:\n\nNQUBITS = 4\nJ = -1\nJX = 0.3\nJZ = 0.2\nBETA = 1.3\nNLAYERS = 3\n\n# Lets check the Hamiltonian:\n\n# +\nH = qml.matrix(heisenberg_chain_1D(NQUBITS, J, JX, JZ))\nplt.imshow(H.real)\nplt.show()\ne = np.linalg.eig(H)[0]\n\nfig = plt.figure(figsize=(1, 5))\nplt.scatter([0.0] * len(e), e, marker=\"_\", s=100)\nplt.ylabel(\"Eigenvalues\")\nplt.xlim([-0.1, 0.1])\nplt.xticks([])\nplt.show()\n\n# +\nvqc1_dev = qml.device(\"default.qubit\", wires=range(4))\n\n\n@qml.qnode(vqc1_dev)\ndef VQC1(params: np.ndarray) -> np.ndarray:\n for nq in range(NQUBITS):\n # from 2208.07621 p4 sec III.1 (minimal entropy circuit)\n qml.RX(params[nq], wires=nq)\n return qml.probs(wires=range(NQUBITS))\n\n\nqml.draw_mpl(VQC1)(np.random.uniform(-1, 1, (NQUBITS,)))\nplt.show()\n\nfig = plt.figure(figsize=(12, 4))\nax = plt.subplot(111)\n\nstates = list(product([0, 1], repeat=NQUBITS))\n\nprobs = VQC1(np.random.uniform(-1, 1, (NQUBITS,)))\n\nax.bar(range(len(states)), probs, width=0.8)\nax.set_xticks(\n range(len(states)),\n labels=[\"$|\" + \"\".join(str(x)[1:-1].split(\",\")) + \"\\\\rangle$\" for x in states],\n minor=False,\n rotation=95,\n fontsize=20,\n)\nax.set_ylabel(\"probabilities\")\nax.minorticks_off()\nplt.show()\n\n# +\nshapes = qml.SimplifiedTwoDesign.shape(NLAYERS, NQUBITS)\n\nvqc2_dev = qml.device(\"default.qubit\", wires=range(NQUBITS))\n\n\ndef VQC2(initial_state: list[int], initial_params: np.ndarray, weights: np.ndarray) -> None:\n qml.BasisStatePreparation(initial_state, wires=range(NQUBITS))\n qml.SimplifiedTwoDesign(\n initial_layer_weights=initial_params, weights=weights, wires=range(NQUBITS)\n )\n\n\n@qml.qnode(vqc2_dev)\ndef circuit(\n initial_state: list[int], initial_params: np.ndarray, weights: np.ndarray, hamil\n) -> np.ndarray:\n VQC2(initial_state, initial_params, weights)\n return qml.expval(hamil)\n\n\nvqc2_dev_state = qml.device(\"default.qubit\", wires=range(NQUBITS))\n\n\n@qml.qnode(vqc2_dev_state)\ndef circuit_state(\n initial_state: list[int], initial_params: np.ndarray, weights: np.ndarray\n) -> np.ndarray:\n VQC2(initial_state, initial_params, weights)\n return qml.state()\n\n\n# -\n\n# $$\n# \\rho = \\sum_i p_i |s_i\\rangle\\langle s_i |; \\\\\n# \\langle \\rho H \\rangle = {\\rm Tr}\\left[\\rho U(\\phi) H U^\\dagger(\\phi)\\right];\\\\\n# {\\rm Tr}\\left[\\rho U(\\phi) H U^\\dagger(\\phi)\\right] = \\sum_i p_i {\\rm Tr}\\left[|s_i\\rangle\\langle s_i| U(\\phi) H U^\\dagger(\\phi)\\right]\n# $$\n\ndef cost(phi1: np.ndarray, phi2: np.ndarray, phi3: np.ndarray, hamil) -> np.ndarray:\n probs = VQC1(phi1)\n\n # QC is a pure state simulator, we need to compute the energy\n # of the mixed state i.e. rho = Sum p_i |s_i> 25 and decay_counter > 25:\n if np.abs(np.min(free_energy[20:]) - free_energy[-1]) < 1e-4:\n decay_counter = 0\n ETA *= 0.5\n\nplt.plot(range(EPOCHS+1), free_energy)\nplt.ylabel(\"free energy\")\nplt.xlabel(\"epoch\")\nplt.show()\n# -\n\n# Construct the mixed state:\n\n# +\nprobs = VQC1(phi1)\n\nstate = np.zeros(shape=(16, 16)).astype(np.complex128)\nfor idx, st in enumerate(product([0, 1], repeat=NQUBITS)):\n if probs[idx] != 0.0:\n current_state = circuit_state(st, phi2, phi3).reshape(-1, 1)\n state += probs[idx] * current_state @ current_state.T.conj()\n# -\n\n# Compare truth and the reconstruction:\n\n# +\nplt.imshow(state.real)\nplt.title(\"reconstructed thermal state\", fontsize=18)\nplt.show()\n\nH = qml.matrix(Hamiltonian)\nexp = scipy.linalg.expm(-BETA * H)\nrho_thermal = exp / np.trace(exp)\n\nentropy = -np.trace(rho_thermal @ scipy.linalg.logm(rho_thermal))\nenergy = np.trace(np.matmul(rho_thermal, H))\nfree_energy = energy - entropy / BETA\nprint(\n f\"Actual free energy : {free_energy.real:.2f}, energy = {energy.real:.2f}, entropy = {entropy.real:.2f}\"\n)\n\nplt.imshow(rho_thermal.real)\nplt.title(\"analytic thermal state\", fontsize=18)\nplt.show()\n\n# +\nH = qml.matrix(Hamiltonian)\nbeta = np.linspace(0.1,3,25)\nfe = []\nfor b in beta:\n\n exp = scipy.linalg.expm(-b * H)\n rho_thermal = exp / np.trace(exp)\n\n entropy = -np.trace(rho_thermal @ scipy.linalg.logm(rho_thermal))\n energy = np.trace(np.matmul(rho_thermal, H))\n free_energy = energy - entropy / b\n fe.append(free_energy)\n\nplt.plot(beta, fe)\nplt.xlabel(\"beta\")\nplt.ylabel(\"free energy\")\nplt.show()\n# -\n\n\n","repo_name":"jackaraz/kias_quc_qml","sub_path":"vqt.ipynb","file_name":"vqt.ipynb","file_ext":"py","file_size_in_byte":6922,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-jupyter-script","pt":"25"} +{"seq_id":"12601025702","text":"import pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\ndata = pd.read_csv(\"Supermart Grocery Sales - Retail Analytics Dataset.csv\")\ndata.head()\n\ndata.shape\n\ndata.info()\n\ndata.describe()\n\ndata['Category'].value_counts()\n\ndata['Sub Category'].value_counts()\n\ndata['Region'].value_counts()\n\n# +\n# Drop north region as it having only one datapoint\n\ndata.drop(data[data['Region'] == 'North'].index, inplace = True )\n# -\n\ndata.head()\n\n# # Data visualization\n\n# Sales by City\ndf1 = data[['City','Sales']]\ndf2 = df1.groupby(['City'])['Sales'].sum()\ndf2 = df2.to_frame()\ndf2 = df2.sort_values('Sales',ascending = False)\ndf2\n\nplt.figure(figsize=(15,8))\nsns.barplot(df2.index,df2['Sales'],palette='hot')\nplt.title(\"City wise Sales\", fontsize=20, color='r')\nplt.xticks(rotation=90)\nplt.show()\n\n# sales by region\ndf3 = data[['Region','Sales']]\ndf4 = df3.groupby(['Region'])['Sales'].sum()\ndf4 = df4.to_frame()\ndf4 = df4.sort_values('Sales',ascending = False)\ndf4\n\nplt.figure(figsize=(15,8))\nsns.barplot(df4.index,df4['Sales'],palette='rocket')\nplt.title(\"Region wise Sales\", fontsize=20, color='r')\nplt.xticks(rotation=90)\nplt.show()\n\n# +\n# sales by category\n\ndf5 = data[['Category', 'Sales']]\ndf6 = df5.groupby(['Category'])['Sales'].sum()\ndf6 = df6.to_frame()\ndf6 = df6.sort_values('Sales',ascending = False )\ndf6\n# -\n\nplt.figure(figsize = (15,8))\nsns.barplot(df6.index, df6['Sales'], palette = 'mako')\nplt.title(\"Sales by category\", fontsize=20, color='g')\nplt.show()\n\n# +\n# profit by region\n\ndf7 = data[['Region','Profit']]\ndf8 = df7.groupby(['Region'])['Profit'].sum()\ndf8 = df8.to_frame()\ndf8 = df8.sort_values('Profit', ascending = False)\ndf8\n# -\n\nplt.figure(figsize = (15,8))\nsns.barplot(df8.index, df8['Profit'], palette='magma')\nplt.title(\"Profit by region\", fontsize=20,color='g')\nplt.show()\n\n# +\n# Extracting year from date\n# -\n\ndata['Year'] = pd.to_datetime(data['Order Date']).dt.year\n\ndata.head()\n\n# +\n# sales per year\n\ndf9 = data[['Year','Sales']]\ndf10 = df9.groupby(['Year'])['Sales'].sum()\ndf10 = df10.to_frame()\ndf10\n# -\n\nplt.figure(figsize=(18,7))\nsns.lineplot(df10.index, df10['Sales'])\nplt.xticks(ticks=[2015,2016,2017,2018])\nplt.title(\"Sales per year\", fontsize=20, color='g')\nplt.grid()\nplt.show()\n\n# +\n# profit per year\n\ndf11 = data[['Year','Profit']]\ndf12 = df11.groupby(['Year'])['Profit'].sum()\ndf12 = df12.to_frame()\ndf12\n# -\n\nplt.figure(figsize=(18,7))\nsns.lineplot(df12.index, df12['Profit'])\nplt.xticks(ticks=[2015,2016,2017,2018])\nplt.title(\"Profit per year\", fontsize=20, color='g')\nplt.grid()\nplt.show()\n\n# +\n# number of orders per year\n\ndf13 = data[['Year','Order ID']]\ndf14 = df13.groupby(['Year'])['Order ID'].count()\ndf14 = df14.to_frame()\ndf14\n# -\n\nplt.figure(figsize=(18,7))\nsns.lineplot(df14.index, df14['Order ID'])\nplt.xticks(ticks=[2015,2016,2017,2018])\nplt.ylabel('Orders')\nplt.title(\"Orders per year\", fontsize=20, color='g')\nplt.grid()\nplt.show()\n\n\n","repo_name":"nikhil-halvankar/Superstore-retail-analysis","sub_path":"Supermart Grocery Sales EDA.ipynb","file_name":"Supermart Grocery Sales EDA.ipynb","file_ext":"py","file_size_in_byte":2923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"25"} +{"seq_id":"5065684625","text":"from sklearn.svm import SVC\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import confusion_matrix, roc_curve, roc_auc_score, recall_score, precision_score, accuracy_score, f1_score, matthews_corrcoef\nimport pandas as pd\nimport numpy as np\nfrom sklearn.datasets import load_breast_cancer\n\ndata = load_breast_cancer()\n\nprint(data.DESCR)\n\nX = data.data\n\ny = data.target\n\nX.shape, y.shape\n\ndata.target_names\n\nmodel = SVC(probability=True, kernel = 'linear', verbose=True)\n\nfrom sklearn.model_selection import train_test_split\nx_train, x_test, y_train, y_test = train_test_split(X, y, test_size=.35)\n\nx_train.shape, x_test.shape, y_train.shape, y_test.shape\n\nmodel.fit(x_train, y_train)\n\ny_pred = model.predict(x_test)\n\ny_proba = model.predict_proba(x_test)\n\nnp.unique(y_test)\n\ny_proba = y_proba[:, 1]\n\nconf = confusion_matrix(y_test, y_pred, labels = [1, 0])\nconf\n\nTP, FN, FP, TN = conf.ravel()\n\nTP, FN, FP, TN\n\nplt.imshow(conf, interpolation='nearest', cmap = plt.cm.Greens)\nplt.title(\"Confusion matrix\")\nplt.xticks([0, 1])\nplt.yticks([0, 1])\nfor i in range(conf.shape[0]):\n for j in range(conf.shape[1]):\n plt.text(j, i, format(conf[i, j]), ha='center', color='white' if i==j else 'black')\nplt.tight_layout()\nplt.xlabel(\"Predicted\")\nplt.ylabel(\"Actual\")\nplt.show()\n\nimport seaborn as sn\nsn.heatmap(conf, annot=True, cmap='Greens')\nplt.xlabel(\"Predicted\")\nplt.ylabel(\"Actual\")\nplt.show()\n\nfrom sklearn.metrics import ConfusionMatrixDisplay\ndisp = ConfusionMatrixDisplay(confusion_matrix=conf)\ndisp.plot()\nplt.show()\n\nresult = {}\n\nresult['accuracy'] = (TP+TN)/(TP+TN+FP+FN)\nresult['accuracy']\n\nresult['precision'] = TP/(TP+FP)\nresult['precision']\n\nresult['recall'] = TP/(TP+FN)\nresult['recall']\n\nresult['f1score'] = 2/((1/result['precision'])+(1/result['recall']))\nresult['f1score']\n\nnum = TP*TN-FP*FN\nden = ((TP+FP)*(TP+FN)*(TN+FP)*(TN+FN))**0.5\nresult['mcc'] = num/den\nresult['mcc']\n\nresult['specificity'] = TN/(TN+FP)\nresult['specificity']\n\nresult['npv'] = TN/(TN+FN)\nresult['npv']\n\nresult\n\nprint(f\"accuracy = {accuracy_score(y_test, y_pred)}\")\nprint(f\"precision = {precision_score(y_test, y_pred)}\")\nprint(f\"recall = {recall_score(y_test, y_pred)}\")\nprint(f\"f1score = {f1_score(y_test, y_pred)}\")\nprint(f\"MCC = {matthews_corrcoef(y_test, y_pred)}\")\nprint(f\"Specificity = {recall_score(y_test, y_pred, pos_label=0)}\")\nprint(f\"npv = {precision_score(y_test, y_pred, pos_label=0)}\")\n\nFPR, TPR, _ = roc_curve(y_test, y_proba)\n\nsn.lineplot(x = FPR, y = TPR, label='predicted data')\nsn.lineplot(x = [0,1], y=[0,1], linestyle='--', label='mean')\nplt.title(\"ROC Curve\")\nplt.xlabel(\"FPR\")\nplt.ylabel(\"TPR\")\nplt.show()\n\nrand_proba = np.random.random(size=(y_proba.shape))\nFPR, TPR, _ = roc_curve(y_test, rand_proba)\n\nsn.lineplot(x = FPR, y = TPR, label='predicted data')\nsn.lineplot(x = [0,1], y=[0,1], linestyle='--', label='mean')\nplt.title(\"ROC Curve\")\nplt.xlabel(\"FPR\")\nplt.ylabel(\"TPR\")\nplt.show()\n\nroc_auc_score(y_test, y_proba)\n\nroc_auc_score(y_test, rand_proba)\n\n\n","repo_name":"Shades-en/ML-Labs","sub_path":"confusion matrix.ipynb","file_name":"confusion matrix.ipynb","file_ext":"py","file_size_in_byte":2979,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"25"} +{"seq_id":"23097475642","text":"# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"sJP7O6HyWJRx\" outputId=\"4f9677c7-6eb9-405e-b2ab-9f76545291ca\"\n# !pip install wandb pmdarima -q\n\n# + id=\"8ROq-WDpVyQ-\"\nimport warnings\nimport math\nimport wandb\nimport numpy as np\nimport pandas as pd\nimport datetime as dt\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nfrom datetime import date, timedelta\nfrom datetime import datetime\nfrom collections import defaultdict\nfrom pmdarima.arima import auto_arima, AutoARIMA\nfrom pmdarima.arima.utils import ndiffs\nfrom pmdarima.pipeline import Pipeline\nfrom pmdarima.preprocessing import BoxCoxEndogTransformer, LogEndogTransformer\nfrom statsmodels.graphics.tsaplots import plot_acf, plot_pacf\nfrom statsmodels.tsa.stattools import adfuller\nfrom statsmodels.tools.eval_measures import rmse, aic\nfrom statsmodels.tsa.statespace.sarimax import SARIMAX\n\npd.options.display.max_rows = 500\nwarnings.filterwarnings('ignore')\n\n\n# + id=\"7Fl5a0OtXyvp\"\ndef plot_features(df, cols, title):\n fig, ax = plt.subplots(figsize=(20, 4))\n df.set_index('Date').plot(ax=ax)\n ax.set_title(title)\n ax.set_xlabel('Date')\n ax.set_ylabel('Value')\n plt.legend(cols)\n plt.axhline(0, linestyle='--', color='k', alpha=0.3)\n plt.show()\n\n\n# + id=\"VeOYLM9OXz1x\"\ndef adfuller_test(ip_dict, signif=0.05, name='', verbose=False):\n \"\"\"Perform ADFuller to test for Stationarity of given series and print report\"\"\"\n def adjust(val, length=6): return str(val).ljust(length)\n res = pd.DataFrame()\n for key in ip_dict.keys():\n series = ip_dict[key][name]\n r = adfuller(series, autolag='AIC')\n output = {\n 'column': key,\n 'signif': signif,\n 'test_statistic': round(r[0], 4),\n 'n_obs': r[3],\n 'pvalue': round(r[1], 4),\n 'n_lags': round(r[2], 4)\n }\n\n p_value = output['pvalue']\n for key, val in r[4].items():\n output[f'critical value {adjust(key)}'] = round(val, 3)\n\n if p_value <= signif:\n output['stationary'] = True\n else:\n output['stationary'] = False\n\n res = pd.concat([res, pd.DataFrame(output, index=[0])], axis=0)\n return res\n\n\n# + id=\"ngzolyJHVyRH\"\n# Read the datasets\ndata = pd.read_csv(\"./data/train.csv\")\nsample_submission = pd.read_csv(\"./data/sample_submission.csv\")\n\n# + id=\"ncpG0yJoVyRJ\"\n# Concatecate `StateCode` and `StationId` with '-' as separator\ndata[\"StateStation\"] = data[\"StateCode\"] + \"_\" + data[\"StationId\"].astype(str)\ndata['Date'] = pd.to_datetime(data['Date'], format='%Y-%m-%d')\ndata[\"month_year\"] = data[\"Date\"].apply(lambda x: dt.datetime.strftime(x, \"%Y-%m\"))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 248} id=\"acakJJGyVyRK\" outputId=\"2af70d42-1b41-4523-ee5d-9393c3f7aa46\"\ndata.head()\n\n# + id=\"KggO6JS_VyRM\"\naqi = defaultdict(lambda: pd.DataFrame())\nfor code in data.StateStation.unique():\n aqi[code] = data[data.StateStation == code][['Date', 'AQI']]\n aqi[code].reset_index(drop=True, inplace=True)\n aqi[code].sort_values(by=['Date'], inplace=True)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"KPzgGGeTVyRO\" outputId=\"01edb040-4849-4ec3-acbd-7cfef575295a\"\naqi.keys()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 204} id=\"4qViNKkSVyRR\" outputId=\"f3d72262-5d4e-4afb-803d-8318fe5e350e\"\naqi['AS_4'].head()\n\n# + id=\"MH4FTzdGMyjj\"\nimport pickle\n\n# + id=\"EVRVZ3cUM2m4\"\nmodel_pkl = pickle.load(open('./data/arima_boxcox.pkl', 'rb'))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 91} id=\"EJ6Y621pM2hy\" outputId=\"d90a567d-9c7d-411c-e868-e5bb522b3610\"\nmodel_pkl\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 1000} id=\"fdticXo6QrlK\" outputId=\"0062d7f2-1e7f-4f50-d2c4-eed8a83bab57\"\naqi['AS_4']\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"GV-2LYNSMY8g\" outputId=\"530133e9-d995-410f-97db-64d068353fbb\"\nmodel_pkl.predict(28)\n\n# + id=\"BU0w9X3tdirt\"\nadf_df = adfuller_test(aqi, name='AQI')\n\n# + id=\"AzDMZYVLX5DX\"\nndiff = list()\nfor col in adf_df['column']:\n res = ndiffs(aqi[col]['AQI'], test='adf')\n ndiff.append(res)\nadf_df['ndiff'] = ndiff\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 1000} id=\"QS4J_DhnVyRS\" outputId=\"e5ca74d8-c3a3-42c6-b7ce-703869f67b1c\"\nadf_df\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 421} id=\"576GMjVl2HY5\" outputId=\"7677db7f-52e0-4b50-9b8c-ac8d7a157301\"\nplot_features(aqi['AS_4'], ['AQI'], 'AQI')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"nrWJ6TRV9ije\" outputId=\"9805b8a6-a467-49f3-8c92-42f1dd6f7d83\"\n# start date\n# start_date = datetime.strptime(, \"%Y-%m-%d\")\n# start_date\nprint(aqi['AS_4'].Date.iloc[-1].date())\nstart_date = (aqi['AS_4'].Date.iloc[-1].date() + timedelta(days=1)).isoformat()\nend_date = (aqi['AS_4'].Date.iloc[-1].date() + timedelta(days=28)).isoformat()\n\n# end_date = datetime.strptime(\"2022-12-31\", \"%Y-%m-%d\")\n\n# # difference between each date. D means one day\nD = 'D'\n\ndate_list = pd.date_range(start_date, end_date, freq=D)\ndate_list\n\n# + id=\"PGw6zOBqR9tw\"\n# pipeline = Pipeline([\n# (\"boxcox\", LogEndogTransformer()),\n# (\"model\", AutoARIMA(start_p=7, start_q=1, d=None, max_p=10, max_q=3, max_d=1, trace=False, suppress_warnings=True, n_fits=40, n_jobs=-1))\n# ])\n# pipeline.fit(aqi['AS_4'].AQI)\n\n# + id=\"6eoMEXYZTGM3\"\n# pipeline.predict(28)\n\n# + id=\"zhWtwOmVSHWo\"\n# pipeline.predict(28)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"CKipS-AT8vG5\" outputId=\"cba68762-e7b2-4162-9ade-036bc2f670a8\"\nres = pd.DataFrame(columns=['ID_Date', 'AQI'])\npred_days = 28\n\n# model_dict = dict()\n# model_dict_new = dict()\nmodel_dict_latest = dict()\nfor code, df in aqi.items():\n print(f\"Working on {code} ...\")\n \n df.dropna(inplace=True)\n\n pipeline = Pipeline([\n (\"boxcox\", LogEndogTransformer()),\n (\"model\", AutoARIMA(start_p=7, start_q=1, d=None, max_p=10, max_q=3, max_d=1, trace=False, suppress_warnings=True, n_fits=50, n_jobs=-1))\n ])\n\n pipeline.fit(df['AQI'])\n # model = AutoARIMA(df['AQI'], start_p=7, start_q=1, d=None, max_p=10, max_q=3, max_d=1, start_P=0, start_Q=0, D=0, max_P=0, max_Q=0, max_D=0, m=1, seasonal=True, \\\n # trace=False, error_action='warn', suppress_warnings=True, random_state = 42, n_fits=40, n_jobs=-1)\n # model = auto_arima(df['AQI'], trace=False, error_action='warn', suppress_warnings=True, n_fits=40, n_jobs=-1)\n \n # model_dict_latest[code] = model\n\n start_date = (df.Date.iloc[-1].date() + timedelta(days=1)).isoformat()\n end_date = (df.Date.iloc[-1].date() + timedelta(days=28)).isoformat()\n\n date_list = pd.date_range(start_date, end_date, freq='D')\n date_list = [code + '_' + str(day) for day in date_list]\n \n yhat = pipeline.predict(n_periods=pred_days)\n\n res = pd.concat([res, pd.DataFrame({'ID_Date': date_list, 'AQI': yhat})])\n \nres.reset_index(drop=True, inplace=True)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"YUA16zsY_fTb\" outputId=\"3f358d57-a340-4943-a120-b31871b32d89\"\nres.shape\n\n# + id=\"G-i9RppVBqzV\"\nres.ID_Date = res.ID_Date.map(lambda x: x.split()[0])\nres.to_csv(\"submission.csv\", index=False)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"zPCk3x_MENnf\" outputId=\"671c58ab-2a3e-4c1a-a66a-066825f68c64\"\nfor key in model_dict.keys():\n print(key, model_dict[key].order == model_dict_latest[key].order)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 74} id=\"Lh4s5C0NENUx\" outputId=\"ec6f280e-ad1d-48f1-ae8a-d5a50c4bb684\"\nmodel_dict['AS_4']\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 74} id=\"ZBayV71lEM6D\" outputId=\"89e56cc8-6354-48db-a13d-876fb46f60be\"\nmodel_dict_latest['AS_4']\n\n# + id=\"8kZ2jkZwJuWG\"\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"hujP3e2nc-fQ\" outputId=\"7db5303a-4b13-48de-a264-47f9662a0452\"\nmodel = auto_arima(aqi['AS_4']['AQI'], start_p=4, start_q=1, d=None, max_p=8, max_q=3, max_d=1, start_P=0, start_Q=0, D=0, max_P=0, max_Q=0, max_D=0, m=1, seasonal=True, \\\n trace=True, error_action='warn', suppress_warnings=True, random_state = 42, n_fits=40, n_jobs=-1)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 465} id=\"nNDW2nYP32S7\" outputId=\"ab221c3c-9c85-49b0-9584-97c994e5a287\"\nmodel.summary()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"3Z_7VovK7Uwh\" outputId=\"2a857dee-5c11-4b3d-b138-bbc74be03a61\"\nmodel.predict(n_periods=28)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"cTjg6EvR8EvT\" outputId=\"6671720b-3b40-4d46-991e-a87445ccb1d8\"\n\n\n# + id=\"6KWEVlD78gvA\"\n\n","repo_name":"sagar118/H2O-Hackathon-AQI-Prediction","sub_path":"notebooks/SARIMA.ipynb","file_name":"SARIMA.ipynb","file_ext":"py","file_size_in_byte":8507,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-jupyter-script","pt":"25"} +{"seq_id":"70623780545","text":"# +\n# Dependencies\nimport requests\nfrom pprint import pprint\nfrom config import api_key\n\nurl = \"https://api.nytimes.com/svc/search/v2/articlesearch.json?\"\n# -\n\n# Search for articles that mention granola\nquery = \"granola\"\n\n# Build query URL\nurl = url + \"q=\" + query + \"&api-key=\" + api_key\nprint(url)\n\n# Request articles\nresponse = requests.get(url).json()\n# The \"response\" property in articles contains the actual articles\narticles_list = [article for article in response[\"response\"][\"docs\"]]\nprint(response)\n# list comprehension\n\n# Print the web_url of each stored article\nprint(articles_lists)\n\n\n\n\n","repo_name":"fareenamughal/World_Weather_Analysis","sub_path":"06-APIs/1/Activities/02-Ins_NYTAPI/Unsolved/.ipynb_checkpoints/Ins_NYT_API-checkpoint.ipynb","file_name":"Ins_NYT_API-checkpoint.ipynb","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"25"} +{"seq_id":"44492124396","text":"import pandas as pd\n\nbtc_hourly = pd.read_csv('Data_Coin_price/btc_hourly.csv')\neth_hourly = pd.read_csv('Data_Coin_price/eth_hourly.csv')\ndoge_hourly = pd.read_csv('Data_Coin_price/doge_hourly.csv')\n\nbtc_daily = pd.read_csv('Data_Coin_price/btc_daily.csv')\neth_daily = pd.read_csv('Data_Coin_price/eth_daily.csv')\ndoge_daily = pd.read_csv('Data_Coin_price/doge_daily.csv')\n\n# Manipulate daily data\n# - Transform to datetime format\n# - Rename the columns\n\nbtc_daily= btc_daily[(btc_daily['datetime']>='2021-01-01') & (btc_daily['datetime']<'2022-01-01')]\nbtc_daily['datetime'] = pd.to_datetime(btc_daily['datetime']).dt.date\nbtc_daily.rename(columns={\"closePriceUsd\": \"BTCUSD_close\", \"highPriceUsd\": \"BTCUSD_high\",\n \"lowPriceUsd\": \"BTCUSD_low\", \"openPriceUsd\": \"BTCUSD_open\"}, inplace=True)\nbtc_daily.tail()\n\neth_daily= eth_daily[(eth_daily['datetime']>='2021-01-01') & (eth_daily['datetime']<'2022-01-01')]\neth_daily['datetime'] = pd.to_datetime(eth_daily['datetime']).dt.date\neth_daily.rename(columns={\"closePriceUsd\": \"ETHUSD_close\", \"highPriceUsd\": \"ETHUSD_high\",\n \"lowPriceUsd\": \"ETHUSD_low\", \"openPriceUsd\": \"ETHUSD_open\"}, inplace=True)\neth_daily.tail()\n\ndoge_daily= doge_daily[(doge_daily['datetime']>='2021-01-01') & (doge_daily['datetime']<'2022-01-01')]\ndoge_daily['datetime'] = pd.to_datetime(doge_daily['datetime']).dt.date\ndoge_daily.rename(columns={\"closePriceUsd\": \"DOGEUSD_close\", \"highPriceUsd\": \"DOGEUSD_high\",\n \"lowPriceUsd\": \"DOGEUSD_low\", \"openPriceUsd\": \"DOGEUSD_open\"}, inplace=True)\ndoge_daily.head()\n\n#Combine daily data\ndaily_prices = btc_daily.merge(eth_daily, on='datetime').merge(doge_daily, on='datetime')\n\ndaily_prices = daily_prices.set_index('datetime')\n\ndaily_prices.to_csv('Coin_price_cleaned_daily.csv')\n\ndaily_prices\n\n\n\n\n\n# Manipulate hourly data\n# - Transform to datetime format and remove timezone information\n# - Rename the columns\n\nbtc_hourly['datetime'] = pd.to_datetime(btc_hourly['datetime']).dt.tz_localize(None)\nbtc_hourly.rename(columns={\"closePriceUsd\": \"BTCUSD_close\", \"highPriceUsd\": \"BTCUSD_high\",\n \"lowPriceUsd\": \"BTCUSD_low\", \"openPriceUsd\": \"BTCUSD_open\"}, inplace=True)\nbtc_hourly= btc_hourly[(btc_hourly['datetime']>='2021-01-01') & (btc_hourly['datetime']<'2022-01-01 00:00:00')]\nbtc_hourly.head()\n\neth_hourly['datetime'] = pd.to_datetime(eth_hourly['datetime']).dt.tz_localize(None)\neth_hourly.rename(columns={\"closePriceUsd\": \"ETHUSD_close\", \"highPriceUsd\": \"ETHUSD_high\",\n \"lowPriceUsd\": \"ETHUSD_low\", \"openPriceUsd\": \"ETHUSD_open\"}, inplace=True)\neth_hourly= eth_hourly[(eth_hourly['datetime']>='2021-01-01') & (eth_hourly['datetime']<'2022-01-01 00:00:00')]\neth_hourly.head()\n\ndoge_hourly['datetime'] = pd.to_datetime(doge_hourly['datetime']).dt.tz_localize(None)\ndoge_hourly.rename(columns={\"closePriceUsd\": \"DOGEUSD_close\", \"highPriceUsd\": \"DOGEUSD_high\",\n \"lowPriceUsd\": \"DOGEUSD_low\", \"openPriceUsd\": \"DOGEUSD_open\"}, inplace=True)\ndoge_hourly= doge_hourly[(doge_hourly['datetime']>='2021-01-01') & (doge_hourly['datetime']<'2022-01-01 00:00:00')]\ndoge_hourly.head()\n\n#Combine hourly data, it has missing data\nhourly_prices = btc_hourly.merge(eth_hourly, on='datetime').merge(doge_hourly, on='datetime')\nhourly_prices = hourly_prices.set_index('datetime')\n\nhourly_prices.info()\n\nhourly_prices.to_csv('Coin_price_cleaned_hourly.csv')\n\n\n\n\n\n\n\n# Check missing data\n\nx = doge_hourly.groupby('datetime').count().reset_index()\n\nx['day'] = pd.to_datetime(x['datetime']).dt.date\n\ny = x.groupby('day').count()\ny\n\ny[y['datetime']<24]\n\n\n","repo_name":"yantkumich/siads592-fomo","sub_path":"Data/Coin_price_cleaned_combiner.ipynb","file_name":"Coin_price_cleaned_combiner.ipynb","file_ext":"py","file_size_in_byte":3636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"25"} +{"seq_id":"73588390785","text":"# # Introduction to ML\n\n# Coding Gradient Descent\n\nimport numpy as np\n\nimport matplotlib.pyplot as plt\n\nX = np.arange(10) #Gives an array from digits 0 to 9\nprint(X)\n\nY = (X-5)**2\nprint(Y)\n\nplt.plot(X, Y)\nplt.show()\n\n# Algorithm for Gradient Descent:\n\nx = np.random.randint(10)\nprint(x)\n\n# +\nx = 0\nsteps = 1\nlearning_rate = 0.1\n\nplt.plot(X,Y)\n\nwhile(steps <= 100) :\n x = x - learning_rate*2*(x-5)\n error = ((x-5)**2)\n plt.scatter(x,error)\n print(\"Value: {} Error: {}\".format(x, error))\n steps += 1\n \nplt.show() \n# -\n\n# # Dataset Preparation\n\n# Generating a random dataset (X-One feature) and Y-Predicted value\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nX = np.random.randn(100) #Generates 100 points of normal distribution\n\nY = (2*X) + 5\n\nplt.scatter(X,Y)\nplt.show()\n\n# To create a dataset we will add some random noise to each point to scatter them from the ideal line\n\ne = np.random.randn(100)\nY = 2*X + 5 + 0.5*e\n\nplt.scatter(X,Y)\nplt.xlabel(\"House Area\")\nplt.ylabel(\"Prices\")\nplt.show()\n\n\n# # Normalise the Dataset\n\n# We now need to figure out the line of this dataset.\n# We have to lern the value of theta where theta is a vector\n# theta = [01, 02]\n\n# Loss Function:E = Sum((Y'i - Yi)** 2)\n#\n# dE/d01 = Sum(2*(Y'i - Yi))\n#\n# dE/d02 = Sum(2*(Y'i - Yi)) * d(Y'i)/d01\n# where d(Y'i)/d01 = X\n#\n# Thus, dE/d02 = Sum(2*(Y'i - Yi)) * X\n#\n# Hence,\n# 01 = 01 - n * dE/d01\n# 02 = 02 - n * dE/d02\n\n# We can visualize it as a 3D graph with Error, 01 and 02 as axis in which a 3D bowl will be created and we will slide down to the minima of the bowl \n\ndef gradient(X,Y,theta):\n \n m = X.shape[0] #Gives the number of training points\n grad = np.zeros((2,))\n \n for i in range(X.shape[0]):\n Yi = theta[1]*X[i] + theta[0]\n grad[0] += 2*(Yi - Y[i])\n grad[1] += 2*(Yi - Y[i])*X[i]\n \n return grad\n\n\ndef total_error(X,Y,theta):\n \n m = X.shape[0]\n e = 0\n for i in range(m):\n Yi = theta[1]*X[i] + theta[0]\n e += (Yi - Y[i])**2\n \n return e\n\n\ndef gradientdescent (X, Y, learning_rate = 0.001, max_steps = 50) :\n \n theta = np.zeros((2,))\n error_list = []\n \n for i in range(max_steps):\n #Update theta\n grad = gradient(X, Y, theta)\n theta[0] = theta[0] - learning_rate * grad[0]\n theta[1] = theta[1] - learning_rate * grad[1]\n error = total_error(X,Y,theta)\n \n error_list.append(error)\n \n return theta, error_list\n\n\ntheta,error_list = gradientdescent (X, Y)\n\nprint(theta)\n\nplt.scatter(X,Y)\nplt.show()\n\nplt.plot(error_list)\nplt.show()\n\nimport time\n\n\ndef gradientdescent_animation (X, Y, learning_rate = 0.001, max_steps = 50) :\n \n theta = np.zeros((2,))\n error_list = []\n m = X.shape[0]\n colors = ['red', 'blue', 'green', 'orange', 'purple', 'yellow']\n clr = 0\n \n for i in range(max_steps):\n #Update theta\n values = []\n grad = gradient(X, Y, theta)\n theta[0] = theta[0] - learning_rate * grad[0]\n theta[1] = theta[1] - learning_rate * grad[1]\n for k in range(m):\n fx = theta[1] * X[k] + theta[0] \n values.append(fx)\n #fig = plt.figure()\n plt.scatter(X,Y)\n plt.plot(X, values, color = colors[clr])\n plt.show()\n time.sleep(1)\n plt.cla()\n plt.clf()\n plt.close('all')\n error = total_error(X,Y,theta)\n error_list.append(error)\n \n if clr > 4:\n clr = 0\n else:\n clr += 1\n \n \n plt.show()\n \n return theta, error_list\n\n# Multivariate Regression\n#\n# Problems involving many features\n\n# y = 00 + 01X1 + 02X2 + 03X3 (Scalar)\n#\n# 0 = [ 00 01 02 03 ]\n#\n# X(') = [ 1\n# X(')1\n# X(')2\n# X(')3 ]\n#\n# Y = transpose(0) * X\n# (1 X 4) * (4 X 1)\n# \n# NOTE: Avoid loops for multiplication, instead use np.dot() as it uses multiplt cores, reducing the time taken \n#\n\n# Y'(i) = SUM(0j * X(i)j)\n# where X(i)j = 1 if j == 0\n# \n# Loss, E = SUM( (Y'(i) - Y(i))** 2 )\n#\n# dE/d0j = SUM (2 * (Y'(i) - Y(i)) * X(i)j )\n#\n# 0 = np.zeros(n)\n# while ()\n#\n# for j in range(n):\n# 0j = 0j- n. dE/d0j\n# = 0j- n. SUM (2 * (Y'(i) - Y(i)) * X(i)j )\n# \n# \n# GRADIENT DESCENT \n# Better Minima than Stochastic\n#\n# - Mini Batch Gradent Descent\n# - Stochastic Gradient Descent\n# \n# \n# Stochastic : Gradient for ith example\n# Batch Size = 1\n# Update theta\n# 0j = 0j- n. gradient\n# Faster Convergence \n# \n# Mini Batch : Gradient for random batch of points\n# Update theta\n# 0j = 0j- n. gradient\n# \n# \n# \n# Stochastic can go wrong with a point that may be noise\n# Practically, mini batch is most preffered\n\nplt.plot(error_list[47:])\nplt.show()\n\n\n\n\n","repo_name":"AbhayKaushik/Code","sub_path":"Introduction to ML.ipynb","file_name":"Introduction to ML.ipynb","file_ext":"py","file_size_in_byte":4993,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"25"} +{"seq_id":"39977163832","text":"# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# \"Open\n\n# + id=\"mr81hj-s5qzj\" colab_type=\"code\" outputId=\"0c124fbb-74ff-43dd-c467-f634cc07cf33\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 128}\nfrom google.colab import drive\ndrive.mount('/content/drive')\n\n# + id=\"RovYwkxx6ng6\" colab_type=\"code\" outputId=\"6a968125-03ad-443f-a928-3fd25c92384d\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 145}\n#run this in the first time\n# !mkdir logs\n# !cp -r '/content/drive/My Drive/colab/recomendation/datset/.' '/content/'\n# !tar -xvf nf_prize_dataset.tar.gz\n# !mkdir data\n# !tar -C /content/data -xf download/training_set.tar\n# !rm -r download\n# !mkdir output\n# !mkdir netflix_data\n\n# + [markdown] id=\"JBwwB1khrspN\" colab_type=\"text\"\n# ###Preprocessing the data\n\n# + id=\"7BJIYTZb-5YI\" colab_type=\"code\" outputId=\"59304907-83b2-40a4-a259-323051bdfa14\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 35}\nfrom os import listdir, path, makedirs\nimport random\nimport sys\nimport time\nimport datetime\nimport csv\nimport keras # imports keras and tensorflow as backend\nimport matplotlib.pyplot as plt # imports matplotlib\nimport numpy as np\nimport pandas as pd\n# %matplotlib inline\nimport os\nimport time\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation\nfrom keras.callbacks import TensorBoard\nfrom keras import optimizers\nimport keras.backend as K\n\n\n# + id=\"YRUJ6cXWAYnX\" colab_type=\"code\" colab={}\ndef print_stats(data):\n total_ratings = 0\n print(\"STATS\")\n for user in data:\n total_ratings += len(data[user])\n print(\"Total Ratings: {}\".format(total_ratings))\n print(\"Total User count: {}\".format(len(data.keys())))\n \n \ndef save_data_to_file(data, filename):\n with open(filename, 'w') as out:\n for userId in data:\n for record in data[userId]:\n out.write(\"{}\\t{}\\t{}\\n\".format(userId, record[0], record[1]))\n\ndef create_NETFLIX_data_timesplit(all_data,\n train_min,\n train_max,\n test_min,\n test_max):\n \"\"\"\n Creates time-based split of NETFLIX data into train, and (validation, test)\n :param all_data:\n :param train_min:\n :param train_max:\n :param test_min:\n :param test_max:\n :return:\n \"\"\"\n train_min_ts = time.mktime(datetime.datetime.strptime(train_min,\"%Y-%m-%d\").timetuple())\n train_max_ts = time.mktime(datetime.datetime.strptime(train_max, \"%Y-%m-%d\").timetuple())\n test_min_ts = time.mktime(datetime.datetime.strptime(test_min, \"%Y-%m-%d\").timetuple())\n test_max_ts = time.mktime(datetime.datetime.strptime(test_max, \"%Y-%m-%d\").timetuple())\n\n training_data = dict()\n validation_data = dict()\n test_data = dict()\n\n train_set_items = set()\n\n for userId, userRatings in all_data.items():\n time_sorted_ratings = sorted(userRatings, key=lambda x: x[2]) # sort by timestamp\n for rating_item in time_sorted_ratings:\n if rating_item[2] >= train_min_ts and rating_item[2] <= train_max_ts:\n if not userId in training_data:\n training_data[userId] = []\n training_data[userId].append(rating_item)\n train_set_items.add(rating_item[0]) # keep track of items from training set\n elif rating_item[2] >= test_min_ts and rating_item[2] <= test_max_ts:\n if not userId in training_data: # only include users seen in the training set\n continue\n p = random.random()\n if p <=0.5:\n if not userId in validation_data:\n validation_data[userId] = []\n validation_data[userId].append(rating_item)\n else:\n if not userId in test_data:\n test_data[userId] = []\n test_data[userId].append(rating_item)\n\n # remove items not not seen in training set\n for userId, userRatings in test_data.items():\n test_data[userId] = [rating for rating in userRatings if rating[0] in train_set_items]\n for userId, userRatings in validation_data.items():\n validation_data[userId] = [rating for rating in userRatings if rating[0] in train_set_items]\n\n return training_data, validation_data, test_data\n\n\n# + id=\"-v1UDViYZKlj\" colab_type=\"code\" colab={}\n\nuser2id_map = dict()\nitem2id_map = dict()\nuserId = 0\nitemId = 0\nall_data = dict()\n\nfolder = 'data/training_set/'\nout_folder = 'netflix_data'\n# create necessary folders:\nfor output_dir in [(out_folder + f) for f in [\n \"/N6M_TRAIN\", \"/N6M_VALID\", \"/N6M_TEST\"]]:\n makedirs(output_dir, exist_ok=True)\n\ntext_files = [path.join(folder, f)\n for f in listdir(folder)\n if path.isfile(path.join(folder, f)) and ('.txt' in f)]\ni = 0\nfor text_file in text_files:\n i = i+1\n if i>11000:\n with open('netflix_data/dict.csv', 'w') as csv_file:\n writer = csv.writer(csv_file)\n for key, value in all_data.items():\n writer.writerow([key, value], delimiter=':')\n all_data.clear()\n with open(text_file, 'r') as f:\n print(\"Processing: {}\".format(text_file))\n lines = f.readlines()\n item = int(lines[0][:-2]) # remove newline and :\n if not item in item2id_map:\n item2id_map[item] = itemId\n itemId += 1\n\n for rating in lines[1:]:\n parts = rating.strip().split(\",\")\n user = int(parts[0])\n if not user in user2id_map:\n user2id_map[user] = userId\n userId += 1\n rating = float(parts[1])\n ts = int(time.mktime(datetime.datetime.strptime(parts[2],\"%Y-%m-%d\").timetuple()))\n if user2id_map[user] not in all_data:\n all_data[user2id_map[user]] = []\n all_data[user2id_map[user]].append((item2id_map[item], rating, ts))\n\nwith open('netflix_data/dict2.csv', 'w') as csv_file:\n writer = csv.writer(csv_file)\n for key, value in all_data.items():\n writer.writerow([key, value])\n\n\n# + id=\"2BFlR40p0Gld\" colab_type=\"code\" colab={}\n(n6m_train, n6m_valid, n6m_test) = create_NETFLIX_data_timesplit(all_data,\n \"2005-06-01\",\n \"2005-11-30\",\n \"2005-12-01\",\n \"2005-12-31\")\nprint(\"Netflix 6m train\")\nprint_stats(n6m_train)\nsave_data_to_file(n6m_train, out_folder+\"/N6M_TRAIN/n6m.train.txt\")\nprint(\"Netflix 6m valid\")\nprint_stats(n6m_valid)\nsave_data_to_file(n6m_valid, out_folder + \"/N6M_VALID/n6m.valid.txt\")\nprint(\"Netflix 6m test\")\nprint_stats(n6m_test)\nsave_data_to_file(n6m_test, out_folder + \"/N6M_TEST/n6m.test.txt\")\n\n# + id=\"fwRPCvMRresk\" colab_type=\"code\" colab={}\n# !cp -r netflix_data '/content/drive/My Drive/colab/recomendation/'\n\n\n# + [markdown] id=\"4scXCKQrxCLL\" colab_type=\"text\"\n# ###Now the data is available in drive\n\n# + id=\"TNDeXf8SxBNx\" colab_type=\"code\" colab={}\n# !cp -r '/content/drive/My Drive/colab/recomendation/netflix_data' .\n\n# + id=\"J_aZCS0h7Rwn\" colab_type=\"code\" colab={}\nNAME = \"DeepRecommender-DR-BaselineLR-{}\".format(int(time.time()))\n\ntensorboard = TensorBoard(log_dir='./logs/{}'.format(NAME))\nDATA_DIR = 'netflix_data'\nnf_6m_train = os.path.join(DATA_DIR, 'N6M_TRAIN', 'n6m.train.txt')\nnf_6m_valid = os.path.join(DATA_DIR, 'N6M_VALID', 'n6m.valid.txt')\nnf_6m_test = os.path.join(DATA_DIR, 'N6M_TEST', 'n6m.test.txt')\n\n# + id=\"8Yaba9CM7tI0\" colab_type=\"code\" colab={}\ndf_train = pd.read_csv(nf_3m_train, names=['CustomerID','MovieID','Rating'], sep='\\t')\nprint(df_train.shape)\ndf_train.head()\ndf_valid = pd.read_csv(nf_3m_valid, names=['CustomerID','MovieID','Rating'], sep='\\t')\nprint(df_valid.shape)\ndf_valid.head()\ndf_test = pd.read_csv(nf_3m_test, names=['CustomerID','MovieID','Rating'], sep='\\t')\nprint(df_test.shape)\ndf_test.head()\n\n# + id=\"uYwgeW819oBx\" colab_type=\"code\" colab={}\ncustomer_map = df_train.CustomerID.unique()\ncustomer_map.sort()\ncustomer_map = customer_map[0:17550]\n#user_map\nnum_users = len(customer_map)\ncustomer_map[-1]\n\nmovie_map = df_train.MovieID.unique()\nmovie_map.sort()\nmovie_map = movie_map[0:1000]\n#movie_map\nnum_movies = len(movie_map)\nmovie_map[-1]\n\n# + id=\"4DFN6zIL90mk\" colab_type=\"code\" colab={}\n#run this only once\nfile = open('matrix_train.csv','w')\ndef temp(i):\n return np.where(movie_map == i)[0][0]\n\nfor id_user in customer_map:\n id_movie = df_train.iloc[:,1][(df_train.iloc[:,0]==id_user) & (df_train.iloc[:,1]<=1000)]\n id_movie = id_movie.apply(temp)\n id_rating=df_train.iloc[:,2][(df_train.iloc[:,0]==id_user) & (df_train.iloc[:,1]<=1000)]\n ratings=np.zeros(num_movies, dtype=np.uint32)\n ratings[id_movie-1]=id_rating\n if sum(ratings)==0:\n continue\n ratings=pd.DataFrame(ratings.reshape(-1, len(ratings)))\n file.write(ratings.to_csv(index=False, header=False))\n del id_movie\n del id_rating\n del ratings\n\n\nfile.close()\n\n\nX = pd.read_csv('matrix_train.csv', header=None)\nprint(X.shape)\nX.head()\n\n# + id=\"oXMtBHTy-kbO\" colab_type=\"code\" colab={}\ncustomer_map = df_valid.CustomerID.unique()\ncustomer_map.sort()\ncustomer_map = customer_map[:7020]\nnum_users = len(customer_map)\ncustomer_map[-1]\n\nmovie_map = df_valid.MovieID.unique()\nmovie_map.sort()\nmovie_map = movie_map[:895]\n#movie_map\nnum_movies = len(movie_map)\nmovie_map[-1]\n\n# + id=\"U3wZUOjy_Iby\" colab_type=\"code\" colab={}\nfile = open('matrix_valid.csv','w')\n\ndef temp(i):\n return np.where(movie_map == i)[0][0]\n\nfor id_user in customer_map:\n id_movie = df_valid.iloc[:,1][(df_valid.iloc[:,0]==id_user) & (df_valid.iloc[:,1]<=1000)]\n id_movie = id_movie.apply(temp)\n id_rating=df_valid.iloc[:,2][(df_valid.iloc[:,0]==id_user) & (df_valid.iloc[:,1]<=1000)]\n ratings=np.zeros(1000, dtype=np.uint32)\n ratings[id_movie-1]=id_rating\n if sum(ratings)==0:\n continue\n ratings=pd.DataFrame(ratings.reshape(-1, len(ratings)))\n file.write(ratings.to_csv(index=False, header=False))\n del id_movie\n del id_rating\n del ratings\n\nfile.close()\n\n\nX_valid = pd.read_csv('matrix_valid.csv', header=None)\nprint(X_valid.shape)\nX_valid.head()\n\n# + id=\"8R6wTKo7_1Bq\" colab_type=\"code\" colab={}\ncustomer_map = df_test.CustomerID.unique()\ncustomer_map.sort()\ncustomer_map = customer_map[:7020]\nnum_users = len(customer_map)\ncustomer_map[-1]\n\nmovie_map = df_test.MovieID.unique()\nmovie_map.sort()\nmovie_map = movie_map[:901]\n#movie_map\nnum_movies = len(movie_map)\nmovie_map[-1]\n\n# + id=\"J8IGWSjb_8EJ\" colab_type=\"code\" colab={}\nfile = open('matrix_test.csv','w')\n\ndef temp(i):\n return np.where(movie_map == i)[0][0]\n\nfor id_user in customer_map:\n id_movie = df_test.iloc[:,1][(df_test.iloc[:,0]==id_user) & (df_test.iloc[:,1]<=1000)]\n id_movie = id_movie.apply(temp)\n id_rating=df_test.iloc[:,2][(df_test.iloc[:,0]==id_user) & (df_test.iloc[:,1]<=1000)]\n ratings=np.zeros(1000, dtype=np.uint32)\n ratings[id_movie-1]=id_rating\n if sum(ratings)==0:\n continue\n ratings=pd.DataFrame(ratings.reshape(-1, len(ratings)))\n file.write(ratings.to_csv(index=False, header=False))\n del id_movie\n del id_rating\n del ratings\n\nfile.close()\n\nX_test = pd.read_csv('matrix_test.csv', header=None)\nprint(X_test.shape)\nX_test.head()\n\n\n# + id=\"dkUG1QFvABpA\" colab_type=\"code\" colab={}\ndef rmse(y_true, y_pred):\n mask_true = K.cast(K.not_equal(y_true, 0), K.floatx())\n masked_squared_error = mask_true * K.square((y_true - y_pred))\n # in case mask_true is 0 everywhere, the error would be nan, therefore divide by at least 1\n # this doesn't change anything as where sum(mask_true)==0, sum(masked_squared_error)==0 as well\n masked_mse = K.sum(masked_squared_error, axis=-1) / K.maximum(K.sum(mask_true, axis=-1), 1)\n return K.sqrt(masked_mse)\n\n\n# + id=\"U9k-T7xSBzoQ\" colab_type=\"code\" colab={}\nmodel = Sequential()\n\nmodel.add(Dense(28, input_dim = X.shape[1], activation='selu'))\nmodel.add(Dense(56, activation='selu'))\nmodel.add(Dense(56, activation='selu'))\nmodel.add(Dropout(0.65))\nmodel.add(Dense(56, activation='selu'))\nmodel.add(Dense(28, activation='selu'))\nmodel.add(Dense(X.shape[1], activation='selu'))\n\n# + id=\"LBV0NwhNB9mF\" colab_type=\"code\" colab={}\nsgd = optimizers.SGD(lr=0.005, momentum=0.9)\nmodel.compile(loss=rmse, optimizer=sgd)\n\nmodel.fit(X, X, batch_size=128, epochs=100, validation_data=(X_valid, X_valid), callbacks=[tensorboard])\n\n# + id=\"acDZ0vLDCBgg\" colab_type=\"code\" colab={}\ntest_loss = model.evaluate(X_test, X_test)\ntest_loss\n","repo_name":"sachinmathewjose/movie-recomendation-DL","sub_path":"recomendation.ipynb","file_name":"recomendation.ipynb","file_ext":"py","file_size_in_byte":12556,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"25"} +{"seq_id":"11315719399","text":"# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# \"Open\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"KlzFCqp7U9m-\" outputId=\"71613a77-3e4f-47e7-d43a-c662c9d6bfbe\"\n# !pip install folium h3 numpy\n# !pip install geopandas\n\n# + id=\"MjJ3xEucTeug\"\nimport folium\nfrom h3 import h3\nfrom collections import Counter\nimport numpy as np\n\ndef plot_most_populated_hexagons(coordinates):\n # Convert coordinates to h3 hexagons at resolution 10\n hexagons = [h3.geo_to_h3(lat, lon, 10) for lat, lon in coordinates]\n \n # Count occurrences of each hexagon\n hexagon_counts = Counter(hexagons)\n \n # Get the 3 most common hexagons\n most_common_hexagons = hexagon_counts.most_common(3)\n \n # Create a map centered at the first most common hexagon\n first_hexagon_center = h3.h3_to_geo(most_common_hexagons[0][0])\n m = folium.Map(location=first_hexagon_center, zoom_start=7)\n \n # Add the most common hexagons to the map\n for hexagon, count in most_common_hexagons:\n # Get the boundary of the hexagon\n boundary = h3.h3_to_geo_boundary(hexagon)\n # Add a polygon to the map for this hexagon\n folium.Polygon(\n locations=boundary + [boundary[0]], # ensure the polygon is closed\n color='blue',\n fill=True,\n fill_color='blue',\n fill_opacity=0.6,\n popup=f'Count: {count}',\n ).add_to(m)\n \n # Display the map\n return m\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"odlYc0Q4V579\" outputId=\"d3473f87-e3cd-4a94-b620-5868e64b4487\"\n# !unzip /content/ne_110m_land.zip\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 373} id=\"E31-hnUKaeCs\" outputId=\"f7542cf8-348e-488e-b1c7-0de9540d9477\"\nimport geopandas as gpd\nimport random\nfrom shapely.geometry import Point\n\ndef generate_land_coordinates():\n # Load the land shapefile\n world = gpd.read_file('/content/ne_110m_land.shp')\n\n while True:\n # Generate a random coordinate\n latitude = random.uniform(-90, 90)\n longitude = random.uniform(-180, 180)\n point = Point(longitude, latitude)\n\n # Check if the point is within any of the land polygons\n if any(world.contains(point)):\n return (latitude, longitude)\n\n\n# + id=\"kjV05aM-ak1m\"\n\n","repo_name":"noveoko/24nme.github.io","sub_path":"Geolocation Laboratory.ipynb","file_name":"Geolocation Laboratory.ipynb","file_ext":"py","file_size_in_byte":2509,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"25"} +{"seq_id":"44079419117","text":"# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"1i1zHHFvu16m\" outputId=\"2496c29c-54b5-45a1-8d59-e42c870dc6f3\"\nfrom google.colab import drive\ndrive.mount('/content/gdrive')\n\n# + id=\"QozkJPrwvpPU\"\n# Load libraries\nimport pandas as pd\nfrom google.colab import files\nfrom sklearn import preprocessing\nfrom sklearn.compose import make_column_transformer\nfrom sklearn.preprocessing import StandardScaler, OneHotEncoder, LabelEncoder\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import metrics \nfrom tensorflow import keras\nfrom tensorflow.keras import layers\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"qHZqfdoDvfhg\" outputId=\"f58e7350-8a26-4998-be6e-327df58fea1e\"\n# Load training data\ntrain_data = pd.read_csv('gdrive/MyDrive/train_windy.csv')\nlen(train_data)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 411} id=\"9rW1I4R-xQTS\" outputId=\"b8ddd585-5a7e-49f4-f4f4-f874ab6ebb61\"\ntrain_data.head()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"_P9Ws2yZxUhS\" outputId=\"dc947941-b4b1-4caf-df9b-a018c34e399f\"\n# Load testing data\ntest_data = pd.read_csv('gdrive/MyDrive/test_windy.csv')\nlen(test_data)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 411} id=\"sJWEMzn-xZEv\" outputId=\"1aba97e2-001c-47c5-c207-90ecf1f223ac\"\ntest_data.head()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"ISwph6v4xex5\" outputId=\"df5ab1e0-b4ee-4323-e280-29996f72d262\"\n# Get the number of missing data points per column\nmissing_values_count_train = train_data.isnull().sum()\nprint(missing_values_count_train)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"sCUmAo7cxjcG\" outputId=\"02b65517-77c6-4599-ed3b-aa8c6ecc7364\"\n# Get the number of missing data points per column\nmissing_values_count_test = test_data.isnull().sum()\nprint(missing_values_count_test)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 411} id=\"oGbJxk1xxlAv\" outputId=\"02d0a2bc-10fa-4f6a-cecb-2b9110eb735c\"\n# Imputing all rows with missing data\n#train_modified = train_data.dropna()\ntrain_imputed = train_data.fillna(method='bfill', axis=0).fillna(0)\ntrain_imputed.head()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 411} id=\"hgMfJUSsxpRm\" outputId=\"3c3c6e8a-ada7-471f-d543-f22e09b52a3a\"\n# Imputing all rows with missing data\ntest_imputed = test_data.fillna(method='bfill', axis=0).fillna(0)\ntest_imputed.head()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"Nyv_x-vOxqO7\" outputId=\"d6cf8464-39ff-42a6-ca34-31fbef335ab2\"\n# Plot statistics of Wind speed\nprint(train_imputed['wind_speed(m/s)'].describe())\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"R_7o_wWXxtBg\" outputId=\"e5538301-6e60-4b39-a0ab-569c9f7db45b\"\nfeatures_num = ['wind_speed(m/s)', 'atmospheric_temperature(°C)', 'shaft_temperature(°C)', 'blades_angle(°)',\n 'gearbox_temperature(°C)', 'engine_temperature(°C)', 'motor_torque(N-m)', 'generator_temperature(°C)',\n 'atmospheric_pressure(Pascal)', 'area_temperature(°C)', 'windmill_body_temperature(°C)', 'wind_direction(°)',\n 'resistance(ohm)', 'rotor_torque(N-m)', 'blade_length(m)', 'blade_breadth(m)', 'windmill_height(m)']\nfeatures_cat = ['cloud_level']\nfeatures_lab = ['turbine_status']\n\npreprocessor = make_column_transformer(\n (StandardScaler(), features_num),\n (OneHotEncoder(), features_cat),\n #(LabelEncoder(), features_lab),\n)\n\ny = train_imputed.pop('windmill_generated_power(kW/h)')\n#train_imputed = train_imputed.iloc[:,[1,2,3,10,12]]\nX = preprocessor.fit_transform(train_imputed)\n\n#test_imputed = test_imputed.iloc[:,[1,2,3,10,12]]\ntest_X = preprocessor.fit_transform(test_imputed)\n\ntrain_imputed.columns\n\n# + id=\"UqwUJnVTxv9J\"\n#Train-test split\ntrain_X, val_X, train_y, val_y = train_test_split(X,y,random_state=1,test_size=0.2)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"j2YILkDXxyok\" outputId=\"4f26c41f-b40d-416c-d969-2e8f5815d030\"\nprint(train_X[0])\n\n# + id=\"mSpKfPE9x1Op\"\nmodel = keras.Sequential([\n # the hidden ReLU layers\n layers.Dense(units=128, activation='relu', input_shape=[20]),\n layers.Dense(units=256, activation='relu'),\n layers.Dense(units=64, activation='relu'),\n # the linear output layer \n layers.Dense(units=1),\n])\n\n# + id=\"CFKV1RA1yZVT\"\nmodel.compile(\n optimizer='adam',\n loss='mae',\n)\n\n# + id=\"mYuKNoueyFPl\"\nhistory = model.fit(\n train_X, train_y,\n validation_data=(val_X, val_y),\n batch_size=256,\n epochs=100,\n verbose = 0\n)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 282} id=\"RHiRY2qcy1pN\" outputId=\"cf8872e7-1d05-4461-ad24-a28f8cba9106\"\nhistory_df = pd.DataFrame(history.history)\nhistory_df.loc[:, ['loss', 'val_loss']].plot()\n\n# + id=\"E-t17NSUy6k7\"\ntest_preds = model.predict(test_X)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 17} id=\"-93rt3RSzDNh\" outputId=\"cf7983e7-4045-45d3-cf30-f96dc0b6ce6c\"\n# The lines below shows how to save predictions in format used for competition scoring.\noutput = pd.DataFrame({'tracking_id': test_data.tracking_id,\n 'datetime': test_data.datetime,\n 'windmill_generated_power(kW/h)': test_preds.flatten()})\n\noutput.head()\noutput.to_csv('submission_windy_dl.csv', index=False)\nfiles.download('submission_windy_dl.csv')\n","repo_name":"Prajit-Rajendran/Coding_competitions","sub_path":"HackerEarth Windy Day ML Challenge/Windy_challenge_DL.ipynb","file_name":"Windy_challenge_DL.ipynb","file_ext":"py","file_size_in_byte":5418,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"28442540705","text":"# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# \"Open\n\n# + [markdown] id=\"LW4TltI3ZTTk\"\n# # **TensorFlow Tutorial**\n#\n#\n#\n# This notebook contains practices and notes from Daniel Bourke's 14 hours long tutorial on TensorFlow 2.0. This notebook is separated into different parts in accordance to how Daniel's video is split. \n#\n# Note that this notebook also contains some trivial theory and/or code, but I've decided to insert that as well since I wanted the notebook to be as representative of the tutorial as possible.\n#\n# If you want to run some chunk of code, please run all the code included in that section.\n#\n#\n# ---\n#\n#\n#\n#\n#\n\n# + [markdown] id=\"W__oxrb8cS1_\"\n# ## Introduction to DL\n\n# + id=\"o7jan22S0VMc\"\nimport numpy as np \nimport pandas as pd\nimport tensorflow as ts \nfrom tensorflow.keras.utils import plot_model\nimport plotly.express as px \nfrom sklearn.model_selection import train_test_split \nfrom sklearn.compose import make_column_transformer\nfrom sklearn.preprocessing import MinMaxScaler, OneHotEncoder \n\n# + [markdown] id=\"-Adb-jnSaES1\"\n# ### Deap Learning\n#\n#\n# Deep learning is a type of machine learning based on artificial neural networks in which multiple layers of processing are used to extract progressively higher level features from data. \n#\n# So what is the difference between a traditional programming and machine learning programmings? In a traditional programming, we have some inputs, then we establish some rules in order to get the output. However, in machine learning, we start with inputs and the ideal outputs and then we try to find some rules between inputs and outputs. How do we find those rules? Well, we use machine learning algorithms such as linear regression, logistic regression, SVM, etc. \n\n# + [markdown] id=\"FpAFduYWbqjH\"\n# ### Why Should We Use Deep learning?\n#\n# For complex problems, thinking about all the rules is nearly impossible. Furthermore, when we take into account that those rule might change in different situations, it becomes impossible to solve some problems using traditional programming paradigms. However, if we can build a simple rule-based system that doesn't require deep learning, then don't use deep learning. If a problem is completely deterministic with a finite set of rules, deep learning is a over-kill or could even underperform in comparison to a traditional programming paradigm. \n#\n# Deep learning is useful when we have problems with long lists of rules, when we are continually chaning environments, or when we want to discover insights within large collections of data.\n#\n# In which situations *deep learning* is typically not that good for? The first one is when we need explainability of our model. Futhermore, deep learning is probably not a best option when the traditional approach is a better option, when errors are unacceptable, or when we don't have much data. \n#

\n# So, when to use traditional ML algorithms and when to use DL algorithms? Traditional ML algorithms are often the best choice for structured data, while DL algorithms often outperform traditional ML algorithms on unstructured data (pictures, videos, sentences, etc.). \n\n# + [markdown] id=\"E6wFK_L7rWDC\"\n# ### What are Neural Networks?\n#\n#\n\n# + [markdown] id=\"-PYKDD9-jsfc\"\n# A neural network is a network or circuit of neurons, or in a modern sense, an artificial neural network composed of artificial neurons or nodes. \n#

\n#\n#
\n#\n#\n# In the picture above, the first column represent the input data, while the last column represent the output. Everything in between those columns are *hideen layers*. Each node in a hidden layer is an activation of combination of nodes in the previous layer. \n#\n# What does that mean? Let's say that in this example, we have four input variables. All those four input variables are combined in order to get the first node of the first hidden layer, as well as the second, third and fourth node of the first hidden layer.\n#\n# How do we combine nodes from the previous layer? We use a simple linear combination. For example, the linear combination for the first node in the first hidden layer is given by:\n#\n# $$\n# \\begin{aligned}\n# z_{1}^{[1]} = w_{1}^{[1]T}x + b_{1}^{[1]}\n# \\end{aligned}\n# $$\n#\n# where $w_{1}^{[1]T}$ is the vector with adequate weights, $x$ are features from the previous layer, and $b_{1}^{[1]}$ is the bias for that node. In this notation, subscripts refer to the specific node, while the superscripts refer to the specific hidden layer. After we get the linear combination, we need to have some kind of *activation function* in order to approximate more complicated function. If we do not apply some activation function, our neural network will always approcimate linear functions regardless of the number of hidden layers.\n#\n# Some popular choices for activation functions are sigmoid function, hyperbolic tangent function, rectified lienar unit (ReLU), and leaky rectified linear unit (LReLU):\n#\n# $$\n# \\begin{aligned}\n# sigmoid = \\frac{1}{1 + e^{-z}}\n# \\end{aligned}\n# $$\n#
\n# $$\n# \\begin{aligned}\n# hyperbolic = \\frac{e^z - e^{-z}}{e^z + e^{-z}}\n# \\end{aligned}\n# $$\n#
\n# $$\n# \\begin{aligned}\n# ReLU = max(0, z)\n# \\end{aligned}\n# $$\n#
\n# $$\n# \\begin{aligned}\n# LReLU = max(0.01 * z, z)\n# \\end{aligned}\n# $$\n#
\n# After we choose a specific activation function, all that we need to do for the specific node of the specific hidden layer is to calculate:\n#\n# $$\n# \\begin{aligned}\n# a_{1}^{[1]} = g(z)\n# \\end{aligned}\n# $$\n#\n# where *g* is the activation function. After that, we do the same calculation for each node of the first hidden layer and we get the activation of the first hidden layer. Now, combinations of activations of the first hidden layers are inputs for the second layer, and so on until we get to the final layer - the output layer.\n#\n# Having that in mind, the first thing that we would be tempted to do is to create a `for loop` in order to calculate the activations of the first hidden layer. However, that would be computationally inefficient since we can combine all nodes of one hidden layer, weights, and biases into a matrix representation which significantly speeds up our process. In this case, the activation of one *whole* hidden layer $l$ is given by:\n#\n#\n# $$\n# \\begin{aligned}\n# A^{[l]} = g(W^{[l]}A^{l-1} + b^{[l]})\n# \\end{aligned}\n# $$\n#\n# where superscript $l$ refers to the specific hidden layer, and $A^{l-1}$ are the activations from the previous layer. This means that we have only one computation per one hidden layer, instead of $n$ computations, where $n$ is the number of nodes in a hidden layer. \n#\n# In order to train a neural network, we firstly initiate some random values for $W^{[l]}$ and $b^{[l]}$, and go through the first step of *forward propagation*, until we come to the final output. This means that we will go through the process of calcualting the activation of each hidden layer with some randomly intitiated numbers until we come to the output, i.e. until we produce some numbers as the output. Since (in supervised learning) our data already has the correct output values, we can compare the predictions of our neural network with the correct output values and determine how bad is our neural network. We formalize how bad the neural network is by defining a *loss function* which entirely depends on the nature of the problem. For example, if our output is a binary variable, then we model output with Bernoulli distribution and apply Maximum Likelihood Estimation which gives us:\n#\n# $$\n# \\begin{aligned}\n# L(\\hat{y}, y) = -(ylog\\hat{y} + (1-y)log(1-\\hat{y}))\n# \\end{aligned}\n# $$\n#\n# Now we have a way to formalize the error of our neural network. Now, in order to improve our neural network, we would apply a *gradient descent algorithm* which changes weights and biases so that the loss function is smaller. The gradient descent algorithm is not that complicated, although it is really elegant. However, I am not going to show it here.\n\n# + [markdown] id=\"g2tF-H0muVj2\"\n# ### What is DL Actually Used For?\n\n# + [markdown] id=\"Y-jfcQfouYYQ\"\n# Let's take a look at some common deep learning use cases. \n# Some of them are recommendation systems, language translations, computer vision, speech recognition, natural language processing, etc. Language translation and speech recognition are oftern referred to as *sequence to sequence* problems. \n\n# + [markdown] id=\"qxKH1ol7wlZE\"\n# ## Introduction to TensorFlow\n\n# + [markdown] id=\"8t4iK2m5wrOo\"\n# ### What is TensorFlow? What are Tensors?\n\n# + [markdown] id=\"igzewRtRw8Z4\"\n# TensorFlow (TF) is end-to-end platform for machine learning. We can write fast deep learning code in Python and run it on GPU. With TF we are also able to access many pre-built deep learning models. Furthermore, it offers a whole stack: preprocessing data, model data, and deploy the model in your application. In the end, TF was originally designed and used in-house by Google and is now open-source. \n#

\n# What exactly is a tensor? In mathematics, a tensor is an algebraic object that describes a relationship between sets of algebraic objects related to a vector space. Objects that tensors may map between include vectors and scalars, and even other tensors. \n\n# + [markdown] id=\"85ZeSrbo0qT-\"\n# A TF workflow typically includes:\n#\n#\n# 1. Getting data ready\n# 2. Building or picking a pretrained model\n# 3. Fitting the model to the data and making predictions\n# 4. Evaluating the model\n# 5. Improving the model through the experimentation\n# 6. Saving and reloading trained models \n#\n#\n\n# + [markdown] id=\"HJyI4vxC1CRk\"\n# ## Tensors in TensorFlow\n\n# + [markdown] id=\"aRNzDzru2VTl\"\n# In this part, we are going to cover some of the most fundamental concepts of tensors using TensorFlow. \n#\n# More specifically, this part will cover:\n# * Introduction to tensors\n# * Getting information from tensors\n# * Maniuplating tensors\n# * Tensors and NumPy\n# * Using @tf.function\n# * Using GPUs with TensorFlow (or TPUs)\n# * A few exercises\n\n# + [markdown] id=\"OExcAoxQ2gdY\"\n# ### Introduction to Tensors\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"xNUS_rEy3QxP\" outputId=\"6eae24c9-ee22-4224-97b3-bdc7162add54\"\n# Import TensorFlow\nimport tensorflow as tf \nimport numpy as np\nprint(tf.__version__)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"A6n-6vr93h93\" outputId=\"51e0d139-837f-4ed9-d85d-8af49fb8e04b\"\n# Create tensor with tf.constant()\nscalar = tf.constant(7)\nprint(scalar)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"dVhscXJo3ykn\" outputId=\"f35a71fe-ac66-419a-b654-ec81b028da09\"\n# Check the number of dimensions of a tensor\nprint(\"Dimensions of scalar:\\n\", scalar.ndim)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"NyksXL134R-e\" outputId=\"0a6baeea-1aae-4c82-8edf-c7bb7a41fabb\"\n# Create a vector\nvector = tf.constant([1, 2, 3, 4, 5])\nprint(\"Vector:\\n\", vector)\nprint(\"\\nDimensions:\\n\", vector.ndim)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"cs-f20YG4fQH\" outputId=\"93e50b11-00d4-4551-f911-a509ac678123\"\n# Create a matrix\nmatrix = tf.constant([\n [1, 2, 3, 4, 5], \n [3, 4, 5, 6, 7]\n ]\n )\nprint(\"Matrix:\\n\", matrix)\nprint(\"\\nDimensions:\\n\", matrix.ndim)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"KFtNTPYL4zXY\" outputId=\"0184ccbd-6fa5-4870-8c71-c1d8cb4934b6\"\n# Let's formally use args of tf.constant()\nmatrix1 = tf.constant(value = [[1, 2, 3, 4], [2, 2, 2, 2]], dtype = tf.float16)\nprint(\"Matrix:\\n\", matrix1)\nprint(\"\\nDimensions:\\n\", matrix1.ndim)\nprint(\"\\nType:\\n\", matrix1.dtype)\nprint(\"\\nShape:\\n\", matrix1.shape)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"AjTaG5yK5dJk\" outputId=\"b261ebb4-6c1c-4b67-b045-4bf84ade0987\"\ntensor = tf.constant([[\n [1, 2, 3], \n [4, 5, 6]], \n [[7, 8, 9], \n [10, 11, 12]],\n [[13, 14, 15], \n [16, 17, 18]]] ,dtype = tf.float16)\nprint(\"Tensor:\\n\", tensor)\nprint(\"\\nDimensions:\\n\", tensor.ndim)\nprint(\"\\nShape:\\n\", tensor.shape)\n\n# + [markdown] id=\"UV_H-Eme6Tos\"\n# What have we created so far?\n# * Scalar: a single number\n# * Vector: a number with direction\n# * Matrix: a 2-dimensional array of numbers\n# * Tensor: an n-dimensional array of numbers (where $n\\ge 0$)\n\n# + [markdown] id=\"0W6brOEW75YQ\"\n# ### Creating Tensors with tf.Variable()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"HMJZYWbg7mLu\" outputId=\"3b2b1816-bbb6-4561-9b9f-9bbda10d2933\"\n# So far, we have created tensors with tf.constant(), but we can do it with tf.Variable() as well\n# The difference between tf.Variable() and tf.constant() is that tf.Variable() creates a changeable tensor\nchangeable_tensor = tf.Variable([10, 7])\nunchangeable_tensor = tf.constant([10, 7])\nprint(changeable_tensor)\nprint(unchangeable_tensor)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"n03IcMA_8bVA\" outputId=\"7d9573c6-29ef-4a39-96b7-d183d0415a17\"\n# Try to change one of the elements in our changeable tensor\ntry:\n changeable_tensor[0].assign(99)\n print('Changing value was successful')\n print(changeable_tensor)\nexcept:\n print('Changing value was not succesful')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"YzhZncCz8yj-\" outputId=\"40dc0669-3908-4321-dd28-448babb24655\"\n# Now let's try to change value in unchangeable tensor\ntry:\n unchangeable_tensor[0].assign(99)\n print('Changing value was successful')\n print(unchangeable_tensor)\nexcept Exception as e:\n print('Changing value was not succesful')\n print(e)\n\n# + [markdown] id=\"aj9eRs8W9Yln\"\n# ### Creating Random Tensors \n\n# + [markdown] id=\"AR_CFLtX9CYl\"\n# Random tensors are tensors of some arbitrary size which contain random numbers. We need random tensors when initializing weights and biasis in neural networks (or, more generally, in any other machine learning algorithm which requires some beginning random numbers). \n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"IZN-0uMV3dvR\" outputId=\"b344be93-ffef-4c06-9618-40f27aa8955b\"\n# Let's create two random (but same) tensors\nrandom1 = tf.random.Generator.from_seed(42) # set seed for reproducibility\nrandom1 = random1.normal(shape = (3, 2))\nprint(random1)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"hjuQkEeW5oox\" outputId=\"e389a1e2-f2bb-47a4-b38f-4b93a785fe4a\"\nrandom_2 = tf.random.Generator.from_seed(41)\nrandom_2 = random_2.normal(shape = (3, 2))\nprint(random_2)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"VMJeERMJ6GUX\" outputId=\"a3cd6c2e-f306-4162-f8de-500a1d1c4b9d\"\n# Are they equal?\nprint(random1 == random_2)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"bfF9zjcs6cKW\" outputId=\"43f0a185-df9c-4051-d3db-ea4dc7bb595f\"\n# What if we want to shuffle the order of rows?\ntf.random.set_seed(42) # setting a general? seed\nprint(tf.random.shuffle(random1)) # It doesn't shuffle inplace, you have to assign to a variable\nprint(\"\\n\", random1)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"X94BXpnJ6vcu\" outputId=\"02f4106b-7e25-4603-dc34-6663d6b5e5ff\"\n# Creating a transpose of a tensor\nprint(tf.transpose(random1))\n\n# + [markdown] id=\"AhYKDTPx_V9i\"\n# ### Other Ways to Create Tensors\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"6SL5rwbf_c1K\" outputId=\"e4053a5b-dc3e-42e6-f4cd-87ed00a830a4\"\nnp_x = np.random.normal(size = (5, 5))\nprint(np_x)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"WLH34KxX_ic6\" outputId=\"3effcc26-5be8-496d-bd1c-059a2b16c2dd\"\ntensor_np = tf.convert_to_tensor(np_x)\nprint(tensor_np)\n\n# + [markdown] id=\"xXJnhJnrB0rz\"\n# > But you can also just input NumPy array into tf.constant() or tf.Variable()!\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"jq9VBGZv_z9i\" outputId=\"873b21d7-1e89-44cd-8772-be5ed1802cf4\"\nones = tf.ones(shape = (7, 6), dtype = tf.int32)\nzeros = tf.zeros(shape = (3, 3), dtype = tf.int16)\nprint(\"Tensor of ones:\\n\", ones)\nprint(\"\\nTensor of zeros:\\n\", zeros)\n\n# + [markdown] id=\"EdBGqgy9AqW9\"\n# > The main difference between NumPy arrays and TensorFlow tensors is that tensors can be run on a GPU (much faster for numerical computing).\n\n# + [markdown] id=\"0dZk7avkBKF3\"\n# ### Getting Information from Tensors\n\n# + [markdown] id=\"VeKrt_1BDOJv\"\n# The most frequently used information from tensors are:\n# * shape\n# * rank (n of dimensinos)\n# * axis or dimension\n# * size\n\n# + id=\"DnRqr_1iEQIF\"\ntensor_A = tf.constant([\n [1, 2, 3, 4],\n [3, 2, 2, 2],\n [3, 2, 1, 3],\n [5, 4, 3, 2]\n ])\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"difCmsx5EYm0\" outputId=\"ce79fbf1-21a0-4faa-e19c-d033d5a20c9c\"\nprint('Shape of tensor:', tensor_A.shape)\nprint('Rank of tensor:', tensor_A.ndim)\nprint('Size of tensor:', tf.size(tensor_A))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"FC7kJCY9ElOE\" outputId=\"ab441cdc-9c4d-4c7d-d840-130fb13d387d\"\nprint('The first column:')\nprint(tensor_A[:, 0])\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"2pvSu0XpFVBc\" outputId=\"ccc59c24-43b4-4ba4-b133-217a0ce60553\"\n# Get various attributes of our tensor\nprint(\"Datatype of every element:\", tensor_A.dtype)\nprint(\"Number of dimensions:\", tensor_A.ndim)\nprint(\"The size of tensor:\", tf.size(tensor_A))\nprint(\"The shape of tensor:\", tensor_A.shape)\nprint(\"Elements along 0 axis:\", tensor_A.shape[0])\nprint(\"Elements along 1 axis:\", tensor_A.shape[1])\n\n# + [markdown] id=\"buPnfGknMuNE\"\n# ### Indexing Tensors\n\n# + [markdown] id=\"yJlraNG9MLQB\"\n# > Tensors can be indexed just like NumPy arrays.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"ZyLoeH3b-Lhy\" outputId=\"b07e14c3-eb1c-4ae9-d137-2646cafdd585\"\n# Get the first 2 elements of each dimension\nprint(tensor_A[:2, :2])\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"gV61vpDK-V1q\" outputId=\"5eb4d2cf-5210-4327-e4c0-336a31ef49e1\"\n# Get the first element from each dimencion from each index except for the final one\nprint(tensor_A[:1, :])\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"kCQm5tH6-zQB\" outputId=\"6bbf1b64-e47a-433b-8fa8-5b2de251a780\"\n# Let's create a rank 2 tensor (2 dimensions)\nrank_2_tensor = tf.constant(np.random.normal(size = (3, 4)))\nprint(rank_2_tensor)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"VnEueHSe_9la\" outputId=\"8aaffa34-83cd-407e-ede3-77cda10fc5bf\"\n# Get the last item of each row of our tensor\nprint(rank_2_tensor[:, -1])\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"3SXpHQGtAJHT\" outputId=\"91de6233-16ec-4e18-90dd-f664a4b1f956\"\n# Add in extra dimension to our rank 2 tensor\nrank_3_tensor = rank_2_tensor[..., tf.newaxis] # three dots mean include all other axes\nprint(rank_3_tensor)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"khbfM-ZlJuAB\" outputId=\"3f683fe9-7b6a-4c2b-95c8-5cc5030c9750\"\n# Alternative to tf.newaxis\ntf.expand_dims(rank_2_tensor, axis = - 1) # expand on final axis\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"8iaJox-LKHsX\" outputId=\"408a7287-477a-4d05-a328-d14043d2ddf5\"\ntf.expand_dims(rank_2_tensor, axis = 0)\n\n# + [markdown] id=\"k-bvO3TvKU1Z\"\n# Note that the numbers always stay the same, but the shape of a tensor is changed.\n\n# + [markdown] id=\"56icp9QuKk09\"\n# ### Tensor Operations\n\n# + [markdown] id=\"7wWPResf5vle\"\n# **Basic Operations**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"HqNiN_tF52jc\" outputId=\"9a2e6086-54bb-4a5d-88cf-b41aa1369ca3\"\n# We can add values to a tensor using the addition operators\ntensor = tf.constant(np.arange(10), shape = (2, 5))\nprint(tensor)\nprint('Addition')\nprint(tensor + 10) # the original tensor is not changed, we didn't assign the values\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"YPHfM-KN6ABt\" outputId=\"3a78eb75-9579-47b4-8d7d-f76999800127\"\n# Multiplication\nprint(tensor * 7)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"pAGXrFgN6Tf0\" outputId=\"8e4530e1-ac7d-459c-e2e6-312dfb8fe5b2\"\n# Substraction\nprint(tensor - 5)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"wdjDUy2N6XAF\" outputId=\"bc3df3cc-a60d-4b06-80b7-47b673170110\"\n# We can also use TensorFlow functions for addition, substraction, division and multiplication (like in NumPy)\nprint('Multiplication')\nprint(tf.multiply(tensor, 5))\nprint('Addition')\nprint(tf.add(tensor, 10))\n\n# + [markdown] id=\"krxZ8dQM6fsF\"\n# **Matrix Multiplication**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"yaGJ0xv7688j\" outputId=\"9a78c570-42cc-4326-ab20-b6ca8a5c857e\"\n# Matrix multiplication\nA = tf.constant([[3, 2, 2], [3, 1, 7]])\nB = tf.constant([[1, 2], [3, 3], [4, 5]])\nprint(tf.linalg.matmul(A, B))\n\n# + [markdown] id=\"oUt2z_XC7esc\"\n# As a quick reminder, in order to multiply matrices, the first matrix should be \n# $A^{m_{*}n}$, while the second should be $B^{n_{*}p}$. The resulting matrix is then of shape $m*p$.\n#\n# There are multiple ways to multiply matrices. One of them is to use dot product of rows of first matrix and columns of the second matrix. In other words, for matrices $A \\in {\\rm I\\!R}^{m*n}, B \\in {\\rm I\\!R}^{n*p}$, the elements $c_{ij}$ of the product $ C=AB \\in {\\rm I\\!R}^{m*p}$ are computed as:\n#\n# $$\n# \\begin{aligned}\n# c_{ij} = \\sum_{l = 1}^{n}a_{il}b_{lj}\\\\\n# i = 1, ..., m\\\\ \n# j = 1, ..., k\n# \\end{aligned}\n# $$\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"VrY5mR1P9wwh\" outputId=\"886e7a4e-d547-4038-b2a7-dd84f23dad9c\"\n# Python has operator @ for matrix multiplication, but it is slower\nprint(A@B)\n\n# + [markdown] id=\"-iXPgHxq91Hi\"\n# Let's find a inverse of a matrix. Remember that only square matrices can have regular inverses, but not all of them will actually have it. Rectangular matrices (more frequent than square matrices in practice) have pseudo-inverse. \n# First of all, let's define the regular inverse of a matrix:\n#\n# $$\n# \\begin{aligned}\n# AA^{-1} = I\n# \\end{aligned}\n# $$\n#\n# In other words, the matrix multiplied by its inverse gives us the identity matrix, i.e. we are back to the beginning. In other words, if we multiply some vector with a matrix, and then multiply it with the matrix inverse, we get to the starting point. The inverse of a matrix can be found using different algorithms, but the most simple one is Gaussian elimination.\n#\n# Now, as we have said, rectangular matrices do not have regular inverse. For them, we often use *Moore-Penrose pseudo-inverse*, which is $(A^{T}A)^{-1}A^{T}$. How do we get that? Well, let's consider a linear equation given by $Ax = b$. We get to the pseudo-inverse by doing a bit of algebra:\n#\n# $$\n# \\begin{aligned}\n# Ax = b \\iff A^{T}Ax = A^{T}b \\iff x = (A^{T}A)^{-1}A^{T}b\n# \\end{aligned}\n# $$\n#\n# This equation is actually used to get the optimal parameters for linear regression.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"4n36WS0gCLb9\" outputId=\"158405ee-bc90-4203-8afb-59ae96793daa\"\nA\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"j1Idr-XI_hug\" outputId=\"c32cfcd2-24f4-4c4f-bbb1-05bd4f8986c4\"\n# Finding the inverse of a matrix\n# You must have float32 or float64 dtypes, cannot be calculated on int dtypes\nA = tf.constant([\n [1, 0, 2, 0], \n [1, 1, 0, 0],\n [1, 2, 0, 1],\n [1, 1, 1, 1]\n ], \n dtype = tf.float32\n )\n\nprint(tf.linalg.inv(A))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"y_0QZdozCHnu\" outputId=\"b0bdda4e-10dc-47c7-a975-a47afa86b57d\"\n# Now let's get pseudo-inverse with the tf.linalg.pinv() functino\nA = tf.constant([\n [1, 0, 1, 2],\n [1, 1, 0, 0],\n [1, 2, 0, 1]\n ],\n dtype = tf.float64)\n\nprint(tf.linalg.pinv(A))\n\n# + [markdown] id=\"f-PqrLOGDXht\"\n# In a nutshell, we can perform matrix multiplication using:\n#\n#\n# * `tf.matmul()`\n# * `tf.tensordot()`\n#\n#\n\n# + [markdown] id=\"Tmyq8FXcgxoO\"\n# ### Changing the Datatype of a Tensor\n\n# + id=\"gDM8IJ6mE_nK\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"02d7f8d1-f258-4997-b1c1-ad0ef62f77af\"\nB = tf.constant([1, 3]) # if we populate the function with integers, dtype will be int32\nprint(B.dtype)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"WLwbAeuAg3jZ\" outputId=\"102092c3-4fc1-4671-b74b-7beeb813d8be\"\n# Let's change it to int16 (reduced precision)\nB = tf.cast(B, dtype = tf.int16)\nprint(B.dtype)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"oCHuT4hOhm1M\" outputId=\"5474689d-0d55-4eb0-a507-ed94867928d8\"\n# Change from int16 to float32\nB = tf.cast(B, dtype = tf.float32)\nprint(B.numpy(), B.dtype)\n\n# + [markdown] id=\"jBbCnp4oiOkU\"\n# ### Aggregating Tensors\n\n# + [markdown] id=\"1KrevdBsjOtj\"\n# Aggregating tensors means condensing them from multiple values down to a smaller amount of values.\n#\n# * Get the minimum\n# * Get the maximum\n# * Get the mean\n# * Get the sum\n# * Get the variance\n# * Get the standard deviation\n#\n#\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"xNc5Eembh-9t\" outputId=\"ab47cbfa-9d1a-4914-8c27-21b8f8469542\"\n# Get the absolute values\nD = tf.constant([-7, -10, -3], dtype = tf.float16)\nprint(tf.abs(D))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"gpQgnME_jhLp\" outputId=\"5833734d-071e-4731-a302-f4c7c1566868\"\n# Aggregation measures\n# TF puts reduce_ before the actual agg measure\nD = tf.constant(np.random.normal(size = (10, 30)))\nprint('Minimum value:', tf.reduce_min(D, axis = 1))\nprint('\\mMaximum value:', tf.reduce_max(D, axis = 1))\nprint('\\mMean value:', tf.reduce_mean(D, axis = 1))\nprint('\\mSum:', tf.reduce_sum(D, axis = 1))\nprint('\\nStandard deviation:', tf.math.reduce_std(D, axis = 1))\nprint('\\nVariance:', tf.math.reduce_variance(D, axis = 1))\n\n# + [markdown] id=\"ZJJFnisCmJcL\"\n# ### Indices of Minimum and Maximum; Squeezing a Tensor\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"JEQBU2u6kCLz\" outputId=\"0c996256-4781-442b-e893-703378af0a12\"\nx = tf.constant([3, 2, 1, 5, 4, 2], dtype = tf.float16)\nprint ('Index of minimum:', tf.argmin(x))\nprint('The minimum value:', x[tf.argmin(x)])\nprint('\\nIndex of maximum:', tf.argmax(x))\nprint('The maximum value:', x[tf.argmax(x)])\n\n# + id=\"JyO-ujFen4qs\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"1147daca-f46b-4735-f8df-bb9e70128e91\"\n# Squeezing a tensor - removes dimensions of size 1 from tensor!\nx = tf.constant([3, 2, 1, 4, 2, 1], shape = (6, 1, 1, 1, 1))\nprint(x.ndim)\nprint(tf.squeeze(x))\nprint(tf.squeeze(x).ndim)\n\n# + [markdown] id=\"IQwByCs3reSI\"\n# ### One-Hot Encoding with Tensors\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"pn82XQitq4YT\" outputId=\"f7c047c4-96c0-4096-f33b-35cab3fb9f8d\"\n# We need to define indices of values which will take values of 1 in each row\nsome_list = [0, 1, 2, 1, 3, 2, 3, 0] \ntf.one_hot(some_list, depth = 4) # depth is the number of unique values\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"w3BaIG9isNHa\" outputId=\"6b37b46c-c081-4564-ed60-e52ee20abe41\"\n# Specify custom values for one hot encoding, but you'll rarely use this\ntf.one_hot(some_list, depth = 4, on_value = 'huehue', off_value = 'auau')\n\n# + [markdown] id=\"K1ZvLqBCtBQk\"\n# ### Square, log, Square Root\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"OAq6EbxysgEB\" outputId=\"c8f0bfc3-c659-4526-a237-36ac290dae24\"\nh = tf.range(1, 10, dtype = tf.float32)\nprint(h)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"RkbGtAVOtIOA\" outputId=\"7e58a9f2-c397-44ad-bd35-9118db2f7313\"\nprint('Squared:', tf.square(h))\nprint('\\nSquare root:', tf.math.sqrt(h))\nprint('\\nLog:', tf.math.log(h))\n\n# + [markdown] id=\"sFDHBCWzt9kJ\"\n# ### Tensors and NumPy\n\n# + [markdown] id=\"At8uYDSNuFPf\"\n# > TensorFlow interacts beautifully and naturally with NumPy arrays.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"4DTlyWYLtL83\" outputId=\"b5cf6541-91d8-4850-dd8a-3b81af71246c\"\n# Create a tensor directly from a NumPy array\nprint(tf.constant(np.arange(12, dtype = np.float32)))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"K33HezwTuMXP\" outputId=\"84b6a8a1-d558-4606-ce36-e1f41790c42a\"\n# Convert a tensor into a NumPy array\nx = tf.constant([1, 3, 2])\nx.numpy()\n\n# + [markdown] id=\"XCQc_cEWvTVe\"\n# ---------\n#\n\n# + [markdown] id=\"_bp4lmLTvVZZ\"\n# ## Neural Networks for Regression Problems\n\n# + id=\"uzwXgUtIwK9A\"\nimport tensorflow as tf \nimport numpy as np \nimport matplotlib.pyplot as plt \n\n# + id=\"YF0OLx-2crO_\"\nx = np.random.normal(size = 15)\ny = 0.56*x + 3.85 + np.random.normal(size = 15, scale = 0.5)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 265} id=\"NF-Jab7tcyMi\" outputId=\"aab70d0e-262b-47f1-9a9e-93214f595a29\"\nplt.scatter(x, y);\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"Fcb_V7MBc7BA\" outputId=\"22d4dd16-8bd1-420d-aeef-dbdacb8f4b03\"\n# Let's take a look at input and output shapes\nprint('Shape of x:', np.shape(x))\nprint('Shape of y:', np.shape(y))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"ezAASEvVfYDc\" outputId=\"e1dc0312-969b-4047-ab6a-f168849b5ba4\"\nx = tf.constant(x)\ny = tf.constant(y)\nx\n\n# + [markdown] id=\"H340jvJNg2Bj\"\n# ### Steps in Modelling with TensorFlow\n\n# + [markdown] id=\"9ZpDQBQ0giCB\"\n# We have a few steps in modelling the relationship between input and output variables. The steps are:\n#\n#\n# 1. Create a model - define the input, hidden, and output layers\n# 2. Compile a model - define the loss function, the optimizer, and evaluation metric\n# 3. Fitting a model\n#\n#\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"C5v2dTLWgosJ\" outputId=\"3e4dfb78-6a76-4bcb-ffc5-a00fed8a335f\"\n# Set random seed\ntf.random.set_seed(42)\n\n# 1. Create a model using the sequential API\nmodel = tf.keras.Sequential(\n layers = [tf.keras.layers.Dense(1)] # the output layer, outputs one number\n )\n\n# 2. Compile the model\nmodel.compile(\n loss = tf.keras.losses.mse, \n optimizer = tf.keras.optimizers.SGD(), \n metrics = ['mse']\n )\n\n# 3. Fit the model\nmodel.fit(x, y, epochs = 10) # ten runs through the dataset\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"pt7bk9HIuHSz\" outputId=\"86ae363d-52cb-4a2e-ddfc-9b67f596df9a\"\nmodel.predict(x)\n\n# + [markdown] id=\"VkquIZb020dn\"\n# ### Improving the Model\n\n# + [markdown] id=\"N1lZ5i-L5mux\"\n# The previous model was not that good - predictions were significantly off. However, we can improve the model by adding new hidden layers, apply different activation functions, increasing the number of epochs, etc.\n\n# + id=\"lf_cUqgq3FbW\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"0e06e699-40bc-4adb-d63c-d4c8f798236a\"\ntf.random.set_seed(42)\n\nmodel = tf.keras.Sequential()\nmodel.add(tf.keras.layers.Dense(100, activation = 'relu')) # First hidden layes has 100 neurons\nmodel.add(tf.keras.layers.Dense(50, activation = 'relu')) # The second hidden layer has 50 neurons\nmodel.add(tf.keras.layers.Dense(50, activation = 'relu')) # The third hidden layer has 30 neurons\nmodel.add(tf.keras.layers.Dense(1)) # default activation is linear activation\n\n# adam optimizer; you can experiment with learning rate as well\nmodel.compile(optimizer = tf.keras.optimizers.Adam(), loss = 'mse', metrics = ['mse', 'mae']) \n\nmodel.fit(x, y, epochs = 100) # 100 epochs\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 282} id=\"J_-zYEwT7PZ6\" outputId=\"57df0af6-1cab-4b7b-8b88-b8136c0ea5fe\"\nplt.scatter(x, model.predict(x))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 282} id=\"cV_qBvtw734T\" outputId=\"4ce2d1c0-abb2-4a58-9aad-579effebf9a2\"\nplt.scatter(x, y)\n\n# + [markdown] id=\"qGFCy85D_dTz\"\n# ### Summarizing and Visualizing the Model\n\n# + [markdown] id=\"q-dxsaWRfSyU\"\n# In practice, a typical workflow you'll go through when building neural network is:\n#\n# ```\n# Build a model -> fit it -> evaluate it -> tweak a model -> \n# fit it -> evaluate it -> tweak a model -> fit it -> evaluate it ...\n# ```\n\n# + [markdown] id=\"hUIkfdecDYjZ\"\n# A good way to evaluate model is to visualize it. It's generally a good idea to visualize:\n# * The data - what data are we working with? What does it look like?\n# * The model - what does our model look like?\n# * The training of a model - how does a model perform whilte it learns?\n# * The predictions o the model - how do the predictions of a model line up against the true values?\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 265} id=\"xmhwrT2hgM9e\" outputId=\"4243da71-812b-4a46-a5f4-173a5a54d59c\"\n# Let's create a bigger dataset\nnp.random.seed(42)\nx = np.random.normal(size = 250)\ny = 5.123 + 1.869 * x + 1.3*np.square(x) + np.random.normal(size = 250, scale = 1.852)\nplt.scatter(x, y);\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"1KCEnDlgghnw\" outputId=\"5f37e0c8-b301-4354-d7ce-d555a5397df8\"\n# Now let's split x and y into training and testing set (let's skip validation set)\nprint('Length of data:', len(x))\n\n# Split the data into train and test sets\nx_train = x[:200] # The first 200 samples \nx_test = x[200:] # The last 50 samples\n\ny_train = y[:200]\ny_test = y[200:]\n\nprint('Length of x train:', len(x_train))\nprint('Length of x test:', len(x_test))\nprint('Length of y train:', len(y_train))\nprint('Length of y test:', len(y_test))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 428} id=\"vkLyUgZiiLOp\" outputId=\"f229ab62-3c2e-4143-b954-00448f605417\"\n# Let's plot two sets of data\nplt.figure(figsize = (10, 7))\nplt.scatter(x_train, y_train, c = 'b', label = 'Training data')\nplt.scatter(x_test, y_test, c = 'g', label = 'Testing data')\nplt.legend()\nplt.show();\n\n# + id=\"jG7k-nBojzI1\"\n# Let's build a model in order to figure out the relationship between train and test data\n# Let's first visualize the model itself before fitting it\n# We need to define the model and build it or fit it\n# Alternatively, we can specify input_shape argument in the first layer and it will build automatically\n\nmodel = tf.keras.Sequential(name = 'Network1')\nmodel.add(\n tf.keras.layers.Dense(\n units = 50, \n input_shape = [1], # figure out the input_shape\n activation = 'relu', \n use_bias = True,\n name = 'Layer1'\n )\n )\nmodel.add(\n tf.keras.layers.Dense(\n 50, \n activation = 'relu', \n use_bias = True, \n kernel_regularizer = tf.keras.regularizers.L2(),\n name = 'Layer2'\n )\n ) \nmodel.add(tf.keras.layers.Dense(1, name = 'Output'))\n\nmodel.compile(\n loss = tf.keras.losses.mse, \n optimizer = tf.keras.optimizers.Adam(lr = 0.0001), \n metrics = ['mse', 'mae']\n )\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"gFAKfqNlk6CM\" outputId=\"d7720ed9-e59d-4f49-c528-45f5559b40de\"\nmodel.summary()\n\n# + [markdown] id=\"UQr73VONlcAm\"\n# In the previous table, the total parameters indicates the total number of parameters in the model. Trainable parameters are those the model can update as it trains. Nontrainable parameters aren't updated during training (this is typicall when we bring in already trained parameters from other models during *transfer learning*). \n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"d5zjvWl0nX9k\" outputId=\"8e518e3e-c581-42d3-b070-b1b131ff6280\"\nmodel.fit(x_train, y_train, epochs = 200)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 265} id=\"zFBQZ79ontDV\" outputId=\"956396e5-443b-4ace-95a5-2fbdff5582e3\"\nplt.scatter(x_test, model.predict(x_test));\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 265} id=\"gOvhyGHvpWKE\" outputId=\"f7117d6c-ad1b-4f29-d3a1-3a3ec5ee0be6\"\nplt.scatter(x_test, y_test);\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 422} id=\"Cpnr9saSvhVk\" outputId=\"ee34b5ae-fd9f-486c-f07e-31549b4655da\"\n# Another way to visualize the mode\nfrom tensorflow.keras.utils import plot_model, Progbar\nplot_model(model, show_shapes = True, show_dtype = True, )\n\n# + [markdown] id=\"gsNbS_Fnx8fk\"\n# ### Visualizing Model's Predictions\n\n# + [markdown] id=\"ToRAMsj8ystn\"\n# To visualize predictions, it's a good idea to plot them against the ground truth labels. \n#\n# Often you'll see this in the form of `y_test` or `y_true` versus `y_pred` (ground truth versus our model's predictions). \n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"j07A0_pmFV9m\" outputId=\"cec769b2-2778-4431-9306-f7973f54af3e\"\n# Make some predictions\ny_pred = model.predict(x_test)\ny_pred.T\n\n\n# + id=\"BxHD2vYSFn7p\"\ndef plot_predictions(train_data, train_labels, test_data, test_labels, predictions):\n \"\"\"\n Plots training data, test data and compares predictions to ground truth labels.\n \"\"\"\n plt.figure(figsize = (10, 7))\n # Plot training data in blue\n plt.scatter(train_data, train_labels, c = 'b', label = 'Train data')\n # Plot test data in green\n plt.scatter(test_data, test_labels, c = 'g', label = 'Test data')\n # Plot model's predictions\n plt.scatter(test_data, predictions, c = 'r', label = 'Predictions')\n # show the legend\n plt.legend()\n return plt\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 428} id=\"-kojgwQoG2-Z\" outputId=\"2bc0b772-616e-4c15-9a26-29d6c6ad88b3\"\nplot_predictions(x_train, y_train, x_test, y_test, y_pred);\n\n# + [markdown] id=\"cLOZqq7CG7Vn\"\n# ### Evaluating the Model with Evaluation Metrics\n\n# + [markdown] id=\"6ipaQfBoHhfn\"\n# Depending on the problem we are working on, there will be different evaluation metrics to evaluate the model's performance.\n#\n# In the regression problems, three most frequently used metrics are:\n#\n#\n# * Mean Absolute Error (MAE)\n# * Mean Squared Error (MSE)\n# * Huber (combination of MAE and MSE; less sensitive to outliers)\n# * Huber approaches MSE when $\\delta$ aproaches 0, while it approaches MAE when $\\delta\\$ approaches infinity \n#\n#\n# The MAE is given by:\n#\n# $$\n# \\begin{aligned}\n# MAE = \\frac{1}{N}\\sum_{i = 1}^{N}|y_{i} - \\hat{y_{i}}|\n# \\end{aligned}\n# $$\n#\n# The MSE is given by:\n#\n# $$\n# \\begin{aligned}\n# MSE = \\frac{1}{N}\\sum_{i = 1}^{N}(y_{i} - \\hat{y_{i}})^{2}\n# \\end{aligned}\n# $$\n#\n# The Huber is given by:\n#\n# $$\n# \\begin{equation}\n# L_{\\delta}(y, f(x)) =\n# \\left\\{\n# \\begin{array}{cc}\n# \\frac{1}{2}(y - f(x))^2 & \\mathrm{if\\ } |y - f(X)| \\le \\delta \\\\\n# \\delta|y - f(x)|-\\frac{1}{2}\\delta^2 & \\mathrm{otherwise\\ } \\\\\n# \\end{array} \n# \\right.\n# \\end{equation}\n# $$\n#
\n# MAE in TF is represented by `tf.keras.losses.MAE()` or `tf.metrics.mean_absolute_error()`. MSE is represented by `tf.keras.losses.MSE()` or `tf.metrics.mean_squared_error()`. Huber is represented by `tf.keras.losses.huber()`.\n#\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"z6FlhlfmJEhP\" outputId=\"dd8e57af-c6ef-4c8e-8b55-2cd2d7cacd8d\"\n# Evaluate the model on the test set the quick way\nmodel.evaluate(x_test, y_test)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"F8jP8jaFLbDs\" outputId=\"38a28019-3b5f-4f6c-eca7-aa9ed8060a3e\"\nmodel_mae = tf.keras.losses.MAE(y_test, tf.squeeze(y_pred)) # you need to squeeze the predictions because of the dimensions problem\nmodel_mse = tf.keras.losses.MSE(y_test, tf.squeeze(y_pred))\nmodel_huber = tf.keras.losses.huber(y_test, tf.squeeze(y_pred), delta = 1.0)\n\nfor i in [model_mae, model_mse, model_huber]:\n print(i)\n print(i.numpy())\n print('--------')\n\n\n# + [markdown] id=\"F_90o9UZNOmV\"\n# ### Experimenting with the Model\n\n# + [markdown] id=\"36Dz35EWkt4g\"\n# In essence, in order to improve the model, we should make it bigger or train it for longer time. Let's do three \"experiments\". The first one should be the base model with only one layer and trained for 300 epochs. The second one could be with two layers and trained for 300 epochs. The final one could have two layers and be trained for 500 epochs. \n#\n# Let's create some data and try it!\n\n# + id=\"6XTw7cKQnCu6\"\n# Before tackling \"experiments\", let's create some quick functions for getting evaluation metrics\n\ndef evaluate_nn(y_test, y_pred):\n mae = tf.keras.losses.MAE(y_test, y_pred).numpy()\n mse = tf.keras.losses.MSE(y_test, y_pred).numpy()\n huber = tf.keras.losses.huber(y_test, y_pred, delta = 1.0).numpy()\n return mae, mse, huber\n\n\n# + id=\"ZVJiibXRijHg\"\n# First experiment\ntf.random.set_seed(42)\nmodel1 = tf.keras.Sequential()\nmodel1.add(tf.keras.layers.Dense(1))\n\nmodel1.compile(\n loss = tf.keras.losses.mse,\n optimizer = tf.keras.optimizers.SGD(),\n metrics = ['mse', 'mae']\n)\n\nmodel1.fit(x_train, y_train, epochs = 300, verbose = 0);\n\n# + id=\"F3SMpmT0inva\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 428} outputId=\"99ed482b-685a-4d9b-8c63-467f270ec3f8\"\nmodel1_pred = model1.predict(x_test)\nplot_predictions(x_train, y_train, x_test, y_test, model1_pred);\n\n# + [markdown] id=\"5Vk9OKC_mMP1\"\n# We can see that the learned relationship is linear since we have only one layer and it's activation is linear activation. Let's evaluate it and try another model.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"REgQSZjZnYhp\" outputId=\"9f151e2e-e677-46b6-f150-98419957006e\"\nresults1 = evaluate_nn(y_test, tf.squeeze(model1_pred))\nprint('MAE:', results1[0])\nprint('MSE:', results1[1])\nprint('Huber:', results1[2])\n\n# + id=\"j3DJNBKqmb7L\"\n# Experiment 2\nmodel2 = tf.keras.Sequential()\nmodel2.add(tf.keras.layers.Dense(100, activation = 'relu'))\nmodel2.add(tf.keras.layers.Dense(100, activation = 'relu'))\nmodel2.add(tf.keras.layers.Dense(1))\n\nmodel2.compile(loss = tf.keras.losses.mse,\n optimizer = tf.keras.optimizers.SGD(),\n metrics = ['mse', 'mae'])\n\nmodel2.fit(x_train, y_train, epochs = 300, verbose = 0);\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 465} id=\"q6bOBpkDm1x8\" outputId=\"1a8c80c0-9424-4638-9a50-bc28e63bb939\"\nmodel2_pred = model2.predict(x_test)\nplot_predictions(x_train, y_train, x_test, y_test, model2_pred);\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"SK7aDdqam7Iq\" outputId=\"121fcdfc-6089-4d5c-e2be-b180f7a0dbf7\"\nresults2 = evaluate_nn(y_test, tf.squeeze(model2_pred))\nprint('MAE:', results2[0])\nprint('MSE:', results2[1])\nprint('Huber:', results2[2])\n\n# + [markdown] id=\"88YMy4j_oMkK\"\n# > We can see this model is actually better than the previous one! Let's try the third experiment with 500 epochs, Adam optimizer and learning rate of 0.0001.\n\n# + id=\"sE70JEtBoYCa\"\n# Third experiment\nmodel3 = tf.keras.Sequential()\n\nmodel3.add(tf.keras.layers.Dense(100, activation = 'relu'))\nmodel3.add(tf.keras.layers.Dense(100, activation = 'relu'))\nmodel3.add(tf.keras.layers.Dense(1))\n\nmodel3.compile(\n loss = tf.keras.losses.mse,\n optimizer = tf.keras.optimizers.Adam(lr = 0.0001),\n metrics = ['mse', 'mae']\n)\n\nmodel3.fit(x_train, y_train, epochs = 500, verbose = 0);\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 465} id=\"J0FIBVOzpDly\" outputId=\"5b21e2fa-034a-4750-b99d-2beeefed8242\"\nmodel3_pred = model3.predict(x_test);\nplot_predictions(x_train, y_train, x_test, y_test, model3_pred);\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"zZFt9ICRpJ75\" outputId=\"13c1d7d7-2a9e-4b47-e689-17e89d21ba23\"\nresults3 = evaluate_nn(y_test, tf.squeeze(model3_pred))\nprint('MAE:', results3[0])\nprint('MSE:', results3[1])\nprint('Huber:', results3[2])\n\n# + [markdown] id=\"Ho8HKzGkpfE5\"\n# > This model is also very good. Let us compare the metrics of all three models next to each others.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"sW59FrkSpo1A\" outputId=\"ffe21a5f-98aa-46d5-c2a8-53b6b90c989b\"\nprint('MAE Model1:', results1[0], ' MAE Model2:', results2[0], ' MAE Model3:', results3[0])\nprint('MSE Model1:', results1[1], ' MSE Model2:', results2[1], ' MSE Model3:', results3[1])\nprint('Huber Model1:', results1[2], ' Huber Model2:', results2[2], ' Huber Model3:', results3[2])\n\n# + [markdown] id=\"2zl6OFWAp584\"\n# Base on the previous results, we can conclude that Model 3 is the best one. However, note that the difference is practically negligible. Furthermore, we didn't use validation set as well, which could mean that the possibility of overfitting on the test data exists.\n\n# + id=\"m7frvhytqRzI\"\n# Let's just create a new model with 5000 epochs, just for fun \n# although we already approcimated the function really well with model2 and model3 :) \n\nmodel4 = tf.keras.Sequential()\n\nmodel4.add(tf.keras.layers.Dense(100, activation = 'relu'))\nmodel4.add(tf.keras.layers.Dense(100, activation = 'relu'))\nmodel4.add(tf.keras.layers.Dense(1))\n\nmodel4.compile(\n loss = tf.keras.losses.mse,\n optimizer = tf.keras.optimizers.Adam(lr = 0.0001),\n metrics = ['mse', 'mae']\n)\n\nmodel4.fit(x_train, y_train, epochs = 5000, verbose = 0);\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 465} id=\"hKWdHBujrEBp\" outputId=\"296ce94b-991a-4ab3-e835-bf48cc397948\"\nmodel4_pred = model4.predict(x_test)\nplot_predictions(x_train, y_train, x_test, y_test, model4_pred);\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"no2qepD8rMR_\" outputId=\"37a5a75b-e185-4296-f753-c488046a6465\"\nresults4 = evaluate_nn(y_test, tf.squeeze(model4_pred))\nprint('MAE:', results4[0])\nprint('MSE:', results4[1])\nprint('Huber:', results4[2])\n\n# + [markdown] id=\"SG77nrifrVHh\"\n# Based on these results, we can conclude that training our model for longer will not always lead to better results. In essence, if we can approximate the function really well with 300 or 500 epochs, there is no need to go over that since the results will be the same. Therefore, we can always start with smaller models in order to see if they work and increase the complexity of the model only if it is necessary. \n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"1lkLybOlrlT-\" outputId=\"b8a0d02a-aae6-4f7c-c325-eb98813414e4\"\n# Let's put evaluation metrics into a pandas dataframe\nimport pandas as pd \n\nmodel_results = [['model1', results1[0], results1[1], results1[2]],\n ['model2', results2[0], results2[1], results2[2]],\n ['model3', results3[0], results3[1], results3[2]],\n ['model4', results4[0], results4[1], results4[2]]\n ]\n\nresult_metrics = pd.DataFrame(model_results, columns = ['Model', 'MAE', 'MSE', \"HUBER\"])\nprint(result_metrics)\n\n# + [markdown] id=\"HvMb1stsszs4\"\n#

\n# Of course, whitle tackling a real-world problem we would experiment with a lot of different models, so tracking their losses this way could become tedious. Obviously, we woudln't do that (this was just for the sake of learning) - we would use some better ways to track our experiments.\n# Those tools are:\n#\n#\n# * TensorBoard - a component of the TF library to help track modelling experiments\n# * Weights & Biases - a tool for tracking all kinds of machine learning experimens (plugs straight into TensorBoard)\n#\n# We will cover these soon enough.\n#\n#\n\n# + [markdown] id=\"zp_ZtxEyuSPC\"\n# ### Saving and Loading the Model\n\n# + [markdown] id=\"bsitvlKaujFl\"\n# Let's say that we have tried a few models and we want to save/export the specific one (model3 in this case, since it proved to be the most optimal one). In essence, how do we export a model from Google Colab or Jupyter Notebook?\n#\n# There are a [few ways to save our model](https://www.tensorflow.org/tutorials/keras/save_and_load). \n#\n#\n# 1. We can save checkpoints during training and if something interrupts the training we can pick up where we left off\n# 2. With the SavedModel format (also useful for continuing with training)\n# 3. With HDF5 format (also useful for continuing with training)\n#\n#\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"c8kGZOohucPs\" outputId=\"6bfcf3bb-072f-429c-cc13-124ace54094d\"\n# Save the model using the savedmodel format\n# It saves it in Google Colab!\nmodel3.save('best_model')\n\n# Let's save it as HDF5 format \nmodel3.save('best_model.h5')\n\n# + [markdown] id=\"UyeJJdHqxQcE\"\n# As a rule of a thumb, if we want to use the model inside TF, when it is better to save it in a SavedModel format, while HDF5 is more suitable for other purposses.\n\n# + id=\"Hwh76RZAv5-E\"\n# Let's try to load the model, we can load it from both formats\nloaded_model = tf.keras.models.load_model('best_model.h5')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"TBm9mJYow7-J\" outputId=\"dd7f93b0-79be-4774-a8bf-00a05c22497c\"\nloaded_model.summary()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 422} id=\"2NmaFStlw9Sy\" outputId=\"6494fcd6-8a35-473e-f5ef-3fba2ba3804e\"\nfrom tensorflow.keras.utils import plot_model\nplot_model(loaded_model, show_shapes = True)\n\n# + [markdown] id=\"ZtgrkP2ZwdcH\"\n# So, how can we download files from the google colab?\n#\n#\n#\n# 1. We can go to the \"files\" tab and right click on the file we are after and then click \"download\"\n# 2. We can use code (see the cell below)\n# 3. Save to Google Drive by conencting Google Drive and copying there\n#\n#\n#\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 17} id=\"c8TYXzcuwnmw\" outputId=\"1459d924-7cd1-4125-e109-a36be2acdff8\"\n# Download a file from Google Colab\nfrom google.colab import files \nfiles.download(\"/content/best_model.h5\") # paste the path inside the parentheses\n\n# + [markdown] id=\"t0lF57Ak1I1O\"\n# ### Medical Cost Dataset - NN Approach\n\n# + id=\"utP8iVcD10wq\"\n# Import libraries\nimport numpy as np \nimport pandas as pd \nimport matplotlib.pyplot as plt\nimport tensorflow as tf \n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 142} id=\"z9ou4n5Vxgv2\" outputId=\"8453b5ec-bbba-412f-c8e1-b904f3f573e1\"\n# Reading insurance dataset\ndata_url = 'https://raw.githubusercontent.com/stedy/Machine-Learning-with-R-datasets/master/insurance.csv'\ninsurance = pd.read_csv(data_url)\ninsurance.head(3)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"g7s0UdADxgtU\" outputId=\"6a757474-2845-4c7c-97dc-3fbfccd888b5\"\n# Let's convert strings into numbers\nprint(insurance['sex'].unique())\nprint(insurance['smoker'].unique())\nprint(insurance['region'].unique())\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 142} id=\"wknQnsvuxgrJ\" outputId=\"acd4f50e-d510-4e0c-d67a-1255015a3637\"\n# One hot encoding\ninsurance_onehot = pd.get_dummies(insurance)\ninsurance_onehot.head(3)\n\n# + id=\"m6dQ21pZxgm5\"\n# split data into X, Y, and then into training and test sets\n\nX = insurance_onehot[insurance_onehot.columns[insurance_onehot.columns != 'charges']]\ny = insurance_onehot['charges']\n\nfrom sklearn.model_selection import train_test_split \nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 42)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"GzyGUPysx1NX\" outputId=\"5c065f3b-7827-4fa5-d5ce-9a66dcac44e9\"\nprint(X_train.shape)\nprint(X_test.shape)\nprint(y_train.shape)\nprint(y_test.shape)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"4qfSIosYwhtu\" outputId=\"64cbce37-1cc8-4419-99d4-27e5fae1b028\"\n# USING MSE AS THE LOSS FUNCTION\ntf.random.set_seed(42)\ninsurance_model = tf.keras.Sequential(name = 'Insurance_Model')\nfor i in range(10):\n insurance_model.add(tf.keras.layers.Dense(100, activation = 'relu'))\ninsurance_model.add(tf.keras.layers.Dense(1))\n\ninsurance_model.compile(\n loss = tf.keras.losses.mse, \n optimizer = tf.keras.optimizers.Adam(learning_rate = 0.0001),\n metrics = ['mse', 'mae']\n)\n\ninsurance_model.fit(X_train, y_train, epochs = 300, verbose = 0)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 265} id=\"q-UvYnsKwhpI\" outputId=\"8a119fab-1fbc-4ce6-f12f-1b97bc3e43c2\"\nplt.scatter(insurance_model.predict(X_test), y_test);\n\n\n# + id=\"Cql7XJmBwhko\"\ndef evaluate_nn(y_test, y_pred):\n mae = tf.keras.losses.MAE(y_test, y_pred).numpy()\n mse = tf.keras.losses.MSE(y_test, y_pred).numpy()\n huber = tf.keras.losses.huber(y_test, y_pred, delta = 1.0).numpy()\n return mae, mse, huber\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"qGbgO6-twhiI\" outputId=\"d27e7c5f-4573-4067-de2b-d503c5660b16\"\nresults = evaluate_nn(y_test, tf.squeeze(insurance_model.predict(X_test)))\nprint('MSE AS THE LOSS FUNCTION:')\nprint('MAE: ', results[0])\nprint('MSE: ', results[1])\nprint('Huber: ', results[2])\n\n# + id=\"jyswvjRO1NIQ\"\n# USING MAE AS THE LOSS FUNCTION\ntf.random.set_seed(42)\ninsurance_model2 = tf.keras.Sequential(name = 'Insurance_Model')\nfor i in range(10):\n insurance_model2.add(tf.keras.layers.Dense(100, activation = 'relu'))\ninsurance_model2.add(tf.keras.layers.Dense(1))\n\ninsurance_model2.compile(\n loss = tf.keras.losses.mae, \n optimizer = tf.keras.optimizers.Adam(learning_rate = 0.0001),\n metrics = ['mae']\n)\n\nhistory = insurance_model2.fit(X_train, y_train, epochs = 300, verbose = 0) # putting inside history variable so that we can plot the training\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 265} id=\"ckS4Ctv21M7b\" outputId=\"f1613cad-66bb-486d-8c9f-f38857ac4bc9\"\nplt.scatter(insurance_model2.predict(X_test), y_test);\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"fvyxQuWJ1b-z\" outputId=\"3f5aff33-0276-4ec8-8c3b-14ac34e5ec01\"\nresults = evaluate_nn(y_test, tf.squeeze(insurance_model2.predict(X_test)))\nprint('MAE AS THE LOSS FUNCTION:')\nprint('MAE: ', results[0])\nprint('MSE: ', results[1])\nprint('Huber: ', results[2])\n\n# + [markdown] id=\"hZJC5Uaf2gZZ\"\n# > We can see that this model is better than the previous one.\n#\n# Therefore, we can use the second model which, on average, makes the mistake of $1790, which is pretty nice.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 296} id=\"40VIRrDL3HMk\" outputId=\"ee4b41ef-40ed-4fdb-ac6c-8a20631b715f\"\n# Let's plot the history of the second model\nloss_history = pd.DataFrame(history.history)\nloss_history.plot()\nplt.ylabel('Loss')\nplt.xlabel('Epochs')\n\n# + [markdown] id=\"6HqpZCmO5DJF\"\n# \"LOSS\" and \"MAE\" are the same line on the previous graph, since MAE was the metric we used as the loss function, and also the metric which we wanted to save.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 204} id=\"SeghbpKG49di\" outputId=\"963c0910-7e5e-431c-e46e-fd9f806ef965\"\nloss_history.head()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 542} id=\"xcW9sAse4ssC\" outputId=\"2d5184d0-3ef5-425a-e5b0-f40afdc8a506\"\n# Or, alternatively, let's plot it with plotly\nimport plotly.express as px \nimport plotly.io as pio\npio.templates.default = 'simple_white'\npx.line(\n loss_history, \n x = loss_history.index, \n y = 'mae', \n labels = {'index' : 'EPOCHS', 'mae' : ' MEAN ABSOLUTE ERROR'}\n )\n\n# + [markdown] id=\"mRUFyir-5N4b\"\n# Based on this graph, we can conclude a few things:\n#\n#\n# 1. MAE drops relativelly quickly, which means that everything is okay with this neural network\n# 2. Then it probably gets stuck in some part of the function\n# 3. Then, a new sudden drop occurrs\n# 4. MAE is pretty stable after 100 epochs\n#\n#\n# So, how do we know when to stop the training? The answer to that question is **[early stopping](https://www.tensorflow.org/api_docs/python/tf/keras/callbacks/EarlyStopping)**. In essence, we stop it once it stops improving the certain metric.\n#\n#\n\n# + [markdown] id=\"Ir7tZxuV63RO\"\n# ### Preprocessing Data (Normalization and Standardization)\n\n# + [markdown] id=\"SUP6_Hnw0kNU\"\n# In order to make the training of a neural network faster (and to even get better results) is to scale features. In other words, we can normalize or standardize features. \n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 282} id=\"IGajnmtP07pV\" outputId=\"bd71c8f0-4d85-4339-f672-736d92c4cca9\"\n# Let's create some histograms\nX['age'].plot(kind = 'hist')\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 282} id=\"_QsnrzvP1xkR\" outputId=\"e1ad96ef-f747-42a3-847f-4c62b24f457d\"\nX['bmi'].plot(kind = 'hist')\n\n# + [markdown] id=\"4Q40mUNR1zYN\"\n# We can clearly see these variables have completely different scales, which is fine. However, it would be much better if we normalize them, or convert all values to between 0 and 1 while reserving the original distribution of our data. That way, we have the same range of each variable and the training of a neural network would be much faster.\n#\n# We can do that with `MinMaxScaler` from `sklearn` and normalization is used as a default scaler with neural networks. On the other hand, we can standardize variables using `StandardScaler` from `sklearn`. \n\n# + id=\"3F6NumjW2R_n\"\nfrom sklearn.compose import make_column_transformer\nfrom sklearn.preprocessing import MinMaxScaler, OneHotEncoder \n\n# + id=\"nYp8LQox3AVL\"\n# Create a column transformer\ncolumn_transformer = make_column_transformer(\n (MinMaxScaler(), ['age', 'bmi', 'children']),\n (OneHotEncoder(handle_unknown = 'ignore'), ['sex', 'smoker', 'region']))\n\n# Create X and y\nX = insurance.drop('charges', axis = 1)\ny = insurance['charges']\n\n# Get train and test data\nfrom sklearn.model_selection import train_test_split \nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 42)\n\n# Fit the column transformer to our training data\n# We want to fit to training data and use that fit for the test data as well\ncolumn_transformer.fit(X_train)\n\n# Normalize training and test data \nX_train_normal = column_transformer.transform(X_train)\nX_test_normal = column_transformer.transform(X_test)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 204} id=\"0b0XMvGq31Bt\" outputId=\"e5a054c0-6a7d-45d0-8f79-f918f6cad10f\"\nX_train.iloc[:5, :]\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"H4BI70_-5E5U\" outputId=\"1e4c5d6b-2392-4582-e237-dcde308f0895\"\nX_train_normal[:5, :]\n\n# + [markdown] id=\"CkqhfAMO5JMd\"\n# Okay, so we have normalized features, Let's build the same neural network model and compare the results!\n\n# + id=\"s6S7jdXt5xNw\"\n# USING MAE AS THE LOSS FUNCTION\ntf.random.set_seed(42)\ninsurance_model3 = tf.keras.Sequential(name = 'Insurance_Model')\nfor i in range(10):\n insurance_model3.add(tf.keras.layers.Dense(100, activation = 'relu'))\ninsurance_model3.add(tf.keras.layers.Dense(1))\n\ninsurance_model3.compile(\n loss = tf.keras.losses.mae, \n optimizer = tf.keras.optimizers.Adam(learning_rate = 0.0001),\n metrics = ['mae']\n)\n\nhistory = insurance_model3.fit(X_train_normal, y_train, epochs = 300, verbose = 0) # putting inside history variable so that we can plot the training\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 265} id=\"yETGwrc86ELq\" outputId=\"beba945d-3c16-4ca8-a43d-aa25d2c6b10a\"\nplt.scatter(insurance_model3.predict(X_test_normal), y_test);\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"pM215LQ056b0\" outputId=\"3d606418-7741-475a-b85b-fe71301924a5\"\nresults = evaluate_nn(y_test, tf.squeeze(insurance_model3.predict(X_test_normal)))\nprint('MAE AS THE LOSS FUNCTION:')\nprint('MAE: ', results[0])\nprint('MSE: ', results[1])\nprint('Huber: ', results[2])\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 296} id=\"eps3JxWI5-X8\" outputId=\"45dab4ca-4b71-4d84-b6b9-6c3f4fffb9be\"\n# Let's plot the history of the second model\nloss_history = pd.DataFrame(history.history)\nloss_history.plot()\nplt.ylabel('Loss')\nplt.xlabel('Epochs')\n\n# + [markdown] id=\"vekcItXR6J0m\"\n# Now this is really beautiful! \n# First of all, we can see that the convergence of the algorithm is much smoother - we don't have that plateu we had with non-normalized features! In other words, in this situation the training is much better and faster! Second of all, MAE is a bit lower that in the previous model! More specifically, it is lower by ~$80. \n#\n# This is what we want - to speed up the training of our model and to get even better results with the same configurations!\n\n# + id=\"-QkIE5bW6lYq\"\n\n","repo_name":"emirdemic/Learning-TensorFlow","sub_path":"TensorFlow.ipynb","file_name":"TensorFlow.ipynb","file_ext":"py","file_size_in_byte":59427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"25126513095","text":"import pandas as pd\nimport numpy as np\nfrom scipy.stats import t\nfrom scipy.stats import norm\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport os\nimport datetime as dt\nfrom datetime import datetime\n# %matplotlib inline\n# %config InlineBackend.figure_format = 'png'\n\nos.listdir()\n\n# ### Overview of the DataSet\n\nos.getcwd()\n\ndf = pd.read_csv('.\\data/london_merged.csv')\n\ndf\n\ndf.head()\n\ndf.columns\n\n# ### Renaming Columns\n\ndf.columns = ['timestamp', 'number', 'temperature', 'temperature_feels', 'hum', 'wind_speed', 'weather_code',\n 'is_holiday', 'is_weekend', 'season']\n\ndf.columns\n\npd.to_datetime(df['timestamp'])\n\n# ### Converting to Datetime the dates\n\ndf['timestamp'] = pd.to_datetime(df['timestamp'])\n\n# ### Adding Year, Month, Day, to the dataset\n\ndf['month'] = df.timestamp.apply(lambda x : x.strftime('%m'))\n\ndf.columns\n\ncolumn_names = ['timestamp', 'month', 'number', 'temperature', 'temperature_feels',\n 'hum', 'wind_speed', 'weather_code', 'is_holiday', 'is_weekend',\n 'season']\n\n# * Reorganizing the columns\n\ndf = df.reindex(columns=column_names)\n\n# * Year, Days, Day_name, Week number\n\ndf['year'] = df.timestamp.apply(lambda x : x.strftime('20%y'))\n\ndf['day'] = df.timestamp.apply(lambda x : x.strftime('%d'))\n\ncolumn_names = ['timestamp', 'year', 'month', 'day', 'number', 'temperature', 'temperature_feels',\n 'hum', 'wind_speed', 'weather_code', 'is_holiday', 'is_weekend',\n 'season']\n\ndf = df.reindex(columns=column_names)\n\ndf['day_name'] = df['timestamp'].dt.day_name()\n\ndf['week_number'] = df.timestamp.apply(lambda x : x.strftime('%U'))\n\n\ndf['time'] = df.timestamp.apply(lambda x : x.strftime('%H:%M'))\n\ndf['date']=df.date.apply(lambda x : x.strftime('%d-%m-20%Y'))\n\n\n\n# * Reorganizing the columns again\n\ndf.columns\n\ncolumn_names = ['timestamp','date', 'year', 'month', 'day', 'day_name', 'week_number', 'time', 'number', 'temperature',\n 'temperature_feels', 'hum', 'wind_speed', 'weather_code', 'is_holiday',\n 'is_weekend', 'season']\n\ndf = df.reindex(columns=column_names)\n\ndf\n\ndf\n\n# * Changing number of month to name of the month\n\ndf['month'] = pd.to_datetime(df['month'], format='%m').dt.month_name().str.slice(stop=3)\n\n\ndf.columns\n\ndf.columns = ['timestamp', 'date', 'year', 'month', 'day', 'day_name', 'week_number',\n 'time', 'bike_number', 'temperature', 'temperature_feels', 'hum',\n 'wind_speed', 'weather_code', 'is_holiday', 'is_weekend', 'season']\n\ndf.to_csv('london_merged_v1.csv')\n\n# ## Null Values\n\ndf.isna().sum()\n\n# ### Saving the updates and cleanning in a new Data Set\n\ndf = pd.read_csv('london_merged_v1.csv')\n\ndf = df.reset_index()\n\ndf.drop('Unnamed: 0', axis=1, inplace=True)\n\ndf.to_csv('london_merged_v1.csv', index=False)\n\ndf = pd.read_csv('london_merged_v1.csv')\n\ndf.sample['']\n\n# ## Removing 2017 Rows\n\ndf = pd.read_csv('.\\data/london_merged_v3.csv')\n\ndf.pivot_table(index='year', columns='day_name', values='bike_number', aggfunc='mean').round(2)\n\n# ### Comment : 2017 looks empty with some days of the week. \n\n# * Investigation about NAN values of 2017\n\n(df['year']==2017).value_counts()\n\n(df['year']==2016).value_counts()\n\n(df['year']==2015).value_counts()\n\ndf.loc[df['year']==2017]\n\n# * Conclussions: YEAR ['2017'] has only 72 entries from 01-01-2017 to 03-03-2017\n\n# ### Removing Entries for 2017 \n\nto_remove = df.loc[df['year']==2017]\n\nto_remove\n\ndf.drop(to_remove.index, axis=0, inplace=True)\n\ndf\n\ndf.loc[df['year']==2017]\n\n# +\n#df.to_csv('london_merged_v4.csv', index=False)\n# -\n\nimport Assumptions\n\ntester = Assumptions.Assumption_Tester_OLS(df1.drop(columns_to_drop, axis=1), y)\n\ntester.run_all()\n\nmodel=ols('MinutesOfBeingAwake ~ NumberOfAwakings + LengthOfRestInMinutes + month_name', data=df)\nmodel_fit=model.fit()\nmodel_fit.summary()\n","repo_name":"isra-st/London_Bike_Sharing","sub_path":"Cleanning_Exploratory_Data_Analysis_Sharing_Bike.ipynb","file_name":"Cleanning_Exploratory_Data_Analysis_Sharing_Bike.ipynb","file_ext":"py","file_size_in_byte":3758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"28160709269","text":"# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# \"Open\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"60mHHdqD5NHQ\" outputId=\"b07fc2dc-f61a-46fa-f389-0cb8db9d68e7\"\nimport tensorflow as tf\n\n# Initialize two constants\nx1 = tf.constant([1,2,3,4])\nx2 = tf.constant([5,6,7,8])\n\n# Multiply\nresult = tf.multiply(x1, x2)\n\n# Print the result\nprint(result)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 1000} id=\"DoC5g8jbJEkS\" outputId=\"e8d11617-bb04-4390-d284-7f23648be0a5\"\n# Import pandas \nimport pandas as pd\n\n# Read in white wine data \nwhite = pd.read_csv(\"http://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv\", sep=';')\n\n# Read in red wine data \nred = pd.read_csv(\"http://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv\", sep=';')\n# Print info on white wine\nprint(white.info())\n\n# Print info on red wine\nprint(red.info())\n# First rows of `red` \nred.head()\n\n# Last rows of `white`\nwhite.tail()\n\n# Take a sample of 5 rows of `red`\nred.sample(5)\n\n# Describe `white`\nwhite.describe()\n\n# Double check for null values in `red`\npd.isnull(red)\nimport matplotlib.pyplot as plt\n\nfig, ax = plt.subplots(1, 2)\n\nax[0].hist(red.alcohol, 10, facecolor='red', alpha=0.5, label=\"Red wine\")\nax[1].hist(white.alcohol, 10, facecolor='white', ec=\"black\", lw=0.5, alpha=0.5, label=\"White wine\")\n\nfig.subplots_adjust(left=0, right=1, bottom=0, top=0.5, hspace=0.05, wspace=1)\nax[0].set_ylim([0, 1000])\nax[0].set_xlabel(\"Alcohol in % Vol\")\nax[0].set_ylabel(\"Frequency\")\nax[1].set_xlabel(\"Alcohol in % Vol\")\nax[1].set_ylabel(\"Frequency\")\n#ax[0].legend(loc='best')\n#ax[1].legend(loc='best')\nfig.suptitle(\"Distribution of Alcohol in % Vol\")\n\nplt.show()\nimport numpy as np\nprint(np.histogram(red.alcohol, bins=[7,8,9,10,11,12,13,14,15]))\nprint(np.histogram(white.alcohol, bins=[7,8,9,10,11,12,13,14,15]))\nimport matplotlib.pyplot as plt\n\nfig, ax = plt.subplots(1, 2, figsize=(8, 4))\n\nax[0].scatter(red['quality'], red[\"sulphates\"], color=\"red\")\nax[1].scatter(white['quality'], white['sulphates'], color=\"white\", edgecolors=\"black\", lw=0.5)\n\nax[0].set_title(\"Red Wine\")\nax[1].set_title(\"White Wine\")\nax[0].set_xlabel(\"Quality\")\nax[1].set_xlabel(\"Quality\")\nax[0].set_ylabel(\"Sulphates\")\nax[1].set_ylabel(\"Sulphates\")\nax[0].set_xlim([0,10])\nax[1].set_xlim([0,10])\nax[0].set_ylim([0,2.5])\nax[1].set_ylim([0,2.5])\nfig.subplots_adjust(wspace=0.5)\nfig.suptitle(\"Wine Quality by Amount of Sulphates\")\n\nplt.show()\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nnp.random.seed(570)\n\nredlabels = np.unique(red['quality'])\nwhitelabels = np.unique(white['quality'])\n\nimport matplotlib.pyplot as plt\nfig, ax = plt.subplots(1, 2, figsize=(8, 4))\nredcolors = np.random.rand(6,4)\nwhitecolors = np.append(redcolors, np.random.rand(1,4), axis=0)\n\nfor i in range(len(redcolors)):\n redy = red['alcohol'][red.quality == redlabels[i]]\n redx = red['volatile acidity'][red.quality == redlabels[i]]\n ax[0].scatter(redx, redy, c=redcolors[i])\nfor i in range(len(whitecolors)):\n whitey = white['alcohol'][white.quality == whitelabels[i]]\n whitex = white['volatile acidity'][white.quality == whitelabels[i]]\n ax[1].scatter(whitex, whitey, c=whitecolors[i])\n \nax[0].set_title(\"Red Wine\")\nax[1].set_title(\"White Wine\")\nax[0].set_xlim([0,1.7])\nax[1].set_xlim([0,1.7])\nax[0].set_ylim([5,15.5])\nax[1].set_ylim([5,15.5])\nax[0].set_xlabel(\"Volatile Acidity\")\nax[0].set_ylabel(\"Alcohol\")\nax[1].set_xlabel(\"Volatile Acidity\")\nax[1].set_ylabel(\"Alcohol\") \n#ax[0].legend(redlabels, loc='best', bbox_to_anchor=(1.3, 1))\nax[1].legend(whitelabels, loc='best', bbox_to_anchor=(1.3, 1))\n#fig.suptitle(\"Alcohol - Volatile Acidity\")\nfig.subplots_adjust(top=0.85, wspace=0.7)\n\nplt.show()\n","repo_name":"NikyDS/sureStartND","sub_path":"Day7.ipynb","file_name":"Day7.ipynb","file_ext":"py","file_size_in_byte":3932,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"29048075798","text":"# +\n# # !pip3 install malaya\n\nimport malaya\nimport re\nfrom malaya.texts._text_functions import split_into_sentences\nfrom malaya.texts import _regex\n\ntokenizer = malaya.preprocessing._tokenizer\nsplitter = split_into_sentences\n\n# +\nimport glob\n\nstories = glob.glob('cnn/stories/*.story')\nlen(stories)\n\n\n# +\ndef is_number_regex(s):\n if re.match(\"^\\d+?\\.\\d+?$\", s) is None:\n return s.isdigit()\n return True\n\ndef preprocessing(string):\n string = re.sub('[^\\'\"A-Za-z\\-(),.$0-9 ]+', ' ', string.lower())\n tokenized = tokenizer(string)\n tokens = []\n for w in tokenized:\n if is_number_regex(w):\n tokens.append('')\n elif re.match(_regex._money, w):\n tokens.append('')\n elif re.match(_regex._date, w):\n tokens.append('')\n else:\n tokens.append(w)\n return tokens\n\ndef split_story(doc):\n index = doc.find('@highlight')\n story, highlights = doc[:index], doc[index:].split('@highlight')\n highlights = [h.strip() for h in highlights if len(h) > 0]\n stories = []\n for s in splitter(story):\n stories.append(preprocessing(s))\n summaries = []\n for s in highlights:\n summaries.append(preprocessing(s))\n return stories, summaries\n\n\n# -\n\nmin_src_nsents = 3\nmax_src_nsents = 20\nmin_src_ntokens_per_sent = 5\nmax_src_ntokens_per_sent = 30\nmin_tgt_ntokens = 5\nmax_tgt_ntokens = 500\nsep_token = '[SEP]'\ncls_token = '[CLS]'\n\nwith open(stories[0]) as fopen:\n story = fopen.read()\nstory, highlights = split_story(story)\n\n\n# +\ndef _get_ngrams(n, text):\n ngram_set = set()\n text_length = len(text)\n max_index_ngram_start = text_length - n\n for i in range(max_index_ngram_start + 1):\n ngram_set.add(tuple(text[i:i + n]))\n return ngram_set\n\n\ndef _get_word_ngrams(n, sentences):\n assert len(sentences) > 0\n assert n > 0\n\n words = sum(sentences, [])\n return _get_ngrams(n, words)\n\ndef cal_rouge(evaluated_ngrams, reference_ngrams):\n reference_count = len(reference_ngrams)\n evaluated_count = len(evaluated_ngrams)\n\n overlapping_ngrams = evaluated_ngrams.intersection(reference_ngrams)\n overlapping_count = len(overlapping_ngrams)\n\n if evaluated_count == 0:\n precision = 0.0\n else:\n precision = overlapping_count / evaluated_count\n\n if reference_count == 0:\n recall = 0.0\n else:\n recall = overlapping_count / reference_count\n\n f1_score = 2.0 * ((precision * recall) / (precision + recall + 1e-8))\n return {\"f\": f1_score, \"p\": precision, \"r\": recall}\n\n\ndef greedy_selection(doc_sent_list, abstract_sent_list, summary_size):\n def _rouge_clean(s):\n return re.sub(r'[^a-zA-Z0-9 ]', '', s)\n\n max_rouge = 0.0\n abstract = sum(abstract_sent_list, [])\n abstract = _rouge_clean(' '.join(abstract)).split()\n sents = [_rouge_clean(' '.join(s)).split() for s in doc_sent_list]\n evaluated_1grams = [_get_word_ngrams(1, [sent]) for sent in sents]\n reference_1grams = _get_word_ngrams(1, [abstract])\n evaluated_2grams = [_get_word_ngrams(2, [sent]) for sent in sents]\n reference_2grams = _get_word_ngrams(2, [abstract])\n\n selected = []\n for s in range(summary_size):\n cur_max_rouge = max_rouge\n cur_id = -1\n for i in range(len(sents)):\n if (i in selected):\n continue\n c = selected + [i]\n candidates_1 = [evaluated_1grams[idx] for idx in c]\n candidates_1 = set.union(*map(set, candidates_1))\n candidates_2 = [evaluated_2grams[idx] for idx in c]\n candidates_2 = set.union(*map(set, candidates_2))\n rouge_1 = cal_rouge(candidates_1, reference_1grams)['f']\n rouge_2 = cal_rouge(candidates_2, reference_2grams)['f']\n rouge_score = rouge_1 + rouge_2\n if rouge_score > cur_max_rouge:\n cur_max_rouge = rouge_score\n cur_id = i\n if (cur_id == -1):\n return selected\n selected.append(cur_id)\n max_rouge = cur_max_rouge\n\n return sorted(selected)\n\ndef get_xy(story, highlights):\n idxs = [i for i, s in enumerate(story) if (len(s) > min_src_ntokens_per_sent)]\n \n idxs = [i for i, s in enumerate(story) if (len(s) > min_src_ntokens_per_sent)]\n\n src = [story[i][:max_src_ntokens_per_sent] for i in idxs]\n src = src[:max_src_nsents]\n\n sent_labels = greedy_selection(src, highlights, 3)\n\n _sent_labels = [0] * len(src)\n for l in sent_labels:\n _sent_labels[l] = 1\n _sent_labels\n \n src_txt = [' '.join(sent) for sent in src]\n text = ' {} {} '.format(sep_token, cls_token).join(src_txt)\n text = '[CLS] %s [SEP]'%(text)\n cls_ids = [i for i, t in enumerate(text.split()) if t == cls_token]\n \n return text, cls_ids, _sent_labels\n\n\n# +\nimport collections\nimport json\n\ndef build_dataset(words, n_words, atleast=1):\n count = [['PAD', 0], ['GO', 1], ['EOS', 2], ['UNK', 3]]\n counter = collections.Counter(words).most_common(n_words)\n counter = [i for i in counter if i[1] >= atleast]\n count.extend(counter)\n dictionary = dict()\n for word, _ in count:\n dictionary[word] = len(dictionary)\n data = list()\n unk_count = 0\n for word in words:\n index = dictionary.get(word, 0)\n if index == 0:\n unk_count += 1\n data.append(index)\n count[0][1] = unk_count\n reversed_dictionary = dict(zip(dictionary.values(), dictionary.keys()))\n return data, count, dictionary, reversed_dictionary\n\n\n# +\n# from dask import delayed\n# import dask\n\n# def process(i):\n# with open(stories[i]) as fopen:\n# story = fopen.read()\n# story, highlights = split_story(story)\n# return get_xy(story, highlights)\n\n# train = []\n# for i in range(len(stories)):\n# im = delayed(process)(i)\n# train.append(im)\n \n# train = dask.compute(*train)\n# -\n\nwith open(stories[1]) as fopen:\n story = fopen.read()\nstory, highlights = split_story(story)\ntext, cls_ids, sent_labels = get_xy(story, highlights)\n\nlen(sent_labels), len(cls_ids), len(text.split())\n\n# +\nfrom tqdm import tqdm\n\ntexts, clss, labels = [], [], []\n\nfor i in tqdm(range(len(stories))):\n with open(stories[i]) as fopen:\n story = fopen.read()\n story, highlights = split_story(story)\n text, cls_ids, sent_labels = get_xy(story, highlights)\n if len(cls_ids) != len(sent_labels):\n continue\n texts.append(text)\n clss.append(cls_ids)\n labels.append(sent_labels)\n# -\n\nconcat = ' '.join(texts).split()\nvocabulary_size = len(list(set(concat)))\n_, count, dictionary, rev_dictionary = build_dataset(concat, vocabulary_size, atleast = 2)\nprint('vocab from size: %d'%(len(dictionary)))\nprint('Most common words', count[4:10])\n\n# +\nfrom sklearn.model_selection import train_test_split\n\ntrain_texts, test_texts, train_clss, test_clss, train_labels, test_labels = \\\ntrain_test_split(texts, clss, labels, test_size = 0.2)\n\n# +\nimport pickle\n\nwith open('dataset.pkl', 'wb') as fopen:\n pickle.dump({'train_texts': train_texts,\n 'test_texts': test_texts,\n 'train_clss': train_clss,\n 'test_clss': test_clss,\n 'train_labels': train_labels,\n 'test_labels': test_labels}, fopen)\n# -\n\nwith open('dictionary.pkl', 'wb') as fopen:\n pickle.dump({'dictionary': dictionary, 'rev_dictionary': rev_dictionary}, fopen)\n\n\n","repo_name":"huseinzol05/NLP-Models-Tensorflow","sub_path":"extractive-summarization/preprocessing-data.ipynb","file_name":"preprocessing-data.ipynb","file_ext":"py","file_size_in_byte":7398,"program_lang":"python","lang":"en","doc_type":"code","stars":1721,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"24414233237","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport torch\nimport cv2\nimport torchvision\nimport torchvision.transforms as transforms\nimport time\nfrom PIL import Image\n\n# +\nimg = np.asarray(Image.open('Desktop/bottleFrames/frame_0002.png')).astype(np.uint8)\nscale_w = img.shape[1] // 400\nscale_h = img.shape[0] // 300\nscaled = np.zeros((300, 400, img.shape[2]), dtype=img.dtype)\nfor i in range(300):\n for j in range(400):\n x = j * scale_w\n y = i * scale_h\n scaled[i, j] = img[y, x]\nframe_N = scaled.copy()\nframe_N = np.dot(frame_N[...,:3], [0.2126, 0.7152, 0.0722])\n\nimg = np.asarray(Image.open('Desktop/bottleFrames/frame_0001.png')).astype(np.uint8)\nscale_w = img.shape[1] // 400\nscale_h = img.shape[0] // 300\nscaled = np.zeros((300, 400, img.shape[2]), dtype=img.dtype)\nfor i in range(300):\n for j in range(400):\n x = j * scale_w\n y = i * scale_h\n scaled[i, j] = img[y, x]\nframe_N_1 = scaled.copy()\nframe_N_1 = np.dot(frame_N_1[...,:3], [0.2126, 0.7152, 0.0722])\n\nframe_N.shape\n\n\n# -\n\ndef inter16x(sa):\n \n def ldps(sa_):\n safety = 1000\n vec = [0,0]\n while safety > 0:\n min_sad = [256**2, (1,1)]\n mid_x = sa_[0] + vec[0]\n mid_y = sa_[1] + vec[1]\n for mvx, mvy in ([0,1], [1,0], [0,-1], [-1,0], [0,0]):\n x_ = mid_x + mvx\n y_ = mid_y + mvy\n org_ = search_area[y_:y_+16, x_:x_+16]\n sad = int(sum(abs(org_.flatten() - curr_mb.flatten())))\n if sad <= min_sad[0]:\n min_sad = [sad, (mvx, mvy)]\n if min_sad[1] == (0,0) or (x_ + min_sad[1][0] == 0 or y_ + min_sad[1][1] == 0) or (x_ + min_sad[1][0] > search_area.shape[0] - 17 or y_ + min_sad[1][1] > search_area.shape[1] - 17):\n return (min_sad[0], mid_x, mid_y)\n else:\n vec[0] += min_sad[1][0]\n vec[1] += min_sad[1][1]\n safety -= 1\n return (256**2, -1, -1)\n \n return ldps(sa)\n\n\n# +\nmotion_matrix = np.zeros((frame_N.shape[0] // 16 - 1, frame_N.shape[1] // 16 - 1), dtype=[('x', int), ('y', int)])\ni_idx = -1\nfor i in range(16, frame_N.shape[0] - 16, 16):\n i_idx += 1\n j_idx = -1\n for j in range(16, frame_N.shape[1] - 16, 16):\n j_idx += 1\n curr_mb = frame_N[i:i+16, j:j+16]\n search_area = frame_N_1[i-12:i+28, j-12:j+28]\n m_x, m_y = inter16x((12,12))[1:3]\n motion_matrix[i_idx][j_idx] = (12 - m_x, 12 - m_y)\n \nmotion_matrix\n# -\n\n\n","repo_name":"pstecklein/h264reuse","sub_path":"motionEstimationExample.ipynb","file_name":"motionEstimationExample.ipynb","file_ext":"py","file_size_in_byte":2554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"25"} +{"seq_id":"13781456947","text":"# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# \"Open\n\n# + [markdown] id=\"kZwvKHXO98Oc\"\n# Nombre: Ana Rodriguez Dominguez\n#\n# Link:https://colab.research.google.com/drive/10MbQCVK2pMZCCIQL8Q9jRzM1bUTgq_Ib?usp=sharing\n#\n# Github: http: //github.com/Anarguezd/03MIAR--Algoritmos-de-Optimizacion\n\n# + id=\"MnAxO9bZ-I_3\"\nimport math\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 53} id=\"ppPKs1DvBPq7\" outputId=\"3ad3cc13-9c87-42b2-d6c4-449f6c0af185\"\n#PROGRAMACION DINAMICA \n#Viaje por el rio\n\n#Definimos las tarifas de cada nodo:\ntarifas=[\n [0,5,4,3,999,999,999],\n [999,0,999,2,3,999,11],\n [999,999,0,1,999,4,10],\n [999,999,999,0,5,6,9],\n [999,999,999,999,0,999,6],\n [999,999,999,999,999,0,3],\n [999,999,999,999,999,999,0]\n ]\n#Definimos los precios de las tarifas:\ndef precios(tarifas):\n #calculamos el numero de nodos total\n N=len(tarifas[0])\n #iniciamos la tabla de precios\n precios= [ [9999]*N for i in [9999]*N]\n ruta= [ [\"\"]*N for i in [\"\"]*N]\n #construimos la matriz precios, recorriendo todos los nodos (origen-destino)\n for i in range(N-1):\n for j in range(i+1,N):\n MIN= tarifas[i][j]\n ruta[i][j] = i\n\n for k in range(i,j):\n if precios[i][k] + tarifas[k][j]< MIN:\n MIN=min(MIN, precios[i][k]+ tarifas[k][j])\n ruta[i][j]= k\n precios[i][j] = MIN\n return precios, ruta\n\nprecios, ruta= precios(tarifas)\n\n\n#Calculo de la ruta usando la matriz ruta:\ndef calcular_ruta(ruta, desde, hasta):\n if desde == hasta:\n return desde\n else:\n return str(calcular_ruta(ruta,desde,ruta[desde][hasta])) + ',' + str(ruta[desde][hasta])\nprint(\"La ruta es: \")\n\ncalcular_ruta(ruta,0,6)\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"773nsxNOG7gF\" outputId=\"de5a3561-c408-4292-f39b-a470e5ce4ebf\"\n#RAMIFICACION Y PODA\n#Asignacion de tareas\n#TAREAS\n#A\n#G\n#E\n#N\n#T\n#E\n#S\ncostes=[[11,12,18,40],\n [14,15,13,22],\n [11,17,19,23],\n [17,14,20,28]\n ]\n#Calculo del valor de una solucion parcial\ndef valor(S,costes):\n valor=0\n for i in range(len(S)):\n valor += costes[i][S[i]]\n return valor\n\nvalor((0,1,2,3),costes)\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"5y0XPCy8OHB_\" outputId=\"d465096c-52fb-4bd4-a5c3-c161aa2abeec\"\n#Coste inferior para soluciones parciales\ndef CI(S,costes):\n valor= 0\n #Valores establecidos\n for i in range(len(S)):\n valor+=costes[i][S[i]]\n #Estimacion\n for i in range(len(S),len(costes)):\n valor+=min([costes[j][i] for j in range(len(S), len(costes))])\n return valor\n\n\nCI((0,1),costes)\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"naJo_if1PZt9\" outputId=\"d55f1c5e-2f18-46af-ea0b-d442e2661787\"\n#Funcion para ramificar\n#Generar tantos hijos como posibilidades haya el siguiente elemento de la tupla\n#(0,)-> (0,1), (0,2), (0,3)\n\ndef crear_hijos(nodo,N):\n hijos=[]\n for i in range(N):\n if i not in nodo:\n hijos.append({'s':nodo + (i,)})\n return hijos\n\ncrear_hijos((0,),4)\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"iiy0dtoRQtLj\" outputId=\"cf522635-3a77-4ca2-eab8-633e4d49dc8d\"\n#Proceso principal; Ramificacion y poda\ndef ramificacion_y_poda(costes):\n #Construccion iterativa de soluciones(arbol). En cada etapa asignamos un agente(ramas).\n #Nodos del grafo {s(1,2), CI:3, CS:5}\n dimension=len(costes)\n mejor_solucion=tuple(i for i in range(len(costes)))\n cotasup= valor(mejor_solucion, costes)\n\n nodos=[]\n nodos.append({'s':(), 'ci':CI((),costes)})\n\n iteracion=0\n while(len(nodos)>0):\n iteracion+=1\n nodo_prometedor=[min(nodos, key=lambda x:x['ci'])][0]['s']\n #Ramificacion\n #Generamos los hijos\n hijos=[{'s':x['s'],'ci':CI(x['s'], costes)}for x in crear_hijos(nodo_prometedor, dimension)]\n #Revisamos la cota superior y nos quedamos con la mejor solucion, si llegamos a una solucion final\n nodo_final=[x for x in hijos if len(x['s'])==dimension]\n if len(nodo_final)>0:\n if nodo_final[0]['ci'] thresh else \"black\")\n\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n plt.tight_layout()\n\nplot_confusion_matrix(cm, ['Normal', 'Pneumonia'], normalize=True)\nplt.show()\n","repo_name":"MaxImmure/CV_Project","sub_path":"Project CV.ipynb","file_name":"Project CV.ipynb","file_ext":"py","file_size_in_byte":18410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"25"} +{"seq_id":"8403942350","text":"# %load_ext autoreload\n# %autoreload 2\n\nfrom IPython.display import display, HTML\ndisplay(HTML(\"\"))\n\n# +\nimport torch\n\nimport aesthetic_tensor as ae\n\nae.aesthetify()\n# -\n\ntorch.rand(5, 10, 10).ae.N.zoom(10).img\n\ntorch.randn(3, 1000).ae.N.hist(figsize=(3, 2))\n\nA = torch.rand(2, 16, 16)\nA.ae\n\nA = torch.rand(6, 3, 10, 10)\n\nA.ae.N.zoom(10).uint8.hwc.pil\n\nslider = ae.ipw.IntSlider(min=0, max=400, value=30)\nslider\n\n(torch.linspace(0, 100, 500).sin()).ae.hook(slider, lambda T, s: T[s:s+50].plot(figsize=(6, 2)))\n\ntorch.rand(3, 10, 10).ae.N.cmap('jet', dim=0).zoom(10).hwc.pil\n\nslider = ae.ipw.IntSlider(value=30)\nslider\n\nT = torch.randn(100, 30, 30).ae.N.imshow(figsize=(3, 3))\n\nae.hook(slider, lambda s: T.raw[s])\n\nT1 = torch.rand(1, 10, 10)\nT2 = torch.rand(1, 10, 10)\nl = torch.linspace(0, torch.pi*2, 200).sin().view(-1, 1, 1)\nR = (T1 * l + (1 - l) * T2).ae\n\nR\n\ntorch.rand(2, 3, 10, 10).ae.N.zoom(10).gif(fps=1)\n\n\n","repo_name":"ichko/aesthetic-tensor","sub_path":"notebooks/aesthetic_notebook.ipynb","file_name":"aesthetic_notebook.ipynb","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"25"} +{"seq_id":"16426130379","text":"import pandas as pd \nimport numpy as np \nimport matplotlib.pyplot as plt \nimport seaborn as sns \nfrom sklearn.model_selection import train_test_split \nfrom sklearn.linear_model import LinearRegression\nfrom sklearn import metrics\nfrom patsy import dmatrices\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.compose import ColumnTransformer\nfrom statsmodels.stats.outliers_influence import variance_inflation_factor\nfrom scipy.stats.mstats import winsorize\n# %matplotlib inline\npd.set_option('display.float_format', lambda x: '%.3f' % x)\n\n# +\n# data=pd.read_csv('Life Expectancy Data.csv')\nimport types\nimport pandas as pd\nfrom botocore.client import Config\nimport ibm_boto3\n\ndef __iter__(self): return 0\n\n# @hidden_cell\n# The following code accesses a file in your IBM Cloud Object Storage. It includes your credentials.\n# You might want to remove those credentials before you share the notebook.\nclient_fc6149441fef45e394b6af2f99827c6f = ibm_boto3.client(service_name='s3',\n ibm_api_key_id='DADyosjuHRgbciww4Z7hoDVO95d9IeCnrbaGtGE-EGpn',\n ibm_auth_endpoint=\"https://iam.cloud.ibm.com/oidc/token\",\n config=Config(signature_version='oauth'),\n endpoint_url='https://s3.eu-geo.objectstorage.service.networklayer.com')\n\nbody = client_fc6149441fef45e394b6af2f99827c6f.get_object(Bucket='lifeexpectancy-donotdelete-pr-nazxuxjseoibxh',Key='Life Expectancy Data.csv')['Body']\n# add missing __iter__ method, so pandas accepts body as file-like object\nif not hasattr(body, \"__iter__\"): body.__iter__ = types.MethodType( __iter__, body )\n\ndata= pd.read_csv(body)\ndata.head()\n# -\n\ndata.head()\n\ndata.shape\n\ndata.info()\n\ndata[['Country','Status']] = data[['Country','Status']].astype('category')\n\ndata.drop(['Country'], axis=1, inplace=True)\n\n# +\n#rename column\norig_cols = list(data.columns)\nnew_cols = []\nfor col in orig_cols:\n new_cols.append(col.strip().replace(' ', ' ').replace(' ', '_').lower())\ndata.columns = new_cols\n\ndata.rename(columns={'thinness_1-19_years':'thin_1','thinness_5-9_years':'thin_5','hiv/aids':'hivaids','under-five_deaths':\\\n 'under_five_deaths'}, inplace=True)\n\n# # convert columns name into lowercase\n# df.columns = map(str.lower, df.columns)\n# df\n# -\n\ndata.isna().sum()*100/data.isna().count()\n\ncont_vars = list(data.columns)[3:]\ndef outliers_visual(data):\n plt.figure(figsize=(15, 40))\n i = 0\n for col in cont_vars:\n i += 1\n plt.subplot(9, 4, i)\n plt.boxplot(data[col])\n plt.title('{} boxplot'.format(col))\n plt.show()\noutliers_visual(data)\n\n# +\ndata_without_outliers = data.copy()\n\nplt.figure(figsize=(15,6))\nplt.subplot(1,2,1)\noriginal_life_expectancy = data_without_outliers['life_expectancy']\nplt.boxplot(original_life_expectancy)\nplt.title(\"original_Life_Expectancy\")\n\nplt.subplot(1,2,2)\nwinsorized_life_expectancy = winsorize(data_without_outliers['life_expectancy'],(0.01,0))\nplt.boxplot(winsorized_life_expectancy)\nplt.title(\"winsorized_life_expectancy\")\n\nplt.show()\n\n# +\nplt.figure(figsize=(18,6))\n\nplt.subplot(1,2,1)\noriginal_adult_mortality = data_without_outliers['adult_mortality']\nplt.boxplot(original_adult_mortality)\nplt.title(\"original_adult_mortality\")\n\nplt.subplot(1,2,2)\nwinsorized_adult_mortality = winsorize(data_without_outliers['adult_mortality'],(0,0.03))\nplt.boxplot(winsorized_adult_mortality)\nplt.title(\"winsorized_adult_mortality\")\n\nplt.show()\n\n# +\nimport seaborn as sns\nimport matplotlib.pyplot as mplt\n\ncorrmat = data.corr()\ntop_corr_features= corrmat.index\nmplt.figure(figsize=(20,20))\ng=sns.heatmap(data[top_corr_features].corr() ,annot=True , cmap=\"RdYlGn\")\n# -\n\ndata.corr()\n\nfrom scipy.stats import pearsonr\nfrom scipy.stats import spearmanr\n\n\ndef linearity(data,target):\n cor_list = []\n for col in data.drop(target, axis = 1).columns:\n if col in data.select_dtypes('category').columns:\n cor_val = spearmanr(data[col], data[target])\n else:\n cor_val = pearsonr(data[col], data[target])\n cor_dict = {\"Predictor\": col,\n \"Correlation\": cor_val[0]\n }\n cor_list.append(cor_dict)\n cor_values = pd.DataFrame(cor_list)\n return cor_values\n\n\nlinearity(data,'life_expectancy')\n\nX_ = data.drop([\"life_expectancy\"], axis = 1)\ny = data.life_expectancy.values\n\nX = pd.get_dummies(X_, columns = data.select_dtypes('category').columns, drop_first = True)\nX.head()\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 42)\nprint(\"X Train:\", X_train.shape)\nprint(\"X Test:\", X_test.shape)\nprint(\"y Train:\", y_train.shape)\nprint(\"y Test:\", y_test.shape)\n\nlm = LinearRegression()\nlm.fit(X_train,y_train)\n\npredictions = lm.predict(X_test)\npred = pd.DataFrame({'Actual': y_test, 'Predicted': predictions})\npred1 = pred.head(10)\npred1\n\nprint('Mean Absolute Error:', metrics.mean_absolute_error(y_test, predictions)) \nprint('Mean Squared Error:', metrics.mean_squared_error(y_test, predictions)) \nprint('Root Mean Squared Error:', np.sqrt(metrics.mean_squared_error(y_test, predictions)))\n\n\n","repo_name":"SmartPracticeschool/llSPS-INT-2034-Predicting-Life-Expectancy-using-Machine-Learning","sub_path":"Life Expectancy Prediction.ipynb","file_name":"Life Expectancy Prediction.ipynb","file_ext":"py","file_size_in_byte":5130,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"25"} +{"seq_id":"71325227905","text":"# + [markdown] id=\"rZYaNyD2FpiL\"\n# # Filtracja bilateralna\n\n# + [markdown] id=\"GgH3xBf_GZAi\"\n#\n\n# + [markdown] id=\"dLH690bzFpiS\"\n# ## Konwolucja obrazu z filtrem o zadanych współczynnikach\n#\n# Splot (konwolucję) obrazu wejściowego $I$ z filtrem $\\psi$ dla ustalonego punktu obrazu $\\mathbf{x}$ można przedstawić następująco:\n#\n# \\begin{equation}\n# \\hat{I}(\\mathbf{x}) = \\frac{1}{W_N}\\sum_{\\mathbf{p} \\in \\eta(\\mathbf{x})} \\psi(||\\mathbf{p}-\\mathbf{x}||)I(\\mathbf{p})\n# \\end{equation}\n#\n# gdzie:\n# - $\\hat{I}$ jest obrazem wynikowym (przefiltrowanym),\n# - $W_N = \\sum_y \\psi(y)$ jest parametrem normalizującym współczynniki filtra $\\psi$,\n# - $||\\cdot||$ jest odległością między punktami obrazu $\\mathbf{x}$ i $\\mathbf{p}$ według ustalonej metryki (np. norma $L_2$). Uwaga, proszę pamiętać, że zarówno $\\mathbf{x}$, jak i $\\mathbf{p}$ to współrzędne przestrzenne,\n# - $\\eta(\\mathbf{x})$ jest otoczeniem punktu $\\mathbf{x}$.\n#\n# Funkcja $\\psi$ decyduje o charakterze filtracji. Dla filtru Gaussowskiego:\n#\n# \\begin{equation}\n# \\psi(y) = G_{\\delta_s}(y)\n# \\end{equation}\n#\n# gdzie: $G_{\\delta_s}(y)$ jest funkcją Gaussa z parametrem skali $\\delta_s$.\n#\n# Opisaną powyżej filtrację realizowaliśmy w ramach ćwiczenia \"Przetwarzanie wstępne. Filtracja kontekstowa.\"\n\n# + [markdown] id=\"y-c-Phd8FpiU\"\n# ## Filtracja bilateralna\n#\n# Wadą klasycznego splotu jest brak adaptacji współczynników filtra do lokalnego otoczenia $\\eta(\\mathbf{x})$ filtrowanego punktu $\\mathbf{x}$.\n# Oznacza to wykorzystanie tych samych współczynników filtra $\\psi$ niezależnie od tego czy otoczenie jest względnie jednorodne lub zawiera krawędzie obiektów (w tym przypadku dochodzi do \"rozmywania\" krawędzi).\n# Filtracja bilateralna uwzględnia lokalne otoczenie filtrowanego punktu, w ten sposób, że parametry filtra zmieniają się w zależności od \"wyglądu\" otocznia.\n#\n#\n# Współczynniki filtra obliczane są na podstawie odległości filtrowanego punktu $\\mathbf{x}$ od każdego punktu otoczenia $\\mathbf{p}$ w dziedzinie przestrzennej obrazu (tak jak przy typowym filtrze np. Gaussa) oraz odległości punktów w przeciwdziedzinie obrazu (np. na podstawie różnicy w jasności pikseli dla obrazu w odcieniach szarości):\n#\n# \\begin{equation}\n# \\hat{I}(\\mathbf{x}) = \\frac{1}{W_N}\\sum_{\\mathbf{p} \\in \\eta(\\mathbf{x})} \\psi(||\\mathbf{p}-\\mathbf{x}||) \\gamma(|I(\\mathbf{p}) - I(\\mathbf{x})|) I(\\mathbf{p})\n# \\end{equation}\n# gdzie:\n# - $W_N$ jest współczynnikiem normalizującym filtr,\n# - $\\gamma$ jest funkcją odległości w przeciwdziedzinie obrazu, np. $\\gamma(y)=\\exp(-\\frac{y^2}{2\\delta_r^2})$\n# - parametr $\\delta_r$ jest utożsamiany z poziomem szumu w obrazie i należy go dobrać w sposób empiryczny.\n#\n# Proszę chwilę zastanowić się nad powyższym równaniem, w szczególności nad funkcją $\\gamma$. Proszę wyznaczyć, jaka będzie wartość funkcji dla pikseli podobnych (różnica 0, 1, 2), a skrajnie różnych (255, 200).\n#\n# ## Realizacja ćwiczenia\n#\n# ### Wczytanie danych\n#\n# 1. Wczytaj dane z pliku *MR_data.mat*. W tym celu wykorzystaj funkcję `loadmat` z pakietu scipy:\n# from scipy.io import loadmat\n# mat = loadmat('MR_data.mat')\n#\n# 2. Wczytany plik zawiera 5 obrazów: *I_noisefree*, *I_noisy1*, *I_noisy2*, *I_noisy3* oraz *I_noisy4*. Odczytać je można w następujący sposób:\n# Input = mat['I_noisy1']\n#\n# 3.Wyświetl wybrany obraz z pliku *MR_data.mat*. Zagadka - co to za obrazowanie medyczne?\n\n# + pycharm={\"name\": \"#%% Zadanie 1 - wy\\u015bwietlanie\\n\", \"is_executing\": true} id=\"hvi5AJiGFpiV\"\nimport cv2\nimport os\nimport requests\nfrom matplotlib import pyplot as plt\nimport numpy as np\nfrom scipy import signal\nfrom scipy.io import loadmat\nimport math\n\nurl = 'https://raw.githubusercontent.com/vision-agh/poc_sw/master/07_Bilateral/'\n\nfileNames = [\"MR_data.mat\"]\nfor fileName in fileNames:\n if not os.path.exists(fileName):\n r = requests.get(url + fileName, allow_redirects=True)\n open(fileName, 'wb').write(r.content)\n\nmat = loadmat('MR_data.mat')\n\n\n# + id=\"ld1hsqUa2RXP\"\ndef show_img(img, title='', cmap='gray'):\n plt.figure(figsize=(img.shape[0] / 100, img.shape[1] / 100), dpi=200)\n plt.imshow(img, cmap=cmap)\n plt.xticks([]), plt.yticks([])\n plt.title(title)\n plt.show()\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 453} id=\"CCQjmzpe2RXP\" outputId=\"893c7c56-e9ad-4dd6-fd9b-2d67c506312c\"\nshow_img(mat['I_noisy1'])\n\n\n# + [markdown] id=\"b2dsan_AFpiX\"\n# ### \"Klasyczna\" konwolucja\n#\n# 1. Zdefiniuj parametry filtra Gaussowskiego: rozmiar okna i wariancję $\\delta_S$.\n# 2. Oblicz współczynniki filtra na podstawie zdefiniowanych parametrów (najprościej w ramach podwójnej pętli for).\n# 2. Sprawdź ich poprawność i zwizualizuj filtr (tak jak w ćwiczeniu pt. \"Przetwarzanie wstępne. Filtracja kontekstowa.\").\n# 3. Wykonaj kopię obrazu wejściowego: `IConv = Input.copy()`\n# 4. Wykonaj podwójną pętlę po obrazie. Pomiń ramkę, dla której nie jest zdefiniowany kontekst o wybranej wielkości.\n# 5. W każdej iteracji stwórz dwuwymiarową tablicę zawierającą aktualny kontekst.\n# 6. Napisz funkcję, która będzie obliczała nową wartość piksela.\n# Argumentem tej funkcji są aktualnie przetwarzane okno i współczynniki filtra.\n# 7. Obliczoną wartość przypisz do odpowiedniego piksela kopii obrazu wejściowego.\n# 8. Wyświetl wynik filtracji.\n# 9. Porównaj wynik z obrazem oryginalnym.\n\n# + pycharm={\"is_executing\": true} id=\"YSByXW8d2RXQ\"\ndef fgaussian(size, sigma):\n m = n = size\n h, k = m//2, n//2\n x, y = np.mgrid[-h:h+1, -k:k+1]\n g = np.exp(-(x**2 + y**2)/(2*sigma**2))\n return g /g.sum() \n \n \ndef mesh(fun, size):\n fig = plt.figure()\n ax = fig.gca(projection='3d')\n \n\n X = np.arange(-size//2, size//2, 1)\n Y = np.arange(-size//2, size//2, 1)\n X, Y = np.meshgrid(X, Y)\n Z = fun\n \n ax.plot_surface(X, Y, Z)\n \n plt.show()\n\n# + id=\"4I6Td-515zyv\" outputId=\"59990ca7-903f-4ae8-ffdd-290d5ed01b48\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 479}\nmesh(fgaussian(5, 0.5), 5)\nmesh(fgaussian(5, 2), 5)\n\n\n# + pycharm={\"name\": \"#%% Zadanie 2 - konwolucja\\n\"} id=\"EL5qWflAFpiY\"\ndef classic(image, window_size=5, sigma_S=1.5):\n w, h = image.shape\n kernel = fgaussian(window_size, sigma_S)\n new_img = np.zeros((w, h))\n offset = window_size // 2\n\n for i in range(offset, w - offset):\n for j in range(offset, h - offset):\n window = image[i - offset : i + offset + 1, j - offset : j + offset + 1]\n new_img[i, j] = np.sum(window * kernel)\n \n return new_img\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 392} id=\"kQ0rPQvJ7kA3\" outputId=\"3038d9b3-9606-40a8-f5b4-480605da52b0\"\nmat_f = classic(mat['I_noisy1'])\nmat_diff = np.abs(mat_f.astype('int32') - mat['I_noisy1'].astype('int32'))\n\nfig, axs = plt.subplots(1, 3, figsize=(20, 20))\naxs[0].imshow(mat['I_noisy1'], 'gray', vmin=0, vmax=255)\naxs[0].set_title('Original')\naxs[1].imshow(mat_f, 'gray', vmin=0, vmax=255)\naxs[1].set_title('Processed')\naxs[2].imshow(mat_diff, 'gray', vmin=0, vmax=255)\naxs[2].set_title('Difference')\nplt.show()\n\n\n# + [markdown] id=\"0mp0PQrdFpiZ\"\n# ### Filtracja bilateralna\n#\n# 1. Zdefiniuj dodatkowy parametr: wariancję $\\delta_R$.\n# 3. Wykonaj kopię obrazu wejściowego: `IBilateral = Input.copy()`\n# 4. Wykonaj podwójną pętlę po obrazie. Pomiń ramkę, dla której nie jest zdefiniowany kontekst o wybranej wielkości.\n# 5. W każdej iteracji stwórz dwuwymiarową tablicę zawierającą aktualny kontekst.\n# 6. Napisz funkcję, która będzie obliczała nową wartość piksela.\n# Argumentami funkcji są aktualnie przetwarzane okno, współczynniki filtra gausowskiego (takie same jak wcześniej) i wariancja $\\delta_R$.\n# 7. Oblicz odległość w przeciwdziedzinie (dla wartości pikseli).\n# 8. Oblicz funkcję Gaussa dla obliczonych odległości z zadanym parametrem.\n# 9. Wykonaj normalizację obliczonych współczynników.\n# 10. Obliczoną wartość przypisz do odpowiedniego piksela kopii obrazu wejściowego.\n# 11. Wyświetl wynik filtracji.\n# 12. Porównaj wynik z obrazem oryginalnym.\n\n# + id=\"GUyUvRh2Fpia\"\ndef bilateral(image, window_size=5, sigma_S=1.5, sigma_R=16):\n w, h = image.shape\n kernel_g = fgaussian(window_size, sigma_S)\n new_img = np.zeros((w, h))\n offset = window_size // 2\n\n def get_kernel(window):\n kernel_b = np.zeros((window_size, window_size))\n center_value = window[offset, offset]\n\n for x in range(window_size):\n for y in range(window_size):\n kernel_b[x, y] = np.exp(-(window[x, y] - center_value)**2 / (2 * sigma_R**2))\n\n kernel = kernel_g * kernel_b\n kernel /= np.sum(kernel)\n\n return kernel\n\n \n for i in range(offset, w - offset):\n for j in range(offset, h - offset):\n window = image[i - offset : i + offset + 1, j - offset : j + offset + 1]\n kernel = get_kernel(window)\n new_img[i, j] = np.sum(window * kernel)\n \n return new_img\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 392} id=\"FBHlBD3F_eEd\" outputId=\"f8075184-aea1-4c3f-cbb0-dd7b2c645160\"\nmat_b = bilateral(mat['I_noisy1'])\nmat_b_diff = np.abs(mat_b.astype('int32') - mat['I_noisy1'].astype('int32'))\n\nfig, axs = plt.subplots(1, 3, figsize=(20, 20))\naxs[0].imshow(mat['I_noisy1'], 'gray', vmin=0, vmax=255)\naxs[0].set_title('Original')\naxs[1].imshow(mat_b, 'gray', vmin=0, vmax=255)\naxs[1].set_title('Processed')\naxs[2].imshow(mat_b_diff, 'gray', vmin=0, vmax=255)\naxs[2].set_title('Difference')\nplt.show()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 1000} id=\"FbZZHFGfAXK_\" outputId=\"92c9a65b-cc11-4e99-adb0-119853d8d4d4\"\nmat_1 = classic(mat['I_noisy1'])\nmat_b_1 = bilateral(mat['I_noisy1'])\nmat_2 = classic(mat['I_noisy2'])\nmat_b_2 = bilateral(mat['I_noisy2'])\nmat_3 = classic(mat['I_noisy3'])\nmat_b_3 = bilateral(mat['I_noisy3'])\nmat_4 = classic(mat['I_noisy4'])\nmat_b_4 = bilateral(mat['I_noisy4'])\n\nfig, axs = plt.subplots(1, 3, figsize=(20, 20))\naxs[0].imshow(mat['I_noisy1'], 'gray', vmin=0, vmax=255)\naxs[0].set_title('Original')\naxs[1].imshow(mat_1, 'gray', vmin=0, vmax=255)\naxs[1].set_title('Classic')\naxs[2].imshow(mat_b_1, 'gray', vmin=0, vmax=255)\naxs[2].set_title('Bilateral')\nplt.show()\nfig, axs = plt.subplots(1, 3, figsize=(20, 20))\naxs[0].imshow(mat['I_noisy2'], 'gray', vmin=0, vmax=255)\naxs[0].set_title('Original')\naxs[1].imshow(mat_2, 'gray', vmin=0, vmax=255)\naxs[1].set_title('Classic')\naxs[2].imshow(mat_b_2, 'gray', vmin=0, vmax=255)\naxs[2].set_title('Bilateral')\nplt.show()\nfig, axs = plt.subplots(1, 3, figsize=(20, 20))\naxs[0].imshow(mat['I_noisy3'], 'gray', vmin=0, vmax=255)\naxs[0].set_title('Original')\naxs[1].imshow(mat_3, 'gray', vmin=0, vmax=255)\naxs[1].set_title('Classic')\naxs[2].imshow(mat_b_3, 'gray', vmin=0, vmax=255)\naxs[2].set_title('Bilateral')\nplt.show()\nfig, axs = plt.subplots(1, 3, figsize=(20, 20))\naxs[0].imshow(mat['I_noisy4'], 'gray', vmin=0, vmax=255)\naxs[0].set_title('Original')\naxs[1].imshow(mat_4, 'gray', vmin=0, vmax=255)\naxs[1].set_title('Classic')\naxs[2].imshow(mat_b_4, 'gray', vmin=0, vmax=255)\naxs[2].set_title('Bilateral')\nplt.show()\n","repo_name":"bchwast/AGH-WdCPO","sub_path":"Cwiczenia 7/07_bilateral.ipynb","file_name":"07_bilateral.ipynb","file_ext":"py","file_size_in_byte":11234,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"25"} +{"seq_id":"34269831123","text":"# !pip install -q numpy pandas tqdm pymystem3 tensorflow torch transformers qdrant-client ranx\n\n# + _uuid=\"8f2839f25d086af736a60e9eeb907d3b93b6e0e5\" _cell_guid=\"b1076dfc-b9ad-4769-8c92-a6c4dae69d19\"\nimport shutil\n\nimport numpy as np\nimport pandas as pd\n\nimport torch\nfrom torch import nn, optim\n\nfrom transformers import AutoTokenizer, AutoModel\nfrom transformers import logging\nlogging.set_verbosity_error()\n\nfrom functools import partial\n\nfrom qdrant_client import QdrantClient\nfrom qdrant_client.http.models import Distance, VectorParams, PointStruct\nfrom qdrant_client.http.models import CollectionStatus\n\nfrom sklearn.model_selection import GroupKFold\nfrom sklearn.metrics import roc_auc_score\n\nimport nltk\nnltk.download(\"stopwords\")\nfrom nltk.corpus import stopwords\nfrom pymystem3 import Mystem\nfrom string import punctuation\n\nfrom ranx import Qrels, Run, evaluate, compare\n\nfrom tqdm import tqdm\nfrom copy import deepcopy\n\ndevice = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\nprint(device)\n\nDIR = '/kaggle/input/aaa-project-search/'\n\n# +\ndf = pd.read_hdf(DIR + 'search_relevance_dataset_v1.hdf', 'table')\ndf.drop(columns=['query_category_id', 'query_microcat_id', 'query_location_id'], inplace=True)\n\ndf.query_id = df.query_id.astype(str)\ndf.item_id = df.item_id.astype(str)\n\ndf.head(3)\n\n# +\n# Create lemmatizer and stopwords list\nmystem = Mystem() \nrussian_stopwords = stopwords.words('russian')\n\n# Preprocess function\ndef preprocess_text(text):\n text = ' '.join(text.lower().split())\n\n# tokens = mystem.lemmatize(text)\n# tokens = [token for token in tokens if token not in russian_stopwords\\\n# and token != ' ' and token.strip() not in punctuation]\n\n# text = ' '.join(tokens)\n\n return text\n\n\n# +\ndf.query_text = df.query_text.apply(preprocess_text)\ndf.title = df.title.apply(preprocess_text)\n\ndf.head(3)\n# -\n\nclient = QdrantClient(':memory:')\n\n\ndef index_dataset(client, df, model, vector_size, collection_name='collection'):\n client.recreate_collection(\n collection_name=collection_name, vectors_config=VectorParams(size=vector_size, distance=Distance.COSINE),\n )\n df = df.drop_duplicates(subset=['item_id'])\n\n points = []\n for row in tqdm(df.itertuples(), total=len(df)):\n points.append(\n PointStruct(\n id=row.Index,\n vector=list(map(float, model(row.title))), # list(map(float.. to make proper type\n payload={\n 'title': row.title, 'description': row.description, 'keywords': row.keywords, 'item_id': row.item_id\n },\n )\n )\n\n operation_info = client.upsert(collection_name=collection_name, wait=True, points=points)\n\n return operation_info\n\n\n# +\n# random model\nrandom_model = lambda text: np.random.randn(32)\n\n# baseline model 1\ntokenizer = AutoTokenizer.from_pretrained('cointegrated/rubert-tiny2')\nmodel = AutoModel.from_pretrained('cointegrated/rubert-tiny2').to(device)\n\ndef embed_bert_cls(text, model, tokenizer):\n t = tokenizer(text, padding=True, truncation=True, return_tensors='pt')\n with torch.no_grad():\n model_output = model(**{k: v.to(model.device) for k, v in t.items()})\n embeddings = model_output.last_hidden_state[:, 0, :]\n embeddings = torch.nn.functional.normalize(embeddings)\n return embeddings[0].cpu().numpy()\n\nbaseline_model_1 = partial(embed_bert_cls, model=model, tokenizer=tokenizer)\n\n# baseline model 2\ntokenizer = AutoTokenizer.from_pretrained('cointegrated/LaBSE-en-ru')\nmodel = AutoModel.from_pretrained('cointegrated/LaBSE-en-ru').to(device)\n\ndef embed_labse_cls(text, model, tokenizer):\n t = tokenizer(text, padding=True, truncation=True, return_tensors='pt')\n with torch.no_grad():\n model_output = model(**{k: v.to(model.device) for k, v in t.items()})\n embeddings = model_output.pooler_output\n embeddings = torch.nn.functional.normalize(embeddings)\n return embeddings[0].cpu().numpy()\n\nbaseline_model_2 = partial(embed_labse_cls, model=model, tokenizer=tokenizer)\n# -\n\nbaseline_model_1('hello').shape, baseline_model_2('hello').shape # ((312,), (768,))\n\n\n# +\nclass ProjectorModel(nn.Module):\n def __init__(self, model_name: str = 'cointegrated/rubert-tiny2', final_emb_size: int = 32):\n super().__init__()\n\n self.model_name = model_name\n self.final_emb_size = final_emb_size\n \n self.tokenizer = AutoTokenizer.from_pretrained(self.model_name)\n self.backbone = AutoModel.from_pretrained(self.model_name, output_hidden_states=True).to(device)\n\n for n, p in self.backbone.named_parameters():\n p.requires_grad = False\n\n self.initial_emd_size = 312 if self.model_name == 'cointegrated/rubert-tiny2' else 768\n\n self.projection_head = nn.Sequential(\n nn.Linear(self.initial_emd_size, self.final_emb_size, device=device), \n )\n\n def backbone_forward(self, text):\n t = self.tokenizer(text, padding=True, truncation=True, return_tensors='pt')\n model_output = self.backbone(**{k: v.to(self.backbone.device) for k, v in t.items()})\n\n# embeddings = model_output.pooler_output # torch.concat([model_output['hidden_states'][-i].mean(dim=1) for i in range(1, 5, 1)], dim=1)\n\n embeddings = model_output.last_hidden_state[:, 0, :] if self.model_name == 'cointegrated/rubert-tiny2' else model_output.pooler_output\n embeddings = nn.functional.normalize(embeddings)\n\n return embeddings\n\n def forward(self, text):\n embeddings = self.backbone_forward(text)\n\n compressed_embeddings = self.projection_head(embeddings)\n compressed_embeddings = nn.functional.normalize(compressed_embeddings)\n\n return compressed_embeddings\n\nProjectorModel()('some text here').shape, ProjectorModel()(['some text here', 'lalala']).shape\n\n\n# -\n\ndef train_eval(model, df_train, df_test, batch_size=64, n_epochs=5, lr=1e-5):\n model.train()\n\n queries = df_train.query_id.unique()\n df_train = df_train.set_index('query_id')\n\n optimizer = optim.AdamW(model.parameters(), lr=lr, weight_decay=1e-3)\n\n for e in range(n_epochs):\n train_set = df_train.loc[np.random.choice(queries, size=len(queries), replace=False), ['query_text', 'title', 'target', 'query_len', 'keywords']].values\n num_batches = len(train_set) // batch_size\n\n for i in tqdm(range(num_batches)):\n start, end = i * batch_size, (i + 1) * batch_size\n batch = train_set[start:end]\n\n x1, x2, y = list(batch[:, 0]), list(batch[:, 1]), torch.tensor(batch[:, 2].astype(int), device=device)\n\n loss = 0.5 * ((y - (model.backbone_forward(x1) * model.backbone_forward(x2)).sum(dim=1))**2).mean() +\\\n 0.5 * ((y - (model(x1) * model(x2)).sum(dim=1))**2).mean()\n loss.backward()\n\n torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)\n\n optimizer.step()\n optimizer.zero_grad()\n\n if e == 0:\n for n, p in model.named_parameters():\n if n[:5] != 'embed':\n p.requires_grad = True\n\n optimizer = optim.AdamW(model.parameters(), lr=lr, weight_decay=1e-2)\n\n model.eval()\n\n test_set = df_test.loc[:, ['query_text', 'title', 'target', 'query_len', 'keywords']].values\n num_batches = len(test_set) // batch_size\n\n pred1, pred2, true = [], [], []\n for i in tqdm(range(num_batches + 1)):\n start, end = i * batch_size, (i + 1) * batch_size\n batch = test_set[start:end]\n\n x1, x2, y = list(batch[:, 0]), list(batch[:, 1]), batch[:, 2].astype(int)\n\n pred1.extend((model.backbone_forward(x1) * model.backbone_forward(x2)).sum(dim=1).abs().cpu().detach().numpy())\n pred2.extend((model(x1) * model(x2)).sum(dim=1).abs().cpu().detach().numpy())\n true.extend(y)\n\n print(f'Epoch {e}:')\n print(f'Test ROC-AUC backbone: {roc_auc_score(true, pred1):.3f}')\n print(f'Test ROC-AUC full net: {roc_auc_score(true, pred2):.3f}')\n\n df_test['true'] = true\n df_test['pred1'] = pred1\n df_test['pred2'] = pred2\n\n print('Test ROC-AUC by query length:')\n display(df_test.groupby('query_len').apply(\n lambda d: [f'{roc_auc_score(d.true, d.pred1):.3f}', f'{roc_auc_score(d.true, d.pred2):.3f}']\n ))\n\n model.train()\n\n\ndf['query_len'] = df['query_text'].apply(lambda x: len(x.split(' ')))\ndf.loc[df.query_len > 3, 'query_len'] = 3\ndf.query_len.value_counts()\n\ndf.title = 'объявление: ' + df.title\ndf.query_text = 'запрос: ' + df.query_text\ndf.head()\n\n# +\n# %%time\n\nkf = GroupKFold(n_splits=2)\n\nfor train_indices, test_indices in kf.split(X=df, groups=df.query_id): \n df_train, df_test = df.loc[train_indices], df.loc[test_indices]\n print('-' * 80)\n print('Train:', df_train.shape, df_train.query_id.nunique(), ' ',\n 'Test:', df_test.shape, df_test.query_id.nunique(), ' ',\n 'Intersection:', set(df_train.query_id).intersection(set(df_test.query_id)))\n print()\n\n runs = []\n for model_name in ['cointegrated/rubert-tiny2']: # ['cointegrated/rubert-tiny2', 'cointegrated/LaBSE-en-ru']:\n for final_emb_size in [64]:\n print('Processing...', model_name, final_emb_size)\n\n model = ProjectorModel(model_name=model_name, final_emb_size=final_emb_size)\n train_eval(model, df_train, df_test, batch_size=512, n_epochs=1+15, lr=1e-5)\n\n model.eval()\n\n final_model = lambda text: model(text).cpu().detach().numpy()[0]\n _ = index_dataset(client, df, final_model, vector_size=final_emb_size,\n collection_name=f'train_collection_{model_name}_{final_emb_size}')\n\n qrels = Qrels.from_df(df_test, q_id_col='query_id', doc_id_col='item_id', score_col='target')\n test_examples = df_test.drop_duplicates(subset=['query_id', 'query_text']).loc[:, ['query_id', 'query_text']]\n\n run_dict = {}\n for row in tqdm(test_examples.itertuples(), total=len(test_examples)):\n search_result = client.search(\n collection_name=f'train_collection_{model_name}_{final_emb_size}', \n query_vector=list(map(float, final_model(row.query_text))), limit=50\n )\n run_dict[row.query_id] = {i.payload['item_id']: i.score for i in search_result}\n\n run = Run(run_dict) # print(evaluate(qrels, run, ['map@10', 'map@50', 'ndcg@10', 'ndcg@50']))\n runs.append(run)\n\n client.delete_collection(collection_name=f'train_collection_{model_name}_{final_emb_size}')\n print('Done')\n\n report = compare(\n qrels=qrels, runs=runs,\n metrics=['map@10', 'map@50', 'ndcg@10', 'ndcg@50'],\n n_permutations=1000, stat_test='student', max_p=0.01,\n )\n print(); print(report); print()\n\n break\n\n# 0.752 - base\n# 0.788-0.789 8-9 epochs - new loss\n# 0.790 8-9 epochs - normalize both\n\n# 0.789 (0.803 backbone) 9-11 epochs - 1/1 loss\n# 0.791-0.792 (0.804-0.805 backbone) 10-11 epochs - 0.5 / 0.5 loss (batch 256 as I remember)\n\n# 0.805 (0.806 backbone) - 10 epochs - lowercase preprocessing\n# 0.805 (0.813 backbone) - 15 epochs - special tokens prior\n\n# +\nmodel.backbone.save_pretrained('model_tuned/')\nmodel.tokenizer.save_pretrained('model_tuned/')\n\ntorch.save(model, 'model_tuned/model_tuned_full.pkl')\n\nshutil.make_archive('model_tuned', 'zip', 'model_tuned/')\n# -\n\nmodel = torch.load('model_tuned/model_tuned_full.pkl', map_location=device)\nmodel.eval()\n\n\n","repo_name":"NBar05/aaa-project-search","sub_path":"notebooks/5-validation-fine-tuning.ipynb","file_name":"5-validation-fine-tuning.ipynb","file_ext":"py","file_size_in_byte":11647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"25"} +{"seq_id":"37756471834","text":"# +\nimport IPython\nimport cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom scipy import fftpack\nfrom scipy.ndimage import convolve\nfrom scipy.fftpack import dct, dctn, idctn\nfrom scipy.linalg import circulant\nimport pywt\nfrom sklearn import linear_model\nfrom IPython.display import clear_output, display\nimport seaborn as sns\nimport matplotlib as mpl\nmpl.rc('image', cmap='Blues')\n\nimport cvxpy as cp\nimport pandas as pd\n# -\n\n# Let's load the [Shepp-Logan phantom](https://en.wikipedia.org/wiki/Shepp–Logan_phantom) and resize it to be $ 128 \\times 128 $.\n\nwidth = 128\nimg = cv2.imread('./SheppLogan_Phantom.png',0, )\nimg = cv2.resize(img, dsize=(width,width))\nN = np.prod(img.shape) # The dimension after flattening\n\n\n# Here's a function that tells us the sparsity of an image, i.e. the proportion of non-zero pixels it has:\n\ndef sparsity(img):\n return (np.sum(np.abs(img) > 1e-9) / np.prod(img.shape))\n\n\n# And the next function tells us the progress in a for loop while we're waiting:\n\ndef print_progress(n, i):\n \n if i % np.max([(n // 100), 1]) == 0:\n clear_output(wait=True)\n print((i + 1) * 100 // n, \"% done\")\n\n\n# Since the image in the original basis is not sparse, we look at its Laplacian which is sparse. We also normalize the coefficients to be 0 or 1:\n\nthresh = 0 # A threshold to zero coefficients\nlap = cv2.Laplacian(img,cv2.CV_64F,ksize=1)\nlap_th = np.copy(lap)\nlap_th[lap_th < thresh] = 0\nlap_th[lap_th != 0] = 1\nplt.imshow(lap_th)\nprint(\"Sparsity: \", sparsity(lap_th))\n\nN = np.prod(img.shape) # Size of experimental domain\np = N # Covariate Dimension\nn = p // 2 #Sample size; we undersample by 50%\nprint('shape: ', img.shape)\nprint('dim: ', p)\nprint('sparsity of the original image: ', sparsity(img))\nprint('sparsity of the Laplacian: ', sparsity(lap_th))\n\n# We will be (under-)sampling the [Discrete Cosine Transform](https://en.wikipedia.org/wiki/Discrete_cosine_transform) of the image, so let's look at this transform and its inverse:\n\nC = dctn(img, norm='ortho')\n# Cshift = np.log(np.abs(np.fft.fftshift(C)))\ninvC = idctn(C, norm='ortho')\nplt.figure(figsize=(20,20))\nplt.subplot(131),plt.imshow(img)\nplt.title('Input Image')\nplt.subplot(132),plt.imshow(np.log(np.abs(C)))\nplt.title('DCT')\nplt.subplot(133), plt.imshow(invC)\nplt.title('iDCT')\nplt.show()\n\n# The matrix of the 2d DCT transform in the vectorized basis can be obtained using Kronecker products:\n\nd = dct(np.eye(img.shape[0]), norm='ortho')\nD = np.kron(d,d).T\n\n# We take the experimental domain to be this matrix $D$ scaled by $\\sqrt{N}$:\n\nX = np.sqrt(N) * D.copy()\n\n# Let's say we are interested in the average intensity of the image within the gray rectangular area:\n\nc_arr = np.zeros(img.shape)\nc_arr[95:110, 50:75] = 1\nplt.figure(figsize=(20,20))\nplt.subplot(121)\nplt.imshow(lap_th, vmin=0, cmap='gray')\nplt.axis('off')\nplt.subplot(122)\nplt.imshow(np.minimum(lap_th + 0.2*c_arr, 1), vmin=0, cmap='gray')\nplt.axis('off')\nplt.savefig('shepp_lap_filter.png', format=\"png\", cmap='gray', vmin=0, dpi=700, bbox_inches='tight')\n\n# The true coefficient $\\beta$ is taken to be the vectorized Laplacian. $c$ is the indicator function of the rectangular area above.\n\nbeta = lap_th.reshape(N)\nc = c_arr.reshape(N)\nc = c / np.sum(np.abs(c))\ngamma = beta.T @ c\n\n# Given this value of $c$ and $X$, we need to solve the following linear program:\n# $$\n# \\begin{align*}\n# \\text{P1: minimize}_{w \\geq 0} &\\quad c^T \\Sigma^{-1} c \\\\\n# \\text{s.t. }\\quad &\\Sigma = \\sum_{i=1}^N w_i x_i x_i^T\\\\\n# &\\sum_{i=1}^N w_i = 1\n# \\end{align*}\n# $$\n\n# Fortunately, this can be written as a linear program:\n# $$\n# \\begin{align*}\n# \\text{P2: minimize}_{a,b} &\\quad \\sum_i a_i \\\\\n# \\text{s.t. }\\quad &c = \\sum_{i=1}^N b_i x_i^T\\\\\n# &a \\geq b\\\\\n# &a \\geq -b\n# \\end{align*}\n# $$\n\n# Given an optimal solution $(a^\\star, b^\\star)$ of $P2$, a solution of $P1$ is found by $w^\\star = |a| / \\| a\\|_1$. The following code solve $P2$ using the cvxpy package. Since it takes a long time to solve this program, I have saved the solution to a file called `w_opt.csv` which I just read it next.\n\nw = cp.Variable((N), nonneg = True)\nz = cp.Variable((N))\nconstraints = [X.T @ z == c, z - w <= 0, -z - w <= 0]\nobj = cp.Minimize(cp.sum(w))\nprob = cp.Problem(obj, constraints)\n\nprob.solve(verbose = True, abstol = 1e-5)\n\nw_opt = w.value / np.sum(w.value)\n\n\ndef c_optimize(X,c):\n N = X.shape[0]\n w = cp.Variable((N), nonneg = True)\n z = cp.Variable((N))\n constraints = [X.T @ z == c, z - w <= 0, -z - w <= 0]\n obj = cp.Minimize(cp.sum(w))\n prob = cp.Problem(obj, constraints)\n prob.solve(verbose = True, abstol = 1e-5)\n return(w.value / np.sum(w.value))\n \n\n\n# +\n#np.savetxt(\"w_opt.csv\", w_opt, delimiter=\",\")\n# -\n\n# ## Read optimal weights\n\nw_opt = np.loadtxt(\"w_opt.csv\", delimiter=\",\")\n\n# Let's take a look at the distirbution of the weights, or rather, their $\\log$:\n\nplt.hist(np.log(w_opt[w_opt > 0]))\nplt.show()\n\n# As seen below, the optimal design improves the asymptotic standard error of the de-biased lasso estimator by a factor of $\\approx 5$:\n\nsigma_opt = np.sqrt(c.T @ np.linalg.solve( X.T @ np.diag(w_opt) @ X, c))\n\nsigma_unif = np.sqrt(c.T @ np.linalg.solve( X.T @ X / N, c))\n\n(sigma_unif / sigma_opt)\n\nfrom sklearn.linear_model import Lasso, LassoCV\nfrom random import sample\n\n\n# The next function computes the de-biased lasso estimator:\n\ndef deb_lasso(x, y, c, u, lasso_tuning, beta_init):\n n = len(y)\n clf = Lasso(alpha=lasso_tuning, fit_intercept=False,\n warm_start=True, max_iter = 999999, copy_X = True,\n normalize = False)\n norms = np.sqrt(np.mean(x**2, axis = 0))\n clf.coef_ = beta_init #Initialize at truth for faster computation\n clf.fit(x / norms, y)\n beta_hat = clf.coef_ / norms\n gamma_hat = c.T @ beta_hat + u.T @ x.T @ (y - x @ beta_hat) / n\n return [gamma_hat, beta_hat]\n\n\nsignal = X @ beta\n\n# We can use cross-validation to find a good value of the tuning paramter for the lasso estimator:\n\n# +\nn = N // 2\nlambda_theory = np.sqrt(np.log(N)/ n)\nindices = np.random.choice(range(N), size=n)\n\ny = signal[indices] + np.random.normal(size=n)\n\nlasso_fit = LassoCV(cv = 10, fit_intercept=False, \n alphas=(np.exp(np.arange(-3, 0, 1e-1)))*lambda_theory,\n n_jobs = -1, max_iter = 999999, verbose=True).fit(X[indices,:],y)\n\nplt.plot(lasso_fit.alphas_, np.mean(lasso_fit.mse_path_, axis = 1))\nplt.show()\n# -\n\nbeta_hat = lasso_fit.coef_\nprint(gamma)\nprint(\"Error: \", np.sum(np.abs(beta - beta_hat)))\nprint(np.sum(beta))\nprint(lambda_theory, lasso_fit.alpha_)\ncv_lambda = lasso_fit.alpha_\n\n# # Uniform Sampling\n\nn = N // 2\nlambda_theory = np.sqrt(np.log(N)/ n)\nu_unif = c\ngamma = c.T @ beta\nsignal = X @ beta\n\ngamma\n\n# +\nn = N // 2\nn_reps = 5\ngammas_unif = np.zeros(n_reps)\nsignal = X @ beta\nbeta_hat = np.zeros(N)\n\nfor i in range(n_reps):\n indices = np.random.choice(range(N), size=n)\n y = signal[indices] + np.random.normal(size=n) \n gammas_unif[i], beta_hat = deb_lasso(X[indices,:], y, c, u_unif, lambda_theory, beta_hat.copy())\n \n print_progress(n_reps, i)\n# print(gammas_unif[i] - gamma)\n# -\n\nnp.savetxt(fname = 'unif_dist.csv', X = gammas_unif, delimiter = ',')\n\ngammas_unif = np.loadtxt(\"unif_dist.csv\", delimiter=\",\")\n\nsns.histplot(gammas_unif - gamma)\nplt.show()\nprint(\"bias: \", np.mean(gammas_unif) - gamma)\nprint(\"std: \", np.std(gammas_unif))\nprint((np.linalg.norm(c) / np.sqrt(n)))\n\n# +\n# np.savetxt(\"unif_dist.csv\", gammas_unif, delimiter=\",\")\n# -\n\n\n\n# # Optimal Sampling\n\n# Next we compute $u = \\Sigma^{-1} c$ for optimal design:\n\nu_opt = np.linalg.solve(X.T @ np.diag(w_opt) @ X, c)\n\nn_reps = 5\ngammas_opt = np.zeros(n_reps)\nbeta_hat = np.zeros(N)\nfor i in range(n_reps):\n indices = np.random.choice(range(N), size=n, p=w_opt)\n y = signal[indices] + np.random.normal(size=n)\n\n gammas_opt[i], beta_hat = deb_lasso(X[indices,:], y, c, u_opt, lambda_theory, beta_hat.copy())\n \n print_progress(n_reps, i)\n print(gammas_opt[i] - gamma)\n\n# +\n# np.savetxt(\"opt_dist.csv\", gammas_opt, delimiter=\",\")\n# -\n\ngammas_opt = np.loadtxt(\"opt_dist.csv\", delimiter=\",\")\n\nsns.histplot(np.sqrt(n)*(gammas_opt - gamma))\nplt.show()\nprint(\"bias: \", np.mean(gammas_opt - gamma))\nprint(\"std: \", (np.std(np.sqrt(n)*(gammas_opt - gamma))))\n\nsns.histplot(np.sqrt(n)*(gammas_unif - gamma))\nplt.show()\nprint(\"bias: \", np.mean(gammas_unif - gamma))\nprint(\"std: \", (np.std(np.sqrt(n)*(gammas_unif - gamma))))\n\n# To see the improvements let's look at the estimation errors under optimal and uniform designs in one plot:\n\nestim_errors = pd.DataFrame({\"Optimal\": gammas_opt, \n \"Uniform\": gammas_unif})\n\nsns.histplot(estim_errors - gamma)\nplt.title(\"Errors under Optimal and Uniform Designs\")\nplt.xlabel(\"Estimation Errors\")\nplt.show()\n\n# As you can see in the plot, the estimation errors under the optimal design are much more concentrated around zero than when using a uniform design. \n\n# # More simulations\n\n# The rest of the code provides more simulations with Gaussian designs along with power and error rate calculations.\n\nimport numpy as np\nfrom scipy.linalg import toeplitz\nfrom sklearn.linear_model import Lasso, LassoCV\nfrom random import sample\nimport cvxpy as cp\nfrom scipy.stats import norm\n\n# +\n\nN = 1000\np = 500\nn = 200\nss = [5, 10]\nmc_samples = 500\n\n\n\nkappas = [0.1, 0.9]\n# Sigma = toeplitz(kappa ** np.arange(p)).T\n# u_unif = np.linalg.solve(Sigma, c)\n\n\nlambda_theory = np.sqrt(np.log(p) / n)\n# -\n\n# # Uniform Sampling\n\n# +\nnp.random.seed(1)\n\nbeta_hat = np.zeros(p)\ngamma_hats_unif = np.zeros([2, len(kappas), len(ss), mc_samples])\nvars_unif = np.zeros([2, len(kappas), len(ss), mc_samples])\ngammas = np.zeros([2, len(kappas), len(ss)])\n \nfor k in range(len(kappas)):\n Sigma = toeplitz(kappas[k] ** np.arange(p)).T\n X = np.random.multivariate_normal(mean=np.zeros(p), cov=Sigma, size=N)\n for l in [0,1]:\n for j in range(len(ss)):\n beta = np.concatenate((np.arange(ss[j],0, -1), np.zeros(p - ss[j])), axis = 0) / ss[j]\n c = np.zeros(p)\n c[ss[j] + l - 1] = 1\n\n u_unif = np.linalg.solve(X.T @ X / N, c)\n\n signal = X @ beta\n gammas[l, k,j] = c.T @ beta\n \n for i in range(mc_samples):\n indices = np.random.choice(range(N), size=n)\n y = signal[indices] + np.random.normal(size=n)\n gamma_hats_unif[l, k, j, i], beta_hat = deb_lasso(X[indices,:], y, c, u_unif, lambda_theory, beta_hat.copy())\n vars_unif[l, k, j, i] = u_unif.T @ X[indices,:].T @ X[indices,:] @ u_unif / (n**2)\n print_progress(mc_samples, i)\n# -\n\nnp.mean(gamma_hats_unif, axis = 3) - gammas\n\nnp.std(gamma_hats_unif, axis = 3)\n\nnp.mean(np.sqrt(vars_unif), axis = 3)\n\n# # c-Optimal Sampling\n\n# +\nnp.random.seed(1)\n\nbeta_hat = np.zeros(p)\ngamma_hats_opt = np.zeros([2, len(kappas), len(ss), mc_samples])\nvars_opt = np.zeros([2, len(kappas), len(ss), mc_samples])\ngammas = np.zeros([2, len(kappas), len(ss)])\n \nfor k in range(len(kappas)):\n Sigma_init = toeplitz(kappas[k] ** np.arange(p)).T\n X = np.random.multivariate_normal(mean=np.zeros(p), cov=Sigma_init, size=N)\n for l in [0,1]:\n for j in range(len(ss)):\n beta = np.concatenate((np.arange(ss[j],0, -1), np.zeros(p - ss[j])), axis = 0) / ss[j]\n c = np.zeros(p)\n c[ss[j] + l - 1] = 1\n\n signal = X @ beta\n gammas[l, k,j] = c.T @ beta\n w_opt = c_optimize(X, c)\n u_opt = np.linalg.solve(X.T @ np.diag(w_opt) @ X, c)\n\n for i in range(mc_samples):\n indices = np.random.choice(range(N), size=n, p = w_opt)\n y = signal[indices] + np.random.normal(size=n)\n gamma_hats_opt[l, k, j, i], beta_hat = deb_lasso(X[indices,:], y, c, u_opt, lambda_theory, beta_hat.copy())\n vars_opt[l, k, j, i] = u_opt.T @ X[indices,:].T @ X[indices,:] @ u_opt / (n**2)\n print_progress(mc_samples, i)\n# -\n\nnp.mean(gamma_hats_opt, axis = 3) - gammas\n\nnp.std(gamma_hats_opt, axis = 3) / np.std(gamma_hats_unif, axis = 3)\n\nnp.std(gamma_hats_opt, axis = 3)\n\nnp.mean(np.sqrt(vars_opt), axis = 3)\n\nnp.sum((gamma_hats_opt +\n np.sqrt(vars_opt) *\n norm().interval(0.95)[0]) > 0, axis = 3) / mc_samples +\\\n np.sum((gamma_hats_opt[:,:,:,:] +\n np.sqrt(vars_opt)[:,:,:,:] *\n norm().interval(0.95)[1]) < 0, axis = 3) / mc_samples\n\nnp.sum((gamma_hats_unif +\n np.sqrt(vars_unif) *\n norm().interval(0.95)[0]) > 0, axis = 3) / mc_samples +\\\n np.sum((gamma_hats_unif[:,:,:,:] +\n np.sqrt(vars_unif)[:,:,:,:] *\n norm().interval(0.95)[1]) < 0, axis = 3) / mc_samples\n\ngammas_array = np.array([gammas.T] * mc_samples).T\n\nnp.sum(((gamma_hats_opt +\n np.sqrt(vars_opt) *\n norm().interval(0.95)[0]) <= gammas_array) *\\\n ((gamma_hats_opt +\n np.sqrt(vars_opt) *\n norm().interval(0.95)[1]) >= gammas_array),axis = 3) / mc_samples \n\nnp.sum(((gamma_hats_unif +\n np.sqrt(vars_unif) *\n norm().interval(0.95)[0]) <= gammas_array) *\\\n ((gamma_hats_unif +\n np.sqrt(vars_unif) *\n norm().interval(0.95)[1]) >= gammas_array),axis = 3) / mc_samples \n\nnp.sqrt(n) * np.std(gamma_hats_opt, axis = 3)\n\nnp.sqrt(n) * np.std(gamma_hats_unif, axis = 3)\n\n# # n-Nearest-Neighbor Sampling\n\n# +\nnp.random.seed(1)\n\nbeta_hat = np.zeros(p)\ngamma_hats_nn = np.zeros([2, len(kappas), len(ss), mc_samples])\nvars_nn = np.zeros([2, len(kappas), len(ss), mc_samples])\ngammas = np.zeros([2, len(kappas), len(ss)])\n \nfor k in range(len(kappas)):\n Sigma_init = toeplitz(kappas[k] ** np.arange(p)).T\n X = np.random.multivariate_normal(mean=np.zeros(p), cov=Sigma_init, size=N)\n for l in [0,1]:\n for j in range(len(ss)):\n beta = np.concatenate((np.arange(ss[j],0, -1), np.zeros(p - ss[j])), axis = 0) / ss[j]\n c = np.zeros(p)\n c[ss[j] + l - 1] = 1\n distances = np.sum((X - c) ** 2, axis = 1)\n indices = np.argsort(distances)[:n]\n signal = X @ beta\n gammas[l, k, j] = c.T @ beta\n \n # u_opt = np.linalg.solve(X[indices,:].T @ X[indices,:] / n, c)\n u_opt = np.linalg.lstsq(X[indices, :].T @ X[indices,:] / n, c, rcond = None)[0]\n\n for i in range(mc_samples):\n \n y = signal[indices] + np.random.normal(size=n)\n gamma_hats_nn[l, k, j, i], beta_hat = deb_lasso(X[indices,:], y, c, u_opt, lambda_theory, beta_hat.copy())\n vars_nn[l, k, j, i] = u_opt.T @ X[indices,:].T @ X[indices,:] @ u_opt / (n**2)\n print_progress(mc_samples, i)\n# -\n\nprint((np.mean(gamma_hats_nn, axis = 3) - gammas))\nprint((np.mean(gamma_hats_opt, axis = 3) - gammas))\n\n\n# # Standard Errors\n\nnp.sqrt(n) * np.std(gamma_hats_nn, axis = 3) \n\n# # Power & FPR\n\nnp.sum((gamma_hats_nn +\n np.sqrt(vars_nn) *\n norm().interval(0.95)[0]) > 0, axis = 3) / mc_samples +\\\n np.sum((gamma_hats_nn[:,:,:,:] +\n np.sqrt(vars_nn)[:,:,:,:] *\n norm().interval(0.95)[1]) < 0, axis = 3) / mc_samples\n\n# # Coverage\n\nnp.mean( ((gamma_hats_nn +\n np.sqrt(vars_nn) *\n norm().interval(0.95)[0]) <= 0 ) * \n ((gamma_hats_nn[:,:,:,:] +\n np.sqrt(vars_nn)[:,:,:,:] *\n norm().interval(0.95)[1]) >= 0), axis = 3)\n\nnp.mean( ((gamma_hats_opt +\n np.sqrt(vars_opt) *\n norm().interval(0.95)[0]) <= 0 ) * \n ((gamma_hats_opt[:,:,:,:] +\n np.sqrt(vars_opt)[:,:,:,:] *\n norm().interval(0.95)[1]) >= 0), axis = 3)\n\n\ndef coverage(est, var_est, param):\n params = np.repeat(param[:, :, :, np.newaxis], est.shape[-1], axis=3)\n return(np.mean( ((est +\n np.sqrt(var_est) *\n norm().interval(0.95)[0]) <= params ) * \n ((est +\n np.sqrt(var_est) *\n norm().interval(0.95)[1]) >= params), axis = 3))\n\n\nprint(coverage(gamma_hats_nn, vars_nn, gammas))\n","repo_name":"ehamid/HD_DoE","sub_path":"DoE-Simulations.ipynb","file_name":"DoE-Simulations.ipynb","file_ext":"py","file_size_in_byte":16126,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"25"} +{"seq_id":"9984559446","text":"# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"iD3o5MO0JQ5n\" outputId=\"41984c19-134c-4da8-ae81-1d1d69f97629\"\nfrom google.colab import drive\ndrive.mount('/content/drive')\n\n# + [markdown] id=\"4KZ8_h0LKE4V\"\n# # KMeans over Songs Features\n#\n\n# + id=\"7uRZa_XvKPC4\"\nimport pandas as pd\nfrom sklearn.cluster import KMeans\nfrom sklearn.preprocessing import StandardScaler\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set()\n\n# + [markdown] id=\"j9Fd71xNKigg\"\n# Load songs data (Extracted from MongoDB)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"hZR9X2KhKn-Y\" outputId=\"099de950-40a6-4d97-b0ee-8b97af11514d\"\ndata = pd.read_csv('/content/drive/MyDrive/DATASETS/songs.csv', engine='python')\nprint(data.describe())\n# Drop id to scale features\nsongs_features = data.drop(['_id'], axis=1)\n\n# + [markdown] id=\"MntvHEW-K9N0\"\n# Scaled data to avoid drift on cluster creation\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"ac4ASSUKLBGU\" outputId=\"e9a6871b-bbd1-463c-eba1-6528821e3493\"\nscaler = StandardScaler()\nscaler.fit(songs_features)\nX = scaler.transform(songs_features)\nprint('Scaled data between', X.min(), X.max())\n\n# + [markdown] id=\"ss8edzmbLE13\"\n# Create KMeans models and compute inertia\n\n# + id=\"EpHpsM0dLMb2\"\n# Set up parameters for K-Means\ncluster_number = range(1, 21)\n# Create models to test k value\nmodels = [KMeans(n_clusters=k) for k in cluster_number]\n# Compute Inertia for each model\ninertia = [model.fit(X).inertia_ for model in models]\n\n# + [markdown] id=\"_ymk2Dg2LRYd\"\n# Show the elbow curve\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 301} id=\"W3h5yoE4LTiB\" outputId=\"fcb88c7a-d6a1-4064-f3f5-8345b9f3da9f\"\nplt.plot(cluster_number, inertia)\nplt.xlabel('Number of Clusters')\nplt.xticks(cluster_number)\nplt.ylabel('Inertia')\nplt.title(\"Elbow curve for songs' features\")\nplt.savefig('elbow-curve.png')\nplt.show()\n\n# + [markdown] id=\"4hgW6rnhQlRU\"\n# K=8 is selected number of cluster. Train model and save it.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"kGIF5P62SLIs\" outputId=\"129327ca-2522-44f5-cc1c-46214fef257e\"\nfrom sklearn.pipeline import Pipeline\n\nprint(models[7].inertia_)\npipe = Pipeline([\n ('scale', scaler),\n ('model', models[7])\n])\npipe\n\n# + [markdown] id=\"uxXayGKgVMao\"\n#\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"Gmwrbte9VNHr\" outputId=\"5d3a867b-801c-4fc3-f60b-67a66050ab4d\"\ngenres = pipe.predict(songs_features)\ndata_genre = data.copy()\ndata_genre.insert(1, 'Genre', genres)\nprint(genres.max())\n\n# + [markdown] id=\"al22luUgUKBb\"\n# Show songs by cluster\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"dhCcnfG8UMYv\" outputId=\"6db777c3-782b-45ef-9d0a-bf28c1313200\"\ndata_genre.groupby('Genre').size()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 328} id=\"4xoCWhr1WFmP\" outputId=\"78e7b5e6-b8b2-4576-f35a-f869dd545d5d\"\ndata_genre.groupby('Genre').mean()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"VhHO5rFRf4bk\" outputId=\"84c8603d-6271-422d-d238-a4238c3da0f2\"\nimport joblib\n\njoblib.dump(pipe, '/content/drive/MyDrive/Models/genres_clustering.pkl')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"zKuOUN7HiyNR\" outputId=\"afc57bec-7950-4cf8-c520-d91a22d6d248\"\nmodel = joblib.load('/content/drive/MyDrive/Models/genres_clustering.pkl')\ngenres_2 = model.predict(songs_features)\ndata_genre = data.copy()\ndata_genre.insert(1, 'Genre', genres_2)\ndata_genre.groupby('Genre').size()\n","repo_name":"mgm9211/spotify-dashboard","sub_path":"KMeansTrain.ipynb","file_name":"KMeansTrain.ipynb","file_ext":"py","file_size_in_byte":3438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"25"} +{"seq_id":"28733719513","text":"# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# \"Open\n\n# + [markdown] id=\"ra9iNU7hD_h7\"\n# #线性回归\n#\n# 对于回归问题,最后类别往往是一个连续值进行选择,而非离散值,一般可能需要使用线性回归的方法,这里主要介绍简单线性回归,和局部加权线性回归。\n#\n# 数据集为 鲍鱼年龄预测数据集:https://raw.githubusercontent.com/Jack-Cherish/Machine-Learning/master/Regression/abalone.txt\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"aSlZzu48D7sD\" outputId=\"d151cc07-f606-4d96-e8e4-1f6d4f066610\"\n#下载数据\n# !wget https://raw.githubusercontent.com/Jack-Cherish/Machine-Learning/master/Regression/abalone.txt\n\n# + id=\"-e-V7kFjEgkC\"\n#加载数据\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef load_data(filename):\n with open(filename,'r') as f:\n content=f.readlines()\n \n\n data,label=[],[]\n for i in content:\n t=i.strip().split('\\t')\n data.append([float(j) for j in t[:-1]])\n label.append(float(t[-1]))\n \n return data,label\n\ndata,label=load_data('abalone.txt')\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"vDUaWXQ7FnXC\" outputId=\"211ef2ec-53d1-49d4-8b86-096c7183a9bf\"\n#局部加权线性回归实现\n\ndef lwlr(testPoint,data,label,k=1.0):\n #k为高斯核的k值,k越小越拟合训练集\n\n xMat=np.mat(data)\n yMat=np.mat(label).T\n m=xMat.shape[0]\n weights=np.mat(np.eye((m))) #创建对焦矩阵\n\n for j in range(m):\n diffMat=testPoint-xMat[j,:]\n weights[j,j]=np.exp(diffMat*diffMat.T/(-2.0*k**2))\n \n xTx=xMat.T*(weights*xMat)\n if np.linalg.det(xTx)==0.0:\n return \n ws=xTx.I *(xMat.T*(weights*yMat))\n\n return testPoint*ws\n\ndef lwlrTest(testArr,data,label,k=1.0):\n testArr=np.mat(testArr)\n m=testArr.shape[0]\n yHat=np.zeros(m)\n for i in range(m):\n yHat[i]=lwlr(testArr[i],data,label,k)\n return yHat\n\ndef standRegres(xArr,yArr):\n xMat = np.mat(xArr); yMat = np.mat(yArr).T\n xTx = xMat.T * xMat #根据文中推导的公示计算回归系数\n if np.linalg.det(xTx) == 0.0:\n print(\"矩阵为奇异矩阵,不能求逆\")\n return\n ws = xTx.I * (xMat.T*yMat)\n return ws\n\n \ndef rssError(yArr,yHatArr):\n return ((yArr-yHatArr)**2).sum()\n\nabX,abY=data,label\nprint('训练集与测试集相同:局部加权线性回归,核k的大小对预测的影响:')\nyHat01 = lwlrTest(abX[0:99], abX[0:99], abY[0:99], 0.1)\nyHat1 = lwlrTest(abX[0:99], abX[0:99], abY[0:99], 1)\nyHat10 = lwlrTest(abX[0:99], abX[0:99], abY[0:99], 10)\nprint('k=0.1时,误差大小为:',rssError(abY[0:99], yHat01.T))\nprint('k=1 时,误差大小为:',rssError(abY[0:99], yHat1.T))\nprint('k=10 时,误差大小为:',rssError(abY[0:99], yHat10.T))\nprint('')\nprint('训练集与测试集不同:局部加权线性回归,核k的大小是越小越好吗?更换数据集,测试结果如下:')\nyHat01 = lwlrTest(abX[100:199], abX[0:99], abY[0:99], 0.1)\nyHat1 = lwlrTest(abX[100:199], abX[0:99], abY[0:99], 1)\nyHat10 = lwlrTest(abX[100:199], abX[0:99], abY[0:99], 10)\nprint('k=0.1时,误差大小为:',rssError(abY[100:199], yHat01.T))\nprint('k=1 时,误差大小为:',rssError(abY[100:199], yHat1.T))\nprint('k=10 时,误差大小为:',rssError(abY[100:199], yHat10.T))\nprint('')\nprint('训练集与测试集不同:简单的线性归回与k=1时的局部加权线性回归对比:')\nprint('k=1时,误差大小为:', rssError(abY[100:199], yHat1.T))\nws = standRegres(abX[0:99], abY[0:99])\nyHat = np.mat(abX[100:199]) * ws\nprint('简单的线性回归误差大小:', rssError(abY[100:199], yHat.T.A))\n","repo_name":"zhangxs131/Machine_learning_notebook","sub_path":"linear_regresssion_base.ipynb","file_name":"linear_regresssion_base.ipynb","file_ext":"py","file_size_in_byte":3792,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"21"} +{"seq_id":"70836913332","text":"import numpy as np\nimport pandas as pd\nfrom mlxtend.frequent_patterns import apriori, association_rules\n\nimport numpy as np\n\ndata = pd.read_csv(\"LiquorSalesSamplev2.csv\")\ndata.head(10)\n\ndata.columns\n\n\ndata.columns = data.columns.str.replace(' ', '')\n\ndata.County.unique()\n\nbasket_3869 = (data[data['County'] ==\"Polk\"].groupby(['Invoice', 'Label'])['BottlesSold'].sum().unstack().reset_index().fillna(0).set_index('Invoice'))\nbasket_3869\n \n\ndef hot_encode(x):\n if(x<= 0):\n return 0\n if(x>= 1):\n return 1\nbasket_encoded = basket_3869.applymap(hot_encode)\nbasket_3869 = basket_encoded\n \n\n# +\nfrq_items = apriori(basket_3869, min_support = 0.30, use_colnames = True)\n \n# Collecting the inferred rules in a dataframe\nrules = association_rules(frq_items, metric =\"lift\", min_threshold = 1)\nrules = rules.sort_values(['confidence', 'lift'], ascending =[False, False])\nrules.head(20)\n\n# +\n#in Polk county if they purchased whiskey and liquer there is a high likelyhood they purchased vodka\n\n# +\n#goal: do this for all the counties next time\n#no to fp growth bc we have apriori\n#move on to classification\n#collect std, mean, yada, yada \n","repo_name":"Group-2-CSPB4502/Iowa-Liquor-Sales","sub_path":"Code/.ipynb_checkpoints/OriginalApriori_Unedited-checkpoint.ipynb","file_name":"OriginalApriori_Unedited-checkpoint.ipynb","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"21"} +{"seq_id":"36483986286","text":"# %load_ext autoreload\n# %autoreload 2\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import r2_score, accuracy_score\nfrom sklearn.preprocessing import LabelBinarizer\nfrom sklearn.linear_model import LogisticRegression, RidgeClassifier\nfrom sklearn.model_selection import cross_val_score, cross_validate\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.layers import Flatten, Dense, SimpleRNN\nfrom sklearn.ensemble import RandomForestClassifier\nfrom tensorflow.keras.callbacks import EarlyStopping\n\n# # Import data\n\ndata = pd.read_csv('../../raw_data/bitstampUSD.csv')\n\n# # Clean data\n\ndata['Timestamp'] = pd.to_datetime(data['Timestamp'], unit='s', origin='unix')\n\ndata = data[[\"Timestamp\", \"Open\"]].fillna(method='ffill')\n\n\ndef open_diff_col(data):\n data['Open_diff'] = data[\"Open\"].diff()\n clean_data = data[1:]\n return clean_data\n\n\ncleaned_data = open_diff_col(data)\n\ndata_sample = cleaned_data[2798176:]\ndata_test = data_sample[1829602:]\n\n\ndef y_encoding(data):\n data['Coded'] = data['Open_diff'].map(lambda x: 0 if x <= 0 else 1)\n return data\n\n\ny_encoded = y_encoding(data_test)\ny_encoded.head()\n\n# # Dumb baseline model\n\nbaseline_sample = data_sample[:1000000]\ny_base = y_encoding(baseline_sample)\nbase = y_base[['Coded']]\n\ntrain_size = 0.6\nindex = round(train_size*base.shape[0])\ndf_train = base.iloc[:index]\ndf_test = base.iloc[index+1:]\n\ny_pred = df_test.shift(1).dropna()\ny_true = df_test[1:]\nprint(f\"Accuracy:{accuracy_score(y_true, y_pred)}\")\n\n# # Simple Ridge Classifier model\n\ny_base.shape\n\ny_base.head()\n\n\ndef input_data(data, sample_size, shift_size, train_size):\n\n data_size = data.shape[0]\n sample = data.iloc[(data_size-sample_size):data_size]\n sample_pp = sample[['Open_diff', 'Timestamp']].set_index(\"Timestamp\").fillna(method='ffill')\n\n\n for i in range(1, shift_size+1):\n sample_pp[f't - {i}'] = sample_pp['Open_diff'].shift(i)\n sample_shifted = sample_pp.dropna() \n\n\n X = sample_shifted.drop(columns=['Open_diff'])\n y = sample_shifted['Open_diff']\n\n\n X_train = X.iloc[0:train_size]\n y_train = y.iloc[0:train_size]\n X_test = X.iloc[(train_size+1):(sample_size-shift_size)]\n y_test = y.iloc[(train_size+1):(sample_size-shift_size)]\n \n return X_train, X_test, y_train, y_test\n\nX_train, X_test, y_train, y_test = input_data(y_base, 10000, 20, 6000)\n\ny_test.head(20)\n\ny_train[y_train > 0] = 1\ny_train[y_train <= 0] = 0\ny_test[y_test > 0] =1\ny_test[y_test <= 0] = 0\n\n\ndef ridge_classifier(X_train, X_test, y_train, y_test):\n log_reg = RidgeClassifier()\n log_reg = log_reg.fit(X_train, y_train)\n results = log_reg.predict(X_test)\n score = log_reg.score(X_test, y_test)\n return score\n\n\nridge_classifier(X_train, X_test, y_train, y_test)\n\n# ## Random Forest Classifier\n\nrf = RandomForestClassifier()\nrf = rf.fit(X_train, y_train)\nresult = rf.predict(X_test)\nresult[:20]\n\nrf_score = rf.score(X_test, y_test)\nrf_score\n\n# ### with cross-val\n\ncv_results = cross_validate(RandomForestClassifier(), X_train, y_train, cv=10)\n\ncv_array = cv_results['test_score']\ncv_array\n\ncv_accuracy = cv_array.mean()\ncv_accuracy\n\n\n# ## Functions for modeling\n\n# +\ndef preprocessing_data(data, shift_size, h=1):\n data_pp = data[2798176:4727776]\n data_pp['Timestamp'] = pd.to_datetime(data_pp['Timestamp'], unit='s', origin='unix')\n data_pp = data_pp[['Open', 'Timestamp']].set_index(\"Timestamp\").fillna(method='ffill')\n data_pp['diff_Open'] = data_pp['Open'].diff(h)\n data_pp['diff_Open'] = data_pp['diff_Open'].dropna()\n data_pp[f\"t+{h}\"] = data_pp['diff_Open'].shift(-h)\n for i in range(0, shift_size):\n data_pp[f't-{i}'] = data_pp['Open'].shift(i)\n data_shifted = data_pp.dropna()\n X = data_shifted.drop(columns=['Open', 'diff_Open', f\"t+{h}\"])\n y = data_shifted[f\"t+{h}\"].copy()\n y[y > 0] = 1\n y[y <= 0] = 0\n return X, y, data_shifted\n\ndef input_data(data, sample_size, shift_size, train_size, h=1, w=0):\n X, y, data_shifted = preprocessing_data(data, shift_size, h)\n data_size = data_shifted.shape[0]\n sample_X = X.iloc[(data_size-sample_size-w):data_size-w]\n sample_y = y.iloc[(data_size-sample_size-w):data_size-w]\n X_train = sample_X.iloc[0:train_size]\n y_train = sample_y.iloc[0:train_size]\n X_test = sample_X.iloc[(train_size+h-1):(sample_size-shift_size)]\n y_test = sample_y.iloc[(train_size+h-1):(sample_size-shift_size)]\n return X_train, X_test, y_train, y_test\n\n\n# -\n\nX_train, X_test, y_train, y_test = input_data(data, 30000, 10, 20000)\n\nX_train.shape, y_train.shape, X_test.shape, y_test.shape\n\n\n\ndef deep_reshape(X_train, X_test, y_train, y_test):\n X_retrain, y_retrain = np.array(X_train), np.array(y_train)\n X_retrain = np.reshape(X_retrain, (X_retrain.shape[0], X_retrain.shape[1], 1))\n X_retest, y_retest = np.array(X_test), np.array(y_test)\n X_retest = np.reshape(X_retest, (X_retest.shape[0], X_retest.shape[1], 1))\n return X_retrain, X_retest, y_retrain, y_retest\n\n\nX_retrain, X_retest, y_retrain, y_retest = deep_reshape(X_train, X_test, y_train, y_test)\n\n\n# +\n# X_retrain, y_retrain = np.array(X_train), np.array(y_train)\n# X_retrain = np.reshape(X_retrain, (X_retrain.shape[0], X_retrain.shape[1], 1))\n\n# +\n# X_retest, y_retest = np.array(X_test), np.array(y_test)\n# X_retest = np.reshape(X_retest, (X_retest.shape[0], X_retest.shape[1], 1))\n# -\n\ndef initialize_model():\n model = Sequential()\n model.add(layers.SimpleRNN(units=10, activation='tanh'))\n model.add(layers.Dense(1, activation='sigmoid'))\n return model\n\n\ndef compile_model(model):\n model.compile(loss='binary_crossentropy', \n optimizer='rmsprop',\n metrics=['accuracy'])\n return model\n\n\nmodel = initialize_model()\nmodel = compile_model(model)\n\nes = EarlyStopping(patience=2, restore_best_weights=True)\nhistory = model.fit(X_retrain, y_retrain,\n# validation_split=0.3,\n epochs=50,\n batch_size=32,\n callbacks=[es])\n\nmodel.evaluate(X_retest, y_retest, verbose=2)\n\n# ## basic RNN results\n\n# +\n# (data, 12000, 10, 8000, h=1, w=0)\n# units=10, Dense 5, Dense 1\n# loss: 0.6931475400924683, accuracy: 0.49724310636520386]\n# -\n\n# # More advanced model\n\n# +\nlstm_model = Sequential()\nlstm_model.add(layers.LSTM(units=10, activation='tanh')) \nlstm_model.add(layers.Dense(5, activation=\"tanh\"))\nlstm_model.add(layers.Dense(1, activation='sigmoid'))\n\nlstm_model.compile(loss='binary_crossentropy', \n optimizer='rmsprop',\n metrics = 'accuracy')\n\nes = EarlyStopping(patience=4, restore_best_weights=True)\n\nlstm_history = lstm_model.fit(X_retrain, y_retrain,\n validation_split = 0.2,\n batch_size=16,\n callbacks=[es],\n epochs=50)\n\nlstm_model.evaluate(X_retest, y_retest, verbose=2)\n\n# +\nGRU_model = Sequential()\nGRU_model.add(layers.GRU(units=10, activation='tanh')) \nGRU_model.add(layers.Dense(20, activation=\"tanh\"))\nGRU_model.add(layers.Dense(1, activation='sigmoid'))\n\nGRU_model.compile(loss='binary_crossentropy', \n optimizer='rmsprop',\n metrics = 'accuracy')\n\nes = EarlyStopping(patience=5, restore_best_weights=True)\n\nGRU_history = lstm_model.fit(X_retrain, y_retrain,\n validation_split = 0.2,\n batch_size=16,\n callbacks=[es],\n epochs=50)\n\nGRU_model.evaluate(X_retest, y_retest, verbose=2)\n# -\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"nhuberde/batch-552-BITCOIN_PREDICTIONS","sub_path":"notebooks/Caro/organised.ipynb","file_name":"organised.ipynb","file_ext":"py","file_size_in_byte":7561,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"21"} +{"seq_id":"16806881076","text":"# +\nverb1 = \"\"\nplace1 = \"\"\nnoun1 = \"\"\nverb2 = \"\"\npronoun1 = \"\"\ningVerb1 = \"\"\nnumber1 = \"\"\nadjective1 = \"\"\nnumber2 = \"\"\nplace2 = \"\"\nnumber3 = \"\"\npluralNoun1 = \"\"\ningVerb2 = \"\"\nadjective2 = \"\"\nnoun2 = \"\"\nverb3 = \"\"\nnoun3 = \"\"\nverb4 = \"\"\nadjective3 = \"\"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nprint(\"When I \" + verb1 + \" to \" + place1 + \" I always get a bunch of \" + noun1 + \" because I just \" + verb2 + \" them!\")\nprint(pronoun1 + \" are very comforting and \" + ingVerb1 + \". And they only cost \" + number1 + \" dollars so they really arn't \" + adjective1 + \".\")\nprint(\"Yesterday, I spent \" + number2 + \" dollars at \" + place2 + \" because I bought \" + number3 + \" \" + pluralNoun1 + \".\")\nprint(\"I think I might have a \" + ingVerb2 + \" problem. It's so much \" + adjective2 + \" though.\")\nprint(\"It's not like I'm a \" + noun2 + \" and I can \" + verb3 + \" it so I don't know that it's a \" + noun3 + \".\")\nprint(\"What do you \" + verb4 + \" ? Do I have a spending problem or am I just a little \" + adjective3 + \"?\")\n","repo_name":"Andi-Orashan/CCIC_DataScience1","sub_path":"MadLibs.ipynb","file_name":"MadLibs.ipynb","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"21"} +{"seq_id":"27818605805","text":"# ![image.png](attachment:image.png)\n# # Classification with Python\n#\n# In this notebook we try to practice all the classification algorithms that we have learned in this course.\n#\n# We load a dataset using Pandas library, and apply the following algorithms, and find the best one for this specific dataset by accuracy evaluation methods.\n#\n# Let's first load required libraries:\n\nimport itertools\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import NullFormatter\nimport pandas as pd\nimport numpy as np\nimport matplotlib.ticker as ticker\nfrom sklearn import preprocessing\n# %matplotlib inline\n\n# # About dataset\n#\n# This dataset is about past loans. The Loan_train.csv data set includes details of 346 customers whose loan are already paid off or defaulted. \n\n# +\nURL = 'https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-ML0101EN-SkillsNetwork/labs/FinalModule_Coursera/data/loan_train.csv'\n \ntrain_data = pd.read_csv(URL, encoding = \"ISO-8859-1\")\n# -\n\n# ### Load Data From CSV File\n\ndf = train_data\ndf.head()\n\n# ### Convert to date time object\n\ndf['due_date'] = pd.to_datetime(df['due_date'])\ndf['effective_date'] = pd.to_datetime(df['effective_date'])\ndf.head()\n\n# ## Data visualization and pre-processing\n#\n# Let’s see how many of each class is in our data set\n\ndf['loan_status'].value_counts()\n\n#\n# 260 people have paid off the loan on time while 86 have gone into collection\n# Let's plot some columns to underestand data better:\n\n# +\nimport seaborn as sns\n\nbins = np.linspace(df.Principal.min(), df.Principal.max(), 10)\ng = sns.FacetGrid(df, col=\"Gender\", hue=\"loan_status\", palette=\"Set1\", col_wrap=2)\ng.map(plt.hist, 'Principal', bins=bins, ec=\"k\")\n\ng.axes[-1].legend()\nplt.show()\n\n# +\nbins = np.linspace(df.age.min(), df.age.max(), 10)\ng = sns.FacetGrid(df, col=\"Gender\", hue=\"loan_status\", palette=\"Set1\", col_wrap=2)\ng.map(plt.hist, 'age', bins=bins, ec=\"k\")\n\ng.axes[-1].legend()\nplt.show()\n# -\n\n# ## Pre-processing: Feature selection/extraction¶\n# ### Let's look at the day of the week people get the loan\n\ndf['dayofweek'] = df['effective_date'].dt.dayofweek\nbins = np.linspace(df.dayofweek.min(), df.dayofweek.max(), 10)\ng = sns.FacetGrid(df, col=\"Gender\", hue=\"loan_status\", palette=\"Set1\", col_wrap=2)\ng.map(plt.hist, 'dayofweek', bins=bins, ec=\"k\")\ng.axes[-1].legend()\nplt.show()\n\n# We see that people who get the loan at the end of the week don't pay it off, so let's use Feature binarization to set a threshold value less than day 4\n\ndf['weekend'] = df['dayofweek'].apply(lambda x: 1 if (x>3) else 0)\ndf.head()\n\n# ### Convert Categorical features to numerical values\n#\n# Let's look at gender: \n\ndf.groupby(['Gender'])['loan_status'].value_counts(normalize=True)\n\n# 86 % of female pay there loans while only 73 % of males pay there loan\n#\n# Let's convert male to 0 and female to 1:\n\ndf['Gender'].replace(to_replace=['male','female'], value=[0,1],inplace=True)\ndf.head()\n\n# ## One Hot Encoding\n# How about education?\n\ndf.groupby(['education'])['loan_status'].value_counts(normalize=True)\n\n# Features before One Hot Encoding\n\ndf[['Principal','terms','age','Gender','education']].head()\n\n# Use one hot encoding technique to conver categorical varables to binary variables and append them to the feature Data Frame\n\nFeature = df[['Principal','terms','age','Gender','weekend']]\nFeature = pd.concat([Feature,pd.get_dummies(df['education'])], axis=1)\nFeature.drop(['Master or Above'], axis = 1,inplace=True)\nFeature.head()\n\n# ### Feature Selection\n#\n# Let's define feature sets, X:\n\nX = Feature\nX[0:5]\n\n# What are our lables?\n\ny = df['loan_status'].values\ny[0:5]\n\n# ## Normalize Data\n#\n# Data Standardization give data zero mean and unit variance (technically should be done after train test split)\n\nX= preprocessing.StandardScaler().fit(X).transform(X)\nX[0:5]\n\n# Classification\n#\n# Now, it is your turn, use the training set to build an accurate model. Then use the test set to report the accuracy of the model You should use the following algorithm:\n#\n# K Nearest Neighbor(KNN)\n# Decision Tree\n# Support Vector Machine\n# Logistic Regression\n#\n# __ Notice:__\n#\n# You can go above and change the pre-processing, feature selection, feature-extraction, and so on, to make a better model.\n# You should use either scikit-learn, Scipy or Numpy libraries for developing the classification algorithms.\n# You should include the code of the algorithm in the following cells.\n#\n# K Nearest Neighbor(KNN)\n#\n# Notice: You should find the best k to build the model with the best accuracy.\\ warning: You should not use the loan_test.csv for finding the best k, however, you can split your train_loan.csv into train and test to find the best k.\n#\n\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=4)\nprint ('Train set:', X_train.shape, y_train.shape)\nprint ('Test set:', X_test.shape, y_test.shape)\n\n# +\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn import metrics\nk = 6\n\nneighK6 = KNeighborsClassifier(n_neighbors = k).fit(X_train,y_train)\nneighK6\n \nyhat = neighK6.predict(X_test)\nyhat[0:5]\n\nprint(\"Train set Accuracy: \", metrics.accuracy_score(y_train, neighK6.predict(X_train)))\nprint(\"Test set Accuracy: \", metrics.accuracy_score(y_test, yhat))\n\n# +\nKs = 10\nmean_acc = np.zeros((Ks-1))\nstd_acc = np.zeros((Ks-1))\n\nConfustionMx = [];\nfor n in range(1,Ks):\n \n \n neigh = KNeighborsClassifier(n_neighbors = n).fit(X_train,y_train)\n yhat=neigh.predict(X_test)\n mean_acc[n-1] = metrics.accuracy_score(y_test, yhat)\n\n \n std_acc[n-1]=np.std(yhat==y_test)/np.sqrt(yhat.shape[0])\n\nplt.plot(range(1,Ks),mean_acc,'g')\nplt.fill_between(range(1,Ks),mean_acc - 1 * std_acc,mean_acc + 1 * std_acc, alpha=0.10)\nplt.legend(('Accuracy ', '+/- 3xstd'))\nplt.ylabel('Accuracy ')\nplt.xlabel('Number of Nabors (K)')\nplt.tight_layout()\nplt.show()\nprint( \"Best accuracy:\", mean_acc.max(), \"k=\", mean_acc.argmax()+1)\n# -\n\n# ## Decision Tree\n\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.model_selection import train_test_split\nX_trainset, X_testset, y_trainset, y_testset = train_test_split(X, y, test_size=0.3, random_state=3)\n#Modelling\nTree = DecisionTreeClassifier(criterion=\"entropy\", max_depth = 6)\nTree\n\nTree.fit(X_trainset,y_trainset)\n\n# +\nfrom sklearn import metrics\nfrom sklearn import tree\nimport matplotlib.pyplot as plt\n\nfrom six import StringIO\nimport pydotplus\nimport matplotlib.image as mpimg\n\nimport pydotplus\nimport graphviz\n\npredTree = Tree.predict(X_testset)\nprint (predTree [0:5])\nprint (y_testset [0:5])\n\nprint(\"Accuracy: \", metrics.accuracy_score(y_testset, predTree))\n# -\n\n# %matplotlib inline \ndot_data = StringIO()\nfilename = \"loan.png\"\nfeatureNames = df.columns[0:8]\ntargetNames = df['loan_status'].unique().tolist()\nout=tree.export_graphviz(Tree,feature_names=featureNames, out_file=dot_data, class_names= np.unique(y_trainset), filled=True, special_characters=True,rotate=False) \ngraph = pydotplus.graph_from_dot_data(dot_data.getvalue()) \ngraph.write_png(filename)\nimg = mpimg.imread(filename)\nplt.figure(figsize=(100, 200))\nplt.imshow(img,interpolation='nearest')\n\n# ## Support Vector Machine\n\n# +\ndf.dtypes\ndf = df[pd.to_numeric(df['education'], errors='coerce').notnull()]\ndf['education'] = df['education'].astype('int')\ndf.dtypes\n\nfrom sklearn import svm\nclf = svm.SVC(kernel='rbf')\nclf.fit(X_train, y_train)\n# -\n\nyhat = clf.predict(X_test)\nyhat [0:5]\nfrom sklearn.metrics import classification_report, confusion_matrix\nimport itertools\n\n\n# +\ndef plot_confusion_matrix(cm, classes,\n normalize=False,\n title='Confusion matrix',\n cmap=plt.cm.Blues):\n\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n\n fmt = '.2f' if normalize else 'd'\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, format(cm[i, j], fmt),\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\ncnf_matrix = confusion_matrix(y_test, yhat, labels=['PAIDOFF','COLLECTION'])\nnp.set_printoptions(precision=2)\n\nprint (classification_report(y_test, yhat))\n\nplt.figure()\nplot_confusion_matrix(cnf_matrix, classes=['PAIDOFF','COLLECTION'],normalize= False, title='Confusion matrix')\n\nfrom sklearn.metrics import f1_score\nf1_score(y_test, yhat, average='weighted')\n\nfrom sklearn.metrics import jaccard_score as jaccard_similarity_score\njaccard_similarity_score(y_test, yhat, pos_label=\"PAIDOFF\")\n# -\n\n# ## Logistic Regression\n\n# +\ndf = df[['loan_status', 'Principal', 'terms', 'effective_date', 'due_date', 'age', 'education', 'Gender']]\ndf['loan_status'] = df['loan_status'].astype('int')\n\nfrom sklearn import preprocessing\nX = preprocessing.StandardScaler().fit(X).transform(X)\nX[0:5]\n\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=4)\nprint ('Train set:', X_train.shape, y_train.shape)\nprint ('Test set:', X_test.shape, y_test.shape)\n\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import confusion_matrix\nLogR = LogisticRegression(C=0.01, solver='liblinear').fit(X_train,y_train)\nLogR\n# -\n\nyhat = LogR.predict(X_test)\nyhat\nyhat_prob = LogR.predict_proba(X_test)\nyhat_prob\n\nfrom sklearn.metrics import jaccard_score as jaccard_similarity_score\njaccard_similarity_score(y_test, yhat, pos_label=\"PAIDOFF\")\nfrom sklearn.metrics import log_loss\nlog_loss(y_test, yhat_prob)\n\n# ## Model Evaluation using Test set\n\nfrom sklearn.metrics import jaccard_score\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics import log_loss\n\nURL2 = 'https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/loan_test.csv'\ntest_data = pd.read_csv(URL, encoding = \"ISO-8859-1\")\ntest_df = test_data\ntest_df.head()\n\n# ### Load Test set for evaluation\n\ntest_df.head()\n\nX= preprocessing.StandardScaler().fit(X).transform(X)\nX[0:5]\nY = test_df['loan_status'].values\nY[0:5]\n\n# +\n#test the KNN algorithm already trained with K=6\nyhatKNN=neigh.predict(X)\nKNNJaccard = jaccard_similarity_score(y,yhatKNN,pos_label='PAIDOFF')\nKNNF1 = f1_score(y, yhatKNN, average='weighted')\nprint(\"Avg F1-score: %.2f\" % KNNF1 )\nprint(\"KNN Jaccard Score: %.2f\" % KNNJaccard)\n\n\nyhatDEC = Tree.predict(X)\nDTJaccard = jaccard_similarity_score(y, yhatDEC,pos_label='PAIDOFF')\nDTF1 = f1_score(y, yhatDEC, average='weighted')\nprint(\"Avg F1-score: %.2f\" % DTF1 )\nprint(\"Decision Tree Jaccard Score: %.2f\" % DTJaccard)\n\nyhatSVM=clf.predict(X)\nSVMJaccard = jaccard_similarity_score(y, yhatSVM,pos_label='PAIDOFF')\nSVMF1 = f1_score(y, yhatSVM, average='weighted')\nprint(\"Avg F1-score: %.2f\" % SVMF1)\nprint(\"SVM Jaccard score: %.2f\" % SVMJaccard)\n\nyhatLOG = LogR.predict(X)\nyhatLOGproba = LogR.predict_proba(X)\nLogRJaccard = jaccard_similarity_score(y, yhatLOG,pos_label='PAIDOFF')\nLogRF1 = f1_score(y, yhatLOG, average='weighted')\nLogloss = log_loss(y, yhatLOGproba)\nprint(\"LogLoss: : %.2f\" % Logloss)\nprint(\"Avg F1-score: %.4f\" % LogRF1)\nprint(\"LOG Jaccard score: %.4f\" % LogRJaccard)\n# -\n\n# # Report\n#\n# You should be able to report the accuracy of the built model using different evaluation metrics:\n#\n# |Algorithm |Jacard|F1 |LogLoss|\n# |-------------|------|-----|-------|\n# |KNN \t |.77 |.78 |NA |\n# |Decision Tree|.75 \t |.78 |NA |\n# |SVM \t |.75 |.76 |NA |\n# |LogisticReg |.7227 |.7199|.56 |\n","repo_name":"katdown-code/IBM-Course-Work","sub_path":"mod9/final-machine-learning.ipynb","file_name":"final-machine-learning.ipynb","file_ext":"py","file_size_in_byte":11997,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"21"} +{"seq_id":"37452098278","text":"# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# \"Open\n\n# + id=\"vKoidO9b2wiE\"\nimport pandas as pd\nimport re\nimport numpy as np\nimport seaborn as sns\nfrom collections import Counter\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"SKm0hnJX3p4u\" outputId=\"e296a9f3-2fa3-4e1f-e12e-215b17338f8f\"\nfrom google.colab import drive\ndrive.mount('/content/drive')\n\n# + id=\"JGCw1qxa37yZ\"\n# !unzip '/content/drive/MyDrive/finalproject/dataset.zip' -d '/content/drive/MyDrive/finalproject/data'\n\n# + [markdown] id=\"2WxptyFv2wiI\"\n# # Jigsaw bias dataset\n\n# + id=\"2bkAS1z02wiI\" outputId=\"1ea460b5-269c-4eac-e464-07f50bbfeb1a\"\nimport pandas as pd\n\njigsaw_bias = pd.read_csv('C:\\\\Users\\\\user\\\\OneDrive\\\\Desktop\\\\codestates\\\\기업협업\\\\dataset\\\\jigsaw-unintended-bias-in-toxicity-classification\\\\train.csv')\njigsaw_bias\n\n# + id=\"W2PsTi7Q2wiK\" outputId=\"c75aa755-aec2-463e-f064-7d57be6fd6f1\"\nimport numpy as np\n\njigsaw_bias.target = np.where(jigsaw_bias.target >= 0.5, 1, 0)\njigsaw_bias = jigsaw_bias[['target', 'comment_text']]\njigsaw_bias.target.value_counts()\n\n# + id=\"usMH4GgHFDhJ\" outputId=\"c75aa755-aec2-463e-f064-7d57be6fd6f1\"\nimport numpy as np\n\njigsaw_bias.target = np.where(jigsaw_bias.target >= 0.7, 1, 0)\njigsaw_bias = jigsaw_bias[['target', 'comment_text']]\njigsaw_bias\n\n# + id=\"Sb8Slf5vFDhK\" outputId=\"98bd66cf-e02e-4795-ad11-f1ded90c1d03\"\njigsaw_bias.target.value_counts()\n\n# + id=\"7UHQ73RE2wiL\" outputId=\"1b25d0f4-ad5f-4c6f-f5a5-1cec4c4a1d7a\"\nfor i,cmmt in enumerate(jigsaw_bias.comment_text):\n print(cmmt)\n if i == 10:\n break \n\n# + id=\"xGTgNeB_2wiL\" outputId=\"0e1c0b33-9b85-4103-c346-59648e725f39\"\njigsaw_tar = jigsaw_bias[(jigsaw_bias.target == 1)]\njigsaw_tar\n\n# + id=\"06POgzHrFDhM\" outputId=\"8e854797-1089-470e-a623-97df1c1b670a\"\njigsaw = jigsaw_bias[(jigsaw_bias.target == 0)]\njigsaw = jigsaw.sample(n=9000,random_state=10)\njigsaw\n\n# + id=\"TEQgyDkAFDhN\" outputId=\"c32623e1-6369-4eb2-f088-5515c114876f\"\njigsaw = jigsaw.rename(columns={'comment_text':'cmmt_list'})\njigsaw['cmmt_list'] = jigsaw['cmmt_list'].apply(lambda x: [x])\ncontext_2 = pd.concat([jigsaw,context])\ncontext_2\n\n# + [markdown] id=\"L5JAZ_YTFDhN\"\n# # Jigsaw dataset\n\n# + id=\"txBy-uyH2wiM\" outputId=\"a864fd30-f3d4-40eb-b224-95182bc2c0f8\"\nimport pandas as pd\n\njigsaw_train = pd.read_csv('C:\\\\Users\\\\user\\\\OneDrive\\\\Desktop\\\\codestates\\\\기업협업\\\\dataset\\\\jigsaw_train.csv')\njigsaw_train\n\n# + id=\"ky7fdsBtFDhO\" outputId=\"30cedf34-926f-4f6a-bce7-c10110fcb371\"\njigsaw_train['target'] = jigsaw_train[['toxic','severe_toxic','obscene','threat','insult','identity_hate']].sum(axis=1)\njigsaw_train['target'] = jigsaw_train['target'].apply(lambda x: 1 if x > 0 else x)\njigsaw_train.target.value_counts()\n\n# + id=\"ws3TPhi_2wiM\" outputId=\"03a60913-fa2b-49cd-8797-0a55327c1895\"\njigsaw_train = jigsaw_train[['comment_text','target']]\njigsaw = pd.concat([jigsaw_train,jigsaw_tar])\n\njigsaw\n\n# + id=\"uR1KF9682wiN\" outputId=\"66e356d0-fb60-46b3-f19d-78e92a654fed\"\njigsaw.target.value_counts()\n\n# + id=\"cpHQJwLYFDhP\" outputId=\"4a28d1a3-816a-4847-cb8a-17c396b202be\"\nfor comment in jigsaw.comment_text:\n if comment.startswith('['):\n print(comment)\n\n# + [markdown] id=\"6Pe4Cpwx2wiO\"\n# # GAP\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 111} id=\"dK6LowUy2wiO\" outputId=\"95ac9778-103d-4b63-f2df-6ecfe1efa5d7\"\nimport pandas as pd\n\ngap = pd.read_csv('https://raw.githubusercontent.com/jing-qian/A-Benchmark-Dataset-for-Learning-to-Intervene-in-Online-Hate-Speech/master/data/gab.csv')\ngap\n\n# + id=\"8vaJXZHv2wiP\" outputId=\"f41852cb-55ef-4e7b-d9b1-86a111fd5867\"\nc = 0\nfor t,i,r in zip(gap.text, gap.hate_speech_idx, gap.response):\n print('Text',t,'\\nResponse:',r,'\\nLabel:',i,'\\n*****************************')\n c+=1\n if c == 5:\n break \n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"o48w4hqh2wiP\" outputId=\"50760990-4c7c-4ccd-91cb-6498f9e46c42\"\ngap.isnull().sum()\n\n# + [markdown] id=\"uciroTLr2wiQ\"\n# # Reddit\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 111} id=\"vef3IK732wiQ\" outputId=\"13505d2d-f060-4be2-8159-390e6b773d77\"\nreddit = pd.read_csv('https://raw.githubusercontent.com/jing-qian/A-Benchmark-Dataset-for-Learning-to-Intervene-in-Online-Hate-Speech/master/data/reddit.csv')\nreddit\n\n# + id=\"grZwibaF2wiQ\" outputId=\"a3c6d07b-e6ab-4ee0-fc27-8fae7d97e5f0\"\ni = 0\nfor t,r in zip(reddit.text, reddit.response):\n print(t,'\\nResponse:',r,'\\n*****************************')\n i+=1\n if i == 2:\n break \n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 419} id=\"oClJLlbl2wiR\" outputId=\"27adc31d-9720-47f6-8dc7-3a4703fd1469\"\ndf = pd.concat([reddit,gap])\ndf = df[['text','hate_speech_idx']]\ndf.reset_index(drop=True, inplace=True)\n\ndf\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"Ok8Z_4Xo2wiR\" outputId=\"99d63161-7ede-448a-9583-944ce0854306\"\norg_len = len(df)\ndf = df.dropna()\nprint(df.isnull().sum())\nprint(f'Total {org_len - len(df)} datas were dropped')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"PE-S1I5F2wiS\" outputId=\"a04aad93-95c8-49f5-cbb9-fc0c675f30e8\"\nimport re\n\ndf['target'] = df['hate_speech_idx'].apply(lambda x: re.findall('[0-9]+',x))\ndf['target'] = df['target'].apply(lambda x: list(map(int, x)))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"59FoWtWPOpod\" outputId=\"a314a77c-b01a-4099-8d01-dd625d5f0a1f\"\nprint(type(df.target[0]))\nprint(type(df.target[0][0]))\n\n# + id=\"7p5r4_uPFDhV\" outputId=\"33a1722f-0aff-428d-fc89-80cc64b075d7\"\nmax_len = max([len(label) for label in df.target])\nprint(max_len)\n\n# + id=\"ZSveR1elFDhX\" outputId=\"04a64368-fa6e-47ad-cbd6-cb0b06aa015f\"\n#라벨이 한개인 데이터만 남김\nimport numpy as np\n\norg_len = len(df)\ndf['target'] = df['target'].apply(lambda x: x if len(x) ==1 else np.NaN)\ndf = df.dropna()\nprint(f'total {org_len - len(df)} datas are dropped')\n\n# + id=\"Sb0HeQWuFDhY\" outputId=\"b9c399e7-f7e4-463e-ffb8-c57508652beb\"\ncnt=0\nfor target, cmmt in zip(df.target, df.text):\n if 1 not in target:\n print('target:',target)\n print(cmmt)\n cnt+=1\n if cnt > 3:\n break\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"P4v8540w2wiS\" outputId=\"cc13f450-96d2-41a2-fa19-bb100d383d80\"\nmax_label = 0\n\nfor i,l_list in enumerate(df.target):\n for label in l_list:\n if label > max_label:\n max_label = label\n elif label == max_label:\n print(i,max_label)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"BOIxtVk32wiS\" outputId=\"a1c6559e-0df0-4626-c0fd-421844761ccf\"\ncmmt = []\nfor cnt, cmmts in enumerate(df.text):\n texts = []\n if len(cmmt) != cnt:\n print(cnt)\n break\n for i in range(1,22):\n try:\n if i == 1:\n text = cmmts.split(f'{i}. ')[1]\n else:\n text = cmmts.split(f'\\n{i}. ')[1]\n text = text.split(f'\\n{i+1}. ')[0]\n text = text.strip()\n texts.append(text) \n \n except IndexError:\n cmmt.append(texts)\n if cnt == len(df.text)-1:\n print('Splitting all rows is finished')\n break\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 521} id=\"F6Xw-3Po2wiU\" outputId=\"ff744e76-1556-44f7-b92e-e733c90be1d3\"\ndf['cmmt_list'] = cmmt\ndata = df[['target','cmmt_list']]\ndata\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"33Z9cKTy2wiU\" outputId=\"c964d54b-22b6-4a4c-c772-6e78590315c8\"\n#Non toxic 코멘트 추가\norg_data = len(data)\n\nfor cmmt, labels in zip(data.cmmt_list, data.target):\n for i in range(labels[-1]): #toxic speech가 있는 열까지만 출력\n if i+1 not in labels:\n try:\n data = data.append({'target':0,'cmmt_list':[cmmt[i]]},ignore_index=True)\n except IndexError:\n print(i)\n print(labels)\n print(len(cmmt))\n break\n \nprint(f'Total {len(data)-org_data} of non_toxic commets are added')\n\n# + id=\"nYgihkdnFDha\" outputId=\"95864b58-e65f-4336-9feb-4e03e7bdebbe\"\nfor i, (cmmt, labels) in enumerate(zip(data.cmmt_list, data.target)):\n if labels == [20] and len(cmmt) < 20:\n print(i)\n\n# + id=\"s4evmoypFDha\" outputId=\"6ec06b3a-fee8-4b15-e73c-f5475f2f1977\"\nprint(df.text.iloc[3311])\nprint(df.cmmt_list.iloc[3311])\nprint(df.target.iloc[3311])\n\n# + id=\"RQkZi22HFDha\"\ndata = data.drop(data.index[3311])\ndata = data.reset_index(drop=True)\n\n# + id=\"ic7H4_IjFDhb\" outputId=\"521ac378-b7f4-4419-8276-9e8ffa0af0c4\"\ndf_2 = data[['cmmt_list','target']]\n\nfor idx, cmmts in enumerate(data['cmmt_list']):\n cnt = 0\n org_len = len(cmmts)\n new_text = []\n new_label = [0] * len(data['target'][idx])\n \n for i,cmmt in enumerate(cmmts):\n if cmmt == '[deleted]' or cmmt == '[removed]' or cmmt == 'deleted' or cmmt == 'removed':\n #라벨 변경\n for j,label in enumerate(data['target'][idx]):\n #[deleted]나 [removed]가 label이었으면 해당 라벨 제거\n if label == i+1: \n data['target'][idx].remove(i+1)\n print(f'deleted wrong label at index{idx}')\n #[deleted]나 [removed]보다 뒷 문장에 매겨진 라벨들은 -1해줌\n elif label > i+1:\n new_label[j]+=1\n #delete 개수 세기\n cnt+=1\n else:\n new_text.append(cmmt)\n \n if org_len - len(new_text) == cnt and cnt != 0:\n data['cmmt_list'][idx] = new_text\n for j in range(len(data['target'][idx])):\n data['target'][idx][j] = data['target'][idx][j] - new_label[j]\n \n elif org_len - len(new_text) == cnt and cnt == 0:\n pass\n else:\n print(f'Index {idx} has error')\n break\n\ncnt=0\nfor new, org in zip(data['cmmt_list'], df_2['cmmt_list']):\n idx = 0\n if new != org:\n for i in range(len(org)):\n try:\n if new[i-idx] != org[i]:\n cnt+=1\n idx+=1\n \n except IndexError: #맨 마지막 문장이 삭제된 경우\n cnt+=1\n \nprint(f'total {cnt} of [deleted]/[removed] sentences are deleted') \n\n# + id=\"YvITfHUSFDhc\" outputId=\"44ba5876-05e2-470a-8cf2-1bf63341c9d4\"\ndf.text.iloc[3250]\n\n# + id=\"GfTi2n5HFDhd\"\ndata = data.drop(data.index[3250])\ndata = data.reset_index(drop=True)\n\n# + id=\"phDdxa6BFDhd\" outputId=\"43e1f7f3-9a52-4558-f204-16924227c779\"\ndf_2 = data[['cmmt_list','target']]\ndf_2\n\n# + id=\"d7Jtk_bsFDhd\" outputId=\"bb0aeb4f-4cdd-4c06-fb64-87bbea927d00\"\n#앞의 문장은 toxic이 아니고, 뒷문장과 합쳐졌을 때 toxic임\n#코멘트의 인덱스는 label-1\n\norg_len = len(data)\nsig_non = 0\ncon_non = 0\nsig_tox = 0\ncon_tox = 0\n\nfor cmmt, labels in zip(data.cmmt_list, data.target):\n try:\n label = labels[0]\n if len(labels) > 1: #라벨이 두 개 이상일 때\n for label in labels:\n if label > 1:\n data = data.append({'target':1,'cmmt_list':[cmmt[label-2:label]]},ignore_index=True) #앞문장과 합쳐졌을때 toxic\n con_tox+=1\n\n #non-toxic context 생성 \n if label > 2 and label-1 not in labels and label-2 not in labels: #toxic 앞 두 문장이 non toxic\n data = data.append({'target':0,'cmmt_list':[cmmt[label-3:label-1]]},ignore_index=True)\n con_non+=1\n elif label-1 not in labels:\n data = data.append({'target':0,'cmmt_list':[cmmt[label-2]]},ignore_index=True) #앞앞문장이 toxic이거나 없을 때\n sig_non+=1\n\n #첫 번째 문장이 toxic일 때 \n elif label == 1:\n data = data.append({'target':1,'cmmt_list':[cmmt[0]]},ignore_index=True)\n sig_tox+=1\n\n elif label > 3: #라벨이 하나고 세번째 문장 이후면\n data = data.append({'target':0,'cmmt_list':[cmmt[label-3:label-1]]},ignore_index=True) #앞의 두 문장 non toxic\n data = data.append({'target':1,'cmmt_list':[cmmt[label-2:label]]},ignore_index=True) #바로 앞문장과 해당 문장 toxic\n con_non+=1\n con_tox+=1\n elif label == 2: #라벨이 하나고 두번째 문장이면\n data = data.append({'target':0,'cmmt_list':[cmmt[label-2]]},ignore_index=True) #앞의 문장은 non toxic\n data = data.append({'target':1,'cmmt_list':[cmmt[label-2:label]]},ignore_index=True) #뒷문장과 합쳐졌을 때 toxic\n sig_non+=1\n sig_tox+=1\n else: #라벨이 하나고 첫번째 문장이면\n data = data.append({'target':1,'cmmt_list':[cmmt[0]]},ignore_index=True) #앞의 문장은 non toxic\n sig_tox+=1\n \n except IndexError:\n print(labels)\n print(cmmt)\n\n \nprint(f'Total {sig_tox} of toxic single-commets are added')\nprint(f'Total {sig_non} of non-toxic single-commets are added')\nprint(f'Total {con_tox} of toxic context-commets are added')\nprint(f'Total {con_non} of non-toxic context-commets are added')\nprint()\nprint(f'Totally {len(data)-org_len} of commets are added')\nassert len(data)-org_len == sig_tox + sig_non + con_tox + con_non\n\n# + id=\"xB4Ntd8LFDhe\" outputId=\"10797974-2ca2-4e3c-f870-22b4540e6b14\"\ndata = data[-28785:]\ndata = data.reset_index(drop=True)\ndata\n\n# + id=\"XuEU3WwQFDhg\" outputId=\"d1d35e75-8251-4a43-b4bd-4656b71555e8\"\n#non_toxic context data 추가\ncnt=0\norg_len = len(data)\n\nfor cmmt, labels in zip(df_2.cmmt_list, df_2.target):\n for label in labels:\n try:\n if label+1 not in labels and label+2 not in labels:\n data = data.append({'target':0,'cmmt_list':cmmt[label:label+2]},ignore_index=True)\n cnt+=1\n except:\n continue\n if cnt > 4900: #Toxic contxt 개수 - non toxic context 개수랑 비슷하게 맞추기\n break\n\nif cnt < 4901:\n print('Additinal process...')\n for cmmt, labels in zip(df_2.cmmt_list, df_2.target):\n if len(labels) == 1 and labels[0] > 4:\n data = data.append({'target':0,'cmmt_list':cmmt[label[0]-5:label[0]-3]},ignore_index=True)\n cnt+=1\n if cnt > 4900:\n break\n \nprint(f'Total {len(data)-org_len} of non-toxic context-commets are added')\n\n# + id=\"ZVwuDdWpFDhh\" outputId=\"a041f292-e0d7-4b65-eff3-43642fd5b4ff\"\ndata = data.reset_index(drop=True)\ndata\n\n# + id=\"sRf9V_JGFDhi\" outputId=\"0ad363b8-d67d-4988-bd15-90aa4d0791bb\"\nimport numpy as np\n\ndef clean(cmmt):\n if not cmmt:\n return np.NaN\n return cmmt\n \ndata['cmmt_list'] = data['cmmt_list'].apply(lambda x: clean(x))\n\ndata.isnull().sum()\n\n# + id=\"n7UMLL7OFDhi\" outputId=\"3bc3afd6-677a-476c-b5a1-9b2d22693988\"\ndata = data.dropna()\ndata\n\n# + id=\"Tsb6JhQUFDhj\"\ndata = data.reset_index(drop=True)\n\n# + id=\"MbNn4lckFDhj\" outputId=\"0b870da9-cb36-49c0-860f-6ce45f8b2ced\"\nsig_non = 0\ncon_non = 0\nsig_tox = 0\ncon_tox = 0\n\nfor i, (target, cmmts) in enumerate(zip(data.target, data.cmmt_list)):\n if len(cmmts) == 2 and target == 1:\n con_tox+=1\n elif len(cmmts) == 2 and target == 0:\n con_non+=1\n elif len(cmmts) == 1 and target == 1:\n sig_tox+=1\n elif len(cmmts) == 1 and target == 0:\n sig_non+=1\n else:\n print('IDX:',i,'LEN:',len(cmmts),'TARGET:',target)\n \nprint(f'con_tox : {con_tox}',f'con_non : {con_non}',f'sig_tox : {sig_tox}',f'sig_non : {sig_non}',sep='\\n')\n\n#위에서 con_tox 잘못계산함...\n\n# + id=\"3zLSC24zFDhj\" outputId=\"a07490e2-9447-4f15-eeb7-27555976ff83\"\norg_len = len(context)\n\nfor cmmt, labels in zip(df_2.cmmt_list, df_2.target):\n if len(labels) == 1 and labels[0] > 16:\n context = context.append({'target':0,'cmmt_list':cmmt[labels[0]-5:labels[0]-3]},ignore_index=True)\n\nprint(f'Total {len(context)-org_len} of non-toxic context-commets are added')\n\n# + id=\"kZG7AG2iFDhk\" outputId=\"50f7a469-e978-4b1f-ab5c-6313c05d6573\"\norg_len = len(data)\n\nfor cmmt, labels in zip(df_2.cmmt_list, df_2.target):\n if len(labels) == 1 and labels[0] > 6:\n data = data.append({'target':0,'cmmt_list':cmmt[labels[0]-7:labels[0]-5]},ignore_index=True)\n\nprint(f'Total {len(data)-org_len} of non-toxic context-commets are added')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 419} id=\"pEv_sU9T3jXH\" outputId=\"939c6627-7207-4693-b04c-17779677ac18\"\nimport pandas as pd\nimport ast\n\ndata = pd.read_csv('C:\\\\Users\\\\user\\\\OneDrive\\\\Desktop\\\\codestates\\\\기업협업\\\\dataset\\\\gap_reddit_2.csv', index_col=0)\ndata['target'] = data['target'].apply(lambda x: ast.literal_eval(x))\ndata['cmmt_list'] = data['cmmt_list'].apply(lambda x: ast.literal_eval(x))\ndata['target'] = data['target'].apply(lambda x: list(map(int, x)))\ndata\n\n# + id=\"0QkE88BCFDhk\"\nfor target, cmmt in zip(data.target, data.cmmt_list):\n if target == [2,3]:\n print(cmmt)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"_HikaFBf7_i8\" outputId=\"7102d861-f55b-4d50-b2de-522bd18e757f\"\norg_data = len(data)\ni = 0\nfor cmmts, labels in zip(data.cmmt_list, data.target):\n cnt = 0\n for label in labels:\n #Option1)label == 1이면 한문장, 2면 0:1, 3이면 0:2, 2,3이면 0:2, 0:3\n #Option2)label == 1이면 한문장, 2면 0:1, 3이면 1:2, 2,3이면 0:1, 1:2\n if label != 0: \n cmmt = cmmts[:label]\n data = data.append({'target':[1], 'cmmt_list':cmmt}, ignore_index=True)\n cnt+=1\n if cnt == len(labels):\n data = data.drop(data.index[i])\n i-=1\n elif label == 0:\n cmmt = cmmts[:2]\n data = data.append({'target':[0], 'cmmt_list':cmmt}, ignore_index=True)\n data = data.drop(data.index[i])\n i-=1\n i+=1\n \nprint(f'Total {len(data)-org_data} of toxic commets are added')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 419} id=\"P-O5WMj9RH01\" outputId=\"25419af0-2089-4c62-feb1-fb8cb7777fab\"\ndata\n\n# + id=\"iMmn7NjaFDhm\" outputId=\"d11f89eb-3134-4512-b72e-a0345268f0b2\"\ndata['target'] = data['target'].apply(lambda x: x[0])\n\ndata.target.unique()\n\n# + id=\"yukeKVT4FDho\" outputId=\"a50da9b5-9a39-428a-c869-9ca5e7c4ea5a\"\norg_data = len(data)\ni = 0\nfor cmmts in data.cmmt_list:\n if cmmts == ['removed'] or cmmts == [['removed']] or cmmts == ['[removed]']:\n data = data.drop(data.index[i])\n i-=1\n i+=1\n \nprint(f'Total {org_data-len(data)} of datas are deleted')\n\n# + id=\"pBBy-xdtFDho\" outputId=\"76371a55-b80e-441a-b480-c00a4c4c9952\"\ndata.target.value_counts()\n\n# + id=\"rGJt5BTwFDhp\" outputId=\"f20df95e-e97a-4eb8-972d-923a93a01cd6\"\nimport numpy as np\n\n# target = data[(data.target == 1)]\n# data = data[(data.target == 0)]\n\ndf = data.copy()\ndf['cmmt_list'] = df['cmmt_list'].apply(lambda x: x if len(x)<3 else np.NaN)\ndf = df.dropna()\ndf.target.value_counts() \n\n# + id=\"DNXzadnGFDhq\" outputId=\"8f9f880f-adfc-46c2-cdde-d5fcf9d0c48d\"\njigsaw = jigsaw.rename(columns={'comment_text':'cmmt_list'})\ndf = pd.concat([data,jigsaw])\n\ndf\n\n# + id=\"c4n2UizuFDhr\" outputId=\"b7e42e03-0cc9-49ff-b3cb-64741e58a5e0\"\ndf.target.value_counts()\n\n# + id=\"WDRIlHONFDhs\"\ndf.to_csv('finaldata.csv', index=False)\n\n# + [markdown] id=\"e1xxCoUl2wiW\"\n# # gao2018\n\n# + id=\"WqVR_EO5FDhs\" outputId=\"862c96d4-8d86-4a97-9336-d6f2ed279940\"\nimport pandas as pd\n\ngao = pd.read_json('https://raw.githubusercontent.com/sjtuprog/fox-news-comments/master/full-comments-u.json#', lines = True)\ngao\n\n# + id=\"6dtEaIY3FDhs\" outputId=\"def7f108-4861-45a7-cc3b-dc05baa5b3da\"\ngroup = gao.groupby('title').sum()\nsample = dict(zip(list(group.index), list(group['label'])))\nsample\n\n# + id=\"Si_55immFDht\" outputId=\"d200e20a-b769-423c-80a0-7bce827c14cc\"\ntarget = gao[(gao.label == 0)]\nprint('Before sampling:',gao.label.value_counts(),sep='\\n')\ngao = gao[(gao.label == 1)]\n\ncmmt = dict(zip(list(group.index), [0]*len(list(group.index))))\n\nfor i in range(len(target)):\n title = target.iloc[i]['title']\n if cmmt[title] < sample[title]:\n gao = gao.append({'title':target.iloc[i]['title'], 'text':target.iloc[i]['text'], 'label':target.iloc[i]['label']}, ignore_index=True)\n cmmt[title]+=1\n \nprint('-'*10)\nprint('After sampling:',gao.label.value_counts(),sep='\\n') \n\n# + id=\"cvReqydTFDht\" outputId=\"2c05ca35-b1c7-442b-f36d-2c41b85f3471\"\ngao.groupby(['title','label']).count()\n\n# + id=\"qP0A72H0FDht\" outputId=\"b5e0c4c6-525a-480d-f6e4-6d21c9067376\"\ngao = gao[['title','text','label']]\n\ncontext = []\n\nfor title, text in zip(gao.title, gao.text):\n context.append([title,text])\n \ngao['cmmt_list'] = context\ngao = gao[['cmmt_list','label']]\ngao = gao.rename(columns={'label':'target'})\ngao\n\n# + id=\"HlpbTgJsFDht\" outputId=\"7a74155c-e540-4807-cb16-d534ce28beb2\"\ncontext = pd.concat([gao,data])\n\ncontext\n\n# + id=\"3Hu2v21rFDhu\" outputId=\"441b7e4c-e53c-4d82-ec87-30e29ece047a\"\ndf_gao.target.value_counts()\n\n# + id=\"JB4j334BFDhu\"\ndf_gao.to_csv('finaldata_wgao.csv', index=False)\n\n# + [markdown] id=\"kplhSGHSFDhu\"\n# # Pan12\n\n# + id=\"Dk3YehLVQfTC\" outputId=\"5f80fe0d-f291-430b-9a43-e277161ceb69\"\nimport xml.etree.ElementTree as ET\n\ntree = ET.parse('C:\\\\Users\\\\user\\\\OneDrive\\\\Desktop\\\\codestates\\\\기업협업\\\\dataset\\\\pan12\\\\train\\\\training-corpus.xml')\nroot = tree.getroot()\n\nroot.tag\n\n# + id=\"fErOIJqlFDhv\" outputId=\"dc2685c3-6b48-448e-e8d4-2f7e4b42331a\"\nlen(root[0])\n\n# + id=\"tGmISH06FDhv\"\npd.read_csv('C:\\\\Users\\\\user\\\\OneDrive\\\\Desktop\\\\codestates\\\\기업협업\\\\dataset\\\\pan12\\\\train\\\\training-corpus.xml')\n\n# + id=\"WLUSZKJYFDhv\" outputId=\"46a6527d-5533-4e96-ad01-f9d40040df53\"\nroot[0][8][2].text\n\n# + id=\"TXoc9OuWFDhv\" outputId=\"cf195e2e-2892-4b28-b115-74aac0843a56\"\ncmmts = []\n\nfor i in len(root):\n for i in len(root[i]):\n id = root[i][0][0].text\n text = root[i][0][2].text\n\n# + [markdown] id=\"kJonT-xL2wiY\"\n# # data collection\n\n# + id=\"0qIGiU1n2wiZ\" outputId=\"3d084212-3d63-4503-f11b-cedc0f19289c\"\ndfs = pd.read_csv('C:\\\\Users\\\\user\\\\OneDrive\\\\Desktop\\\\codestates\\\\기업협업\\\\dataset\\\\combined.tsv', sep='\\t')\n\ndfs = dfs[(dfs.file_language == 'en')]\ndfs.file_name.unique()\n\n# + id=\"8sFZLFyF2wia\" outputId=\"e3735a80-7916-4b5e-c26e-2eb4aab35bc6\"\nfiles = ['ousidhoum2019en.csv', 'davidson2017en.csv', 'gibert2018en.csv',\n 'gao2018en.csv', 'qian2019en_gab.csv', 'qian2019en_reddit.csv',\n 'mandl2019en.csv', 'bretschneider2017en.csv', 'basile2019en.csv',\n 'wulczyn2017en_toxic.csv', 'wulczyn2017en_aggressive.csv',\n 'wulczyn2017en_attack.csv', 'zampieri2019en.csv',\n 'bretschneider2016en_wow.csv', 'bretschneider2016en_lol.csv']\n\ndf = dfs[(dfs.file_name == files[0])]\ndf\n\n# + id=\"EOZoSYrHFDhx\" outputId=\"9304a3ac-c29d-4f2d-9563-09eb756ea260\"\ndf.labels.unique()\n\n# + id=\"YK1Q3figFDhx\"\ndf['cmmt_list'] = df['cmmt_list'].apply(lambda x: ast.literal_eval(x))\n\n# + [markdown] id=\"6Zsg3htXFDhx\"\n# # Toxicity Detection: Does Context Really Matter?\n\n# + id=\"yKeHj7sXFDhy\" outputId=\"1b38ea1b-e761-4c9e-f0d7-80a57a7721b0\"\ngc = pd.read_csv('C:\\\\Users\\\\user\\\\OneDrive\\\\Desktop\\\\codestates\\\\기업협업\\\\dataset\\\\gc.csv')\ngc\n\n# + id=\"OTnqFlYbFDhy\" outputId=\"cef7c24f-172f-4c28-fcdd-451352f93a8d\"\ngc.label.value_counts()\n\n\n# + id=\"SNIzbLmqFDhy\" outputId=\"13f16e2f-bee2-4d1f-f994-919d307d7e1f\"\ndef sampling_func(data, n_sample):\n np.random.seed(10)\n N = len(data)\n sample = data.take(np.random.permutation(N)[:n_sample])\n return sample\n\ngc = gc.groupby('label', group_keys=False).apply(sampling_func, n_sample=151)\ngc.label.value_counts()\n\n# + id=\"yw_n2InuFDhy\"\ndata = gc[(gc.label == 1)]\n\ni = 0\nfor q,a in zip(data.parent,data.text):\n if i > 10:\n break\n print('PARENT:\\n',q)\n print('TEXT:\\n',a)\n print('*'*10)\n i+=1\n\n# + [markdown] id=\"BcU4LW6JFDhz\"\n# 데이터들이 공격적이거나 나쁜 말들이 아닌데도 label이 1로 부여되어 있어 안쓰기로 결정\n\n# + id=\"XHW0agYmFDhz\" outputId=\"73ba8725-3ed1-4369-95e7-d76644ea711c\"\ncomments = []\nfor q,a in zip(gc.parent,gc.text):\n comments.append([q,a])\n\ngc['cmmt_list'] = comments\ngc = gc.rename(columns={'label':'target'})\ngc = gc[['target','cmmt_list']]\ncontext = pd.concat([gao,gc])\n\ncontext\n\n# + id=\"ygZfH701FDhz\" outputId=\"f0680d0a-56f5-4ef6-92b7-1176a3c96df1\"\ncontext.target.value_counts()\n\n# + [markdown] id=\"VwD8m-47FDh0\"\n# # Sexual tweet\n\n# + id=\"pF6YVLCGFDh0\" outputId=\"6100fe28-be92-4e0a-b9c3-53d63223ffaa\"\nsa = pd.read_csv('C:\\\\Users\\\\user\\\\OneDrive\\\\Desktop\\\\codestates\\\\기업협업\\\\dataset\\\\sexual_Cleaned_tweets.csv')\nsa\n\n# + id=\"2oEByAU_FDh0\" outputId=\"1a2ae75e-5df7-4db8-dff8-2fa06d421270\"\ndata = sa[(sa['Unnamed: 9'].notnull())]\ndata\n\n# + id=\"iSfKL5wGFDh0\" outputId=\"fcb86802-5267-40fb-f8b6-ea7806d91644\"\nsa['Text'][127] = sa['Text'][127] + ', ' + sa['Unnamed: 9'][127] + ', ' + sa['Unnamed: 10'][127]\nsa['Text'][1874] = sa['Text'][1874] + ', ' + sa['Unnamed: 9'][1874] + ', ' + sa['Unnamed: 10'][1874] + ', ' + sa['Unnamed: 11'][1874]\nsa['Text'][2043] = sa['Text'][2043] + ', ' + sa['Unnamed: 9'][2043] \nsa['Text'][2955] = sa['Text'][2955] + ', ' + sa['Unnamed: 9'][2955]\nsa['Text'][4095] = sa['Text'][4095] + ', ' + sa['Unnamed: 9'][4095] + ', ' + sa['Unnamed: 10'][4095]\n\ndata = sa[(sa['Unnamed: 10'].notnull())]\ndata\n\n# + id=\"d85Z0XjYFDh1\" outputId=\"2d8bf032-7a0c-4fcd-f782-03dd6c7e3502\"\nsa = sa.drop(['Unnamed: 9','Unnamed: 10','Unnamed: 11'], axis=1)\nsa = sa[['Label','Text']]\nsa = sa.rename(columns={'Label':'target','Text':'cmmt_list'})\n\nsa\n\n# + id=\"W3X3We_vFDh1\" outputId=\"42cc19f2-ccad-440b-bf14-168e9301b65e\"\nsa.target.value_counts()\n\n# + id=\"hHfZcNdHFDh1\" outputId=\"52e448d4-0b5d-4e3c-a04c-11fedc0e77d6\"\ni = 0\nfor label, cmmt in zip(sa.target, sa.cmmt_list):\n if label == 1 and i > 70 and i < 101:\n print(i, cmmt)\n elif label > 100:\n break\n i+=1\n\n# + [markdown] id=\"uX0S3gTHFDh1\"\n# 1,6, 10, 18, 19, 30, 40, 41, 42, 50, 42, 54, 63, 70, 78, 82, 90, 94\n# drop 29, 79\n\n# + id=\"4QazEyMIFDh2\" outputId=\"d929ec25-34a3-405c-96df-2a933d3d560f\"\nidx = [1, 6, 10, 18, 19, 30, 40, 41, 42, 50, 42, 54, 63, 70, 78, 82, 90, 94]\n\nfor i in idx:\n sa['target'][i] = 0\n\nsa = sa.drop(sa.index[29])\nsa[77:80]\n\n# + id=\"UI1EP6RsFDh3\" outputId=\"5564e1c6-3aef-4d1a-ef1e-b89e6aea2975\"\nsa['cmmt_list'] = sa['cmmt_list'].apply(lambda x: [x])\nsa\n\n# + id=\"ExzKhozpFDh4\" outputId=\"4498478b-d6b5-4cf8-9421-2b210b647862\"\ncontext = pd.concat([sa, context])\ncontext\n\n# + id=\"Y0Pma081FDh5\" outputId=\"89e55285-2ac3-4916-e895-9c3d54c865e0\"\ncontext.target.value_counts()\n\n# + id=\"RnYMk6kiFDh5\" outputId=\"91a1b1a8-7678-474b-9df2-61d5c8cd9e4c\"\nver1 = pd.concat([sa,df])\nver1 = ver1.dropna()\nver1 = ver1.reset_index(drop=True)\n\nver1\n\n# + id=\"LJAuZ9TLFDh5\" outputId=\"97d138c6-3e0b-4c23-ca0d-b7ea7ab0eb96\"\ndf.to_csv('finaldata.csv', index=False)\n\ndf_gao = pd.concat([sa,df_gao])\ndf_gao.to_csv('finaldata_wgao.csv', index=False)\n\ndf_gao\n\n# + [markdown] id=\"BWp08Bj7FDh6\"\n# # Questions\n\n# + id=\"T1PmOnkQFDh6\" outputId=\"4e1c7901-ec5c-404b-bd23-a2fa66eeea78\"\nq = pd.read_csv('C:\\\\Users\\\\user\\\\OneDrive\\\\Desktop\\\\codestates\\\\기업협업\\\\dataset\\\\question\\\\train.csv')\nq\n\n# + id=\"7McLntilFDh7\" outputId=\"a91a8474-db9b-4383-99ac-dabf87095a00\"\nq.target.value_counts()\n\n\n# + id=\"WYRtFb5rFDh7\" outputId=\"11fe1776-d7e5-4a2e-8e63-3451b10ff77d\"\ndef sampling_func(data, n_sample):\n np.random.seed(10)\n N = len(data)\n sample = data.take(np.random.permutation(N)[:n_sample])\n return sample\n\nq = q.groupby('target', group_keys=False).apply(sampling_func, n_sample=9120)\nq.target.value_counts()\n\n# + id=\"yqW-o_grFDh7\" outputId=\"af0d62e7-6b1f-4e80-db3b-aba33e9189be\"\nq['cmmt_list'] = q['question_text'].apply(lambda x : [x])\nq = q[['target','cmmt_list']]\ncontext = pd.concat([q,context])\ncontext.target.value_counts()\n\n# + [markdown] id=\"YbwfRyziFDh8\"\n# # Racism\n\n# + id=\"hCCTx0IzFDh8\" outputId=\"0274b614-9fd2-4014-b794-2d031723c79a\"\nracism = pd.read_csv('C:\\\\Users\\\\user\\\\OneDrive\\\\Desktop\\\\codestates\\\\기업협업\\\\dataset\\\\twitter_racism_parsed_dataset.csv')\nracism\n\n# + id=\"nvZSqllUFDh8\" outputId=\"ae387859-a36c-426f-c856-64b90021e282\"\nracism.oh_label.value_counts()\n\n\n# + id=\"sJq5Bj7OFDh8\" outputId=\"96dd0344-a420-4ca6-ef96-fd0c57158807\"\ndef sampling_func(data, n_sample):\n np.random.seed(10)\n N = len(data)\n sample = data.take(np.random.permutation(N)[:n_sample])\n return sample\n\nracism = racism.groupby('oh_label', group_keys=False).apply(sampling_func, n_sample=1970)\nracism.oh_label.value_counts()\n\n# + id=\"IKYk2rj5FDh9\" outputId=\"2adc6792-8985-43af-c40e-20b2548702f7\"\nracism['Text'] = racism['Text'].apply(lambda x : ['how do you think of them?',x])\nracism = racism[['Text','oh_label']]\nracism = racism.rename(columns={'oh_label':'target','Text':'cmmt_list'})\n\ncontext = pd.concat([racism,context])\ncontext\n\n# + [markdown] id=\"XvuiZE3NFDh9\"\n# # Preprocessing\n\n# + [markdown] id=\"sXmvUPihFDh9\"\n# ## Ver1. Use pronoun, swearing\n\n# + id=\"IFrBsgRSFDh9\"\nimport re\nimport unicodedata\n\ndef clean_text(text):\n text = text.lower().strip()\n text = ''.join(c for c in unicodedata.normalize('NFD', text) if unicodedata.category(c) != 'Mn')\n text = re.sub(r'[\\r|\\t|\\n]', ' ', text)\n text = re.sub('(http|ftp|https)://(?:[-\\w.]|(?:\\da-f]{2}))+','',text) #url 제거\n text = re.sub('(\\[a-z0-9\\_.+-\\]+@\\[a-z0-9-\\]+.\\[a-z0-9-.\\]+)','',text) #email 제거\n text = re.sub('<[^>]*>','',text) #html tag 제거\n text = re.sub(r\"[^a-z.!?]+\", r\" \", text) #문자+문장부호만 빼고 모두 제거\n text = re.sub(r\"([.!?])\", r\" \\1\", text) #문장부호는 \\1로 대체\n text = re.sub(' the ', ' ', text)\n text = re.sub(' a ', ' ', text)\n text = re.sub(' u ', 'you ', text)\n text = re.sub(' ur ', ' your ', text)\n text = re.sub(' y ', 'why ', text)\n text = re.sub(' ciu ', 'see you ', text)\n text = re.sub(' da ', 'dumb ass ', text)\n text = re.sub(' fug ', 'fuck ugly ', text)\n text = re.sub('gratest', 'greatest ', text)\n text = re.sub('sh\\*t', 'shit ', text)\n text = re.sub('s\\*\\*t', 'shit ', text)\n text = re.sub('f\\*ck', 'fuck ', text)\n text = re.sub(' f ', 'fuck ', text)\n text = re.sub('fu\\*k', 'fuck ', text)\n text = re.sub('f\\*\\*k', 'fuck ', text) \n text = re.sub('f\\*\\*\\*\\*\\*g', 'fuck ', text)\n text = re.sub('p\\*ssy', 'pussy ', text)\n text = re.sub('p\\*\\*\\*y', 'pussy ', text)\n text = re.sub('pu\\*\\*y', 'pussy ', text)\n text = re.sub('p\\*ss', 'piss ', text)\n text = re.sub('b\\*tch', 'bitch ', text)\n text = re.sub('bit\\*h', 'bitch ', text)\n text = re.sub(' btch ', 'bitch ', text)\n text = re.sub(' bch ', 'bitch ', text)\n text = re.sub('h\\*ll', 'hell ', text)\n text = re.sub('h\\*\\*l', 'hell ', text)\n text = re.sub('cr\\*p', 'crap ', text)\n text = re.sub('d\\*mn', 'damn ', text)\n text = re.sub('stu\\*pid', 'stupid ', text)\n text = re.sub('st\\*pid', 'stupid ', text)\n text = re.sub('n\\*gger', 'nigger ', text)\n text = re.sub('n\\*\\*\\*ga', 'nigger ', text)\n text = re.sub('f\\*ggot', 'faggot ', text)\n text = re.sub('scr\\*w', 'screw ', text)\n text = re.sub('pr\\*ck', 'prick ', text)\n text = re.sub('g\\*d', 'god ', text)\n text = re.sub('s\\*x', 'sex ', text)\n text = re.sub('a\\*s', 'ass ', text)\n text = re.sub('a\\*\\*hole', 'asshole ', text)\n text = re.sub('a\\*\\*\\*ole', 'asshole ', text)\n text = re.sub('a\\*\\*', 'ass ', text) \n text = re.sub(r\"im \", \"i am \", text)\n text = re.sub(r\"what's\", \"what is \", text)\n text = re.sub(r\"\\'s\", \" \", text)\n text = re.sub(r\"\\'ve\", \" have \", text)\n text = re.sub(r\"can't\", \"can not \", text)\n text = re.sub(r\"n't\", \" not \", text)\n text = re.sub(r\"i'm\", \"i am \", text)\n text = re.sub(r\"\\'re\", \" are \", text)\n text = re.sub(r\"\\'d\", \" would \", text)\n text = re.sub(r\"\\'ll\", \" will \", text)\n text = re.sub(r\"\\'scuse\", \" excuse \", text)\n text = re.sub('\\W', ' ', text)\n text = re.sub('\\s+', ' ', text)\n text = text.strip(' ')\n \n return text\n\ndef preprocessing(comment):\n cnt=0\n if type(comment) == str:\n return clean_text(comment)\n elif type(comment) == list:\n cnt+=1\n comments = []\n for text in comment:\n if text == 'removed' or text == '[removed]' or text == ['removed']:\n continue\n text = clean_text(text)\n comments.append(text)\n return ' [SEP] '.join(comments)\n else:\n print(type(comment))\n\n\n# + id=\"ODFov4DJFDh-\" outputId=\"d7430c2c-6498-4cbc-99a1-ff30d01d3b59\"\nimport time\n\nstart = time.time()\nver1['cleaned_comment'] = ver1['cmmt_list'].apply(lambda x: preprocessing(x))\nprint(f'Preprocessing is finished: {time.time()-start:.2f} secs are taken')\n\n# + id=\"aClN4padFDh-\" outputId=\"c1760f98-4173-4a4f-b9bb-d5adf17517ea\"\norg_len = len(ver1)\nver1 = ver1[(ver1.cleaned_comment != '')]\nprint(f'Total {org_len-len(ver1)} of datas are removed')\n\n# + id=\"h0ELo9JKFDh-\" outputId=\"5546cbfa-a302-46ab-e654-69ab8033f370\"\nimport seaborn as sns\n\nver1['char_length'] = ver1['cleaned_comment'].apply(lambda x: len(str(x)))\n\nsns.displot(ver1['char_length']);\n\n# + id=\"1tUb5q1EFDh-\" outputId=\"50e870b4-06d4-4687-a25b-f5b371d13f7f\"\nver1_trim = ver1[(ver1.char_length <= 512)]\nver1_trim = ver1_trim[['target','cleaned_comment']]\n\nver1_trim.to_csv('finaldata.csv', index=False)\nprint(len(ver1_trim))\nprint(ver1_trim['target'].value_counts())\n\n# + [markdown] id=\"gbkFZ4n7FDh_\"\n# ## Ver2. lemmatizing & change some target words to token\n\n# + id=\"A7mKHZEzFDh_\" outputId=\"c2c6cb45-495d-49f7-de1a-552f08e7ab0d\"\n# !pip install -U nltk\n\n# + id=\"jE7qyBnRFDh_\" outputId=\"d2ec1ce7-ec04-443a-ca58-429a25c96ab2\"\nfrom nltk import pos_tag\nfrom nltk.stem import WordNetLemmatizer\n\nwnl = WordNetLemmatizer()\n\ndef penn2morphy(penntag):\n \"\"\" Converts Penn Treebank tags to WordNet. \"\"\"\n morphy_tag = {'NN':'n', 'JJ':'a',\n 'VB':'v', 'RB':'r'}\n try:\n return morphy_tag[penntag[:2]]\n except:\n return 'n' \n\ntext = 'FUCKing you bitches'\ntext = text.lower().split()\ntext = ' '.join([wnl.lemmatize(w, pos=penn2morphy(tag)) for w, tag in pos_tag(text)])\ntext\n\n# + id=\"BotLUYdcFDh_\"\nimport re\nimport unicodedata\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk import pos_tag\n\nwnl = WordNetLemmatizer()\ntarget = ['gay', 'gays', 'homosexual', 'lesbian', 'LGBT', 'moslem', 'muslim', 'jew', 'jews' 'blacks', 'nigga', 'niggas']\n\ndef penn2morphy(penntag):\n \"\"\" Converts Penn Treebank tags to WordNet. \"\"\"\n morphy_tag = {'NN':'n', 'JJ':'a',\n 'VB':'v', 'RB':'r'}\n try:\n return morphy_tag[penntag[:2]]\n except:\n return 'n' \n\ndef clean_text(text):\n text = text.lower().strip()\n text = ''.join(c for c in unicodedata.normalize('NFD', text) if unicodedata.category(c) != 'Mn')\n text = re.sub(r'[\\r|\\t|\\n]', ' ', text)\n text = re.sub('(http|ftp|https)://(?:[-\\w.]|(?:\\da-f]{2}))+','',text) #url 제거\n text = re.sub('(\\[a-z0-9\\_.+-\\]+@\\[a-z0-9-\\]+.\\[a-z0-9-.\\]+)','',text) #email 제거\n text = re.sub('<[^>]*>','',text) #html tag 제거\n text = re.sub(r\"[^a-z.!?]+\", r\" \", text) #문자+문장부호만 빼고 모두 제거\n text = re.sub(r\"([.!?])\", r\" \\1\", text) #문장부호는 \\1로 대체\n text = re.sub(' the ', ' ', text)\n text = re.sub(' a ', ' ', text)\n text = re.sub(' u ', 'you ', text)\n text = re.sub(' ur ', ' your ', text)\n text = re.sub(' y ', 'why ', text)\n text = [w for w in text.split() if len(w)>1] #remove single alphabet in the sentence\n text = [w if w not in target else '[TARGET]' for w in text]\n text = ' '.join([wnl.lemmatize(w, pos=penn2morphy(tag)) for w, tag in pos_tag(text)])\n text = re.sub(' ciu ', 'see you ', text)\n text = re.sub(' da ', 'dumb ass ', text)\n text = re.sub(' fug ', 'fuck ugly ', text)\n text = re.sub('gratest', 'greatest ', text)\n text = re.sub('sh\\*t', 'shit ', text)\n text = re.sub('s\\*\\*t', 'shit ', text)\n text = re.sub('f\\*ck', 'fuck ', text)\n text = re.sub('fu\\*k', 'fuck ', text)\n text = re.sub('f\\*\\*k', 'fuck ', text) \n text = re.sub('f\\*\\*\\*\\*\\*g', 'fuck ', text)\n text = re.sub('p\\*ssy', 'pussy ', text)\n text = re.sub('p\\*\\*\\*y', 'pussy ', text)\n text = re.sub('pu\\*\\*y', 'pussy ', text)\n text = re.sub('p\\*ss', 'piss ', text)\n text = re.sub('b\\*tch', 'bitch ', text)\n text = re.sub('bit\\*h', 'bitch ', text)\n text = re.sub(' btch ', 'bitch ', text)\n text = re.sub(' bch ', 'bitch ', text)\n text = re.sub('h\\*ll', 'hell ', text)\n text = re.sub('h\\*\\*l', 'hell ', text)\n text = re.sub('cr\\*p', 'crap ', text)\n text = re.sub('d\\*mn', 'damn ', text)\n text = re.sub('stu\\*pid', 'stupid ', text)\n text = re.sub('st\\*pid', 'stupid ', text)\n text = re.sub('n\\*gger', 'nigger ', text)\n text = re.sub('n\\*\\*\\*ga', 'nigger ', text)\n text = re.sub('f\\*ggot', 'faggot ', text)\n text = re.sub('scr\\*w', 'screw ', text)\n text = re.sub('pr\\*ck', 'prick ', text)\n text = re.sub('g\\*d', 'god ', text)\n text = re.sub('s\\*x', 'sex ', text)\n text = re.sub('a\\*s', 'ass ', text)\n text = re.sub('a\\*\\*hole', 'asshole ', text)\n text = re.sub('a\\*\\*\\*ole', 'asshole ', text)\n text = re.sub('a\\*\\*', 'ass ', text) \n text = re.sub(r\"im \", \"i am \", text)\n text = re.sub(r\"what's\", \"what is \", text)\n text = re.sub(r\"\\'s\", \" \", text)\n text = re.sub(r\"\\'ve\", \" have \", text)\n text = re.sub(r\"can't\", \"can not \", text)\n text = re.sub(r\"n't\", \" not \", text)\n text = re.sub(r\"i'm\", \"i am \", text)\n text = re.sub(r\"\\'re\", \" are \", text)\n text = re.sub(r\"\\'d\", \" would \", text)\n text = re.sub(r\"\\'ll\", \" will \", text)\n text = re.sub(r\"\\'scuse\", \" excuse \", text)\n text = re.sub('\\W', ' ', text)\n text = re.sub('\\s+', ' ', text)\n text = text.strip(' ')\n \n return text\n\ndef preprocessing(comment):\n if type(comment) == str:\n return clean_text(comment)\n elif type(comment) == list:\n comments = []\n for text in comment:\n if text == 'removed' or text == '[removed]' or text == ['removed']:\n continue\n text = clean_text(text)\n comments.append(text)\n return ' [SEP] '.join(comments)\n else:\n print(type(comment))\n\n\n# + id=\"t2Mz0Nw_FDiA\" outputId=\"1e474ae4-a63f-4e42-d28f-0b8e09c776c8\"\nimport time\n\nstart = time.time()\nver2 = ver1.copy()\nver2['cleaned_comment'] = ver2['cmmt_list'].apply(lambda x: preprocessing(x))\nprint(f'Preprocessing is finished: {time.time()-start:.2f} secs are taken')\n\n# + id=\"5cDGH5_7FDiA\" outputId=\"56dee020-37f3-4142-b4bb-82f8dcfaa432\"\norg_len = len(ver2)\nver2 = ver2[(ver2.cleaned_comment != '')]\nprint(f'Total {org_len-len(ver2)} of datas are removed')\n\n# + id=\"t79pKwm-FDiB\" outputId=\"b33c88fb-7e67-4ce4-f980-82e110289e32\"\nimport seaborn as sns\n\nver2['char_length'] = ver2['cleaned_comment'].apply(lambda x: len(str(x)))\n\nsns.displot(ver2['char_length']);\n\n# + id=\"QIp8YwweFDiB\" outputId=\"17035903-67ae-4834-8a35-4f09617fa590\"\nver2_trim = ver2[(ver2.char_length <= 512)]\nver2_trim = ver2_trim[['target','cleaned_comment']]\n\nver2_trim.to_csv('finaldata_ver2.csv', index=False)\nprint(len(ver2_trim))\nprint(ver2_trim['target'].value_counts())\n\n# + [markdown] id=\"EZO86M-LFDiB\"\n# ## Ver3. Context dataset\n\n# + id=\"dAlf3lFBFDiC\" outputId=\"b3760864-02e2-427c-8744-2554d16860c0\"\nsig_non = 0\ncon_non = 0\nsig_tox = 0\ncon_tox = 0\n\nfor i, (target, cmmts) in enumerate(zip(context.target, context.cmmt_list)):\n if len(cmmts) == 2 and target == 1:\n con_tox+=1\n elif len(cmmts) == 2 and target == 0:\n con_non+=1\n elif len(cmmts) == 1 and target == 1:\n sig_tox+=1\n elif len(cmmts) == 1 and target == 0:\n sig_non+=1\n else:\n print('IDX:',i,'LEN:',len(cmmts),'TARGET:',target)\n \nprint(f'con_tox : {con_tox}',f'con_non : {con_non}',f'sig_tox : {sig_tox}',f'sig_non : {sig_non}',sep='\\n')\n\n# + id=\"KJjUSTlAFDiC\"\nimport re\nimport unicodedata\n\ndef clean_text(text):\n text = text.lower().strip()\n text = ''.join(c for c in unicodedata.normalize('NFD', text) if unicodedata.category(c) != 'Mn')\n text = re.sub(r'[\\r|\\t|\\n]', ' ', text)\n text = re.sub('(http|ftp|https)://(?:[-\\w.]|(?:\\da-f]{2}))+','',text) #url 제거\n text = re.sub('(\\[a-z0-9\\_.+-\\]+@\\[a-z0-9-\\]+.\\[a-z0-9-.\\]+)','',text) #email 제거\n text = re.sub('<[^>]*>','',text) #html tag 제거\n text = re.sub(r\"[^a-z.!?]+\", r\" \", text) #문자+문장부호만 빼고 모두 제거\n text = re.sub(r\"([.!?])\", r\" \\1\", text) #문장부호는 \\1로 대체\n text = re.sub(' the ', ' ', text)\n text = re.sub(' a ', ' ', text)\n text = re.sub(' u ', 'you ', text)\n text = re.sub(' ur ', ' your ', text)\n text = re.sub(' y ', 'why ', text)\n text = ' '.join([w for w in text.split() if len(w)>1]) #remove single alphabet in the sentence\n #text = ' '.join([wnl.lemmatize(w, pos=penn2morphy(tag)) for w, tag in pos_tag(text)])\n text = re.sub(' ciu ', 'see you ', text)\n text = re.sub(' da ', 'dumb ass ', text)\n text = re.sub(' fug ', 'fuck ugly ', text)\n text = re.sub('gratest', 'greatest ', text)\n text = re.sub('sh\\*t', 'shit ', text)\n text = re.sub('s\\*\\*t', 'shit ', text)\n text = re.sub('f\\*ck', 'fuck ', text)\n text = re.sub('fu\\*k', 'fuck ', text)\n text = re.sub('f\\*\\*k', 'fuck ', text) \n text = re.sub('f\\*\\*\\*\\*\\*g', 'fuck ', text)\n text = re.sub('p\\*ssy', 'pussy ', text)\n text = re.sub('p\\*\\*\\*y', 'pussy ', text)\n text = re.sub('pu\\*\\*y', 'pussy ', text)\n text = re.sub('p\\*ss', 'piss ', text)\n text = re.sub('b\\*tch', 'bitch ', text)\n text = re.sub('bit\\*h', 'bitch ', text)\n text = re.sub(' btch ', 'bitch ', text)\n text = re.sub(' bch ', 'bitch ', text)\n text = re.sub('h\\*ll', 'hell ', text)\n text = re.sub('h\\*\\*l', 'hell ', text)\n text = re.sub('cr\\*p', 'crap ', text)\n text = re.sub('d\\*mn', 'damn ', text)\n text = re.sub('stu\\*pid', 'stupid ', text)\n text = re.sub('st\\*pid', 'stupid ', text)\n text = re.sub('n\\*gger', 'nigger ', text)\n text = re.sub('n\\*\\*\\*ga', 'nigger ', text)\n text = re.sub('f\\*ggot', 'faggot ', text)\n text = re.sub('scr\\*w', 'screw ', text)\n text = re.sub('pr\\*ck', 'prick ', text)\n text = re.sub('g\\*d', 'god ', text)\n text = re.sub('s\\*x', 'sex ', text)\n text = re.sub('a\\*s', 'ass ', text)\n text = re.sub('a\\*\\*hole', 'asshole ', text)\n text = re.sub('a\\*\\*\\*ole', 'asshole ', text)\n text = re.sub('a\\*\\*', 'ass ', text) \n text = re.sub(r\"im \", \"i am \", text)\n text = re.sub(r\"what's\", \"what is \", text)\n text = re.sub(r\"\\'s\", \" \", text)\n text = re.sub(r\"\\'ve\", \" have \", text)\n text = re.sub(r\"can't\", \"can not \", text)\n text = re.sub(r\"n't\", \" not \", text)\n text = re.sub(r\"i'm\", \"i am \", text)\n text = re.sub(r\"\\'re\", \" are \", text)\n text = re.sub(r\"\\'d\", \" would \", text)\n text = re.sub(r\"\\'ll\", \" will \", text)\n text = re.sub(r\"\\'scuse\", \" excuse \", text)\n text = re.sub('\\W', ' ', text)\n text = re.sub('\\s+', ' ', text)\n text = text.strip(' ')\n \n return text\n\nremoved_data = ['removed','[removed]',['removed'],'deleted','[deleted]',['deleted']]\n\ndef preprocessing(comment):\n try:\n if type(comment) == str:\n return clean_text(comment)\n elif type(comment) == list:\n global cnt\n cnt+=1\n comments = []\n for text in comment:\n if text in removed_data:\n print('deleted removed data')\n continue\n text = clean_text(text)\n comments.append(text)\n return comments\n else:\n print(type(comment))\n except:\n print(comment)\n\n\n# + id=\"fE7nLFpIFDiD\" outputId=\"0c7014e6-ea21-4fbf-89a5-d44287f23698\"\nimport time\n\ncnt=0\nstart = time.time()\ncontext['cleaned_comment'] = context['cmmt_list'].apply(lambda x: preprocessing(x))\nprint(f'Preprocessing is finished: {time.time()-start:.2f} secs are taken')\nprint(f'Total {cnt} lists are cleaned')\n\n# + id=\"8G-vwUIQFDiE\" outputId=\"1a2c001f-119c-442d-e296-bbd66ecf5ee4\"\norg_len = len(context)\ncontext = context.dropna()\nprint(context.target.value_counts())\nprint(org_len-len(context))\n\n# + id=\"mUKhC2t9FDiF\" outputId=\"1ce5e73a-24d5-4087-b03e-2770be33a754\"\nimport seaborn as sns\n\ncontext['char_length'] = context['cleaned_comment'].apply(lambda x: len(' [SEP] '.join(x).split()))\n\nsns.displot(context['char_length']);\n\n# + id=\"DkeV998GFDiF\" outputId=\"2c5138b3-ff4a-4c78-a8ef-fdafd07ce144\"\ncontext_trim = context[['target','cleaned_comment']]\ncontext_trim.to_csv('context_add.csv', index=False)\nprint(len(context_trim))\n#print(context_trim['target'].value_counts())\n\n# + [markdown] id=\"xqwaGjKvFDiF\"\n# ## Test dataset\n\n# + id=\"EL6bTdEhFDiF\" outputId=\"8fce8c38-43f4-4c51-8b62-b144cef2d02e\"\ngao = gao.rename(columns={'label':'target'})\ntest = gao[['target','cmmt_list']]\n\ntest\n\n# + id=\"enxue40XFDiG\"\nimport re\nimport unicodedata\n\ndef clean_text(text):\n text = text.lower().strip()\n text = ''.join(c for c in unicodedata.normalize('NFD', text) if unicodedata.category(c) != 'Mn')\n text = re.sub(r'[\\r|\\t|\\n]', ' ', text)\n text = re.sub('(http|ftp|https)://(?:[-\\w.]|(?:\\da-f]{2}))+','',text) #url 제거\n text = re.sub('(\\[a-z0-9\\_.+-\\]+@\\[a-z0-9-\\]+.\\[a-z0-9-.\\]+)','',text) #email 제거\n text = re.sub('<[^>]*>','',text) #html tag 제거\n text = re.sub(r\"[^a-z.!?]+\", r\" \", text) #문자+문장부호만 빼고 모두 제거\n text = re.sub(r\"([.!?])\", r\" \\1\", text) #문장부호는 \\1로 대체\n text = re.sub(' the ', ' ', text)\n text = re.sub(' a ', ' ', text)\n text = re.sub(' u ', 'you ', text)\n text = re.sub(' ur ', ' your ', text)\n text = re.sub(' y ', 'why ', text)\n text = re.sub(' ciu ', 'see you ', text)\n text = re.sub(' da ', 'dumb ass ', text)\n text = re.sub(' fug ', 'fuck ugly ', text)\n text = re.sub('gratest', 'greatest ', text)\n text = re.sub('sh\\*t', 'shit ', text)\n text = re.sub('s\\*\\*t', 'shit ', text)\n text = re.sub('f\\*ck', 'fuck ', text)\n text = re.sub(' f ', 'fuck ', text)\n text = re.sub('fu\\*k', 'fuck ', text)\n text = re.sub('f\\*\\*k', 'fuck ', text) \n text = re.sub('f\\*\\*\\*\\*\\*g', 'fuck ', text)\n text = re.sub('p\\*ssy', 'pussy ', text)\n text = re.sub('p\\*\\*\\*y', 'pussy ', text)\n text = re.sub('pu\\*\\*y', 'pussy ', text)\n text = re.sub('p\\*ss', 'piss ', text)\n text = re.sub('b\\*tch', 'bitch ', text)\n text = re.sub('bit\\*h', 'bitch ', text)\n text = re.sub(' btch ', 'bitch ', text)\n text = re.sub(' bch ', 'bitch ', text)\n text = re.sub('h\\*ll', 'hell ', text)\n text = re.sub('h\\*\\*l', 'hell ', text)\n text = re.sub('cr\\*p', 'crap ', text)\n text = re.sub('d\\*mn', 'damn ', text)\n text = re.sub('stu\\*pid', 'stupid ', text)\n text = re.sub('st\\*pid', 'stupid ', text)\n text = re.sub('n\\*gger', 'nigger ', text)\n text = re.sub('n\\*\\*\\*ga', 'nigger ', text)\n text = re.sub('f\\*ggot', 'faggot ', text)\n text = re.sub('scr\\*w', 'screw ', text)\n text = re.sub('pr\\*ck', 'prick ', text)\n text = re.sub('g\\*d', 'god ', text)\n text = re.sub('s\\*x', 'sex ', text)\n text = re.sub('a\\*s', 'ass ', text)\n text = re.sub('a\\*\\*hole', 'asshole ', text)\n text = re.sub('a\\*\\*\\*ole', 'asshole ', text)\n text = re.sub('a\\*\\*', 'ass ', text) \n text = re.sub(r\"im \", \"i am \", text)\n text = re.sub(r\"what's\", \"what is \", text)\n text = re.sub(r\"\\'s\", \" \", text)\n text = re.sub(r\"\\'ve\", \" have \", text)\n text = re.sub(r\"can't\", \"can not \", text)\n text = re.sub(r\"n't\", \" not \", text)\n text = re.sub(r\"i'm\", \"i am \", text)\n text = re.sub(r\"\\'re\", \" are \", text)\n text = re.sub(r\"\\'d\", \" would \", text)\n text = re.sub(r\"\\'ll\", \" will \", text)\n text = re.sub(r\"\\'scuse\", \" excuse \", text)\n text = re.sub('\\W', ' ', text)\n text = re.sub('\\s+', ' ', text)\n text = text.strip(' ')\n \n return text\n\ndef preprocessing(comment):\n cnt=0\n if type(comment) == str:\n return clean_text(comment)\n elif type(comment) == list:\n cnt+=1\n comments = []\n for text in comment:\n if text == 'removed' or text == '[removed]' or text == ['removed']:\n continue\n text = clean_text(text)\n comments.append(text)\n return ' [SEP] '.join(comments)\n else:\n print(type(comment))\n\n\n# + id=\"lxm67OfkFDiG\"\nimport re\nimport unicodedata\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk import pos_tag\n\nwnl = WordNetLemmatizer()\ntarget = ['gay', 'gays', 'homosexual', 'lesbian', 'LGBT', 'moslem', 'muslim', 'jew', 'jews' 'blacks', 'nigga', 'niggas']\n\ndef penn2morphy(penntag):\n \"\"\" Converts Penn Treebank tags to WordNet. \"\"\"\n morphy_tag = {'NN':'n', 'JJ':'a',\n 'VB':'v', 'RB':'r'}\n try:\n return morphy_tag[penntag[:2]]\n except:\n return 'n' \n\ndef clean_text(text):\n text = text.lower().strip()\n text = ''.join(c for c in unicodedata.normalize('NFD', text) if unicodedata.category(c) != 'Mn')\n text = re.sub(r'[\\r|\\t|\\n]', ' ', text)\n text = re.sub('(http|ftp|https)://(?:[-\\w.]|(?:\\da-f]{2}))+','',text) #url 제거\n text = re.sub('(\\[a-z0-9\\_.+-\\]+@\\[a-z0-9-\\]+.\\[a-z0-9-.\\]+)','',text) #email 제거\n text = re.sub('<[^>]*>','',text) #html tag 제거\n text = re.sub(r\"[^a-z.!?]+\", r\" \", text) #문자+문장부호만 빼고 모두 제거\n text = re.sub(r\"([.!?])\", r\" \\1\", text) #문장부호는 \\1로 대체\n text = re.sub(' the ', ' ', text)\n text = re.sub(' a ', ' ', text)\n text = re.sub(' u ', 'you ', text)\n text = re.sub(' ur ', ' your ', text)\n text = re.sub(' y ', 'why ', text)\n text = [w for w in text.split() if len(w)>1] #remove single alphabet in the sentence\n text = [w if w not in target else '[TARGET]' for w in text]\n text = ' '.join([wnl.lemmatize(w, pos=penn2morphy(tag)) for w, tag in pos_tag(text)])\n text = re.sub(' ciu ', 'see you ', text)\n text = re.sub(' da ', 'dumb ass ', text)\n text = re.sub(' fug ', 'fuck ugly ', text)\n text = re.sub('gratest', 'greatest ', text)\n text = re.sub('sh\\*t', 'shit ', text)\n text = re.sub('s\\*\\*t', 'shit ', text)\n text = re.sub('f\\*ck', 'fuck ', text)\n text = re.sub('fu\\*k', 'fuck ', text)\n text = re.sub('f\\*\\*k', 'fuck ', text) \n text = re.sub('f\\*\\*\\*\\*\\*g', 'fuck ', text)\n text = re.sub('p\\*ssy', 'pussy ', text)\n text = re.sub('p\\*\\*\\*y', 'pussy ', text)\n text = re.sub('pu\\*\\*y', 'pussy ', text)\n text = re.sub('p\\*ss', 'piss ', text)\n text = re.sub('b\\*tch', 'bitch ', text)\n text = re.sub('bit\\*h', 'bitch ', text)\n text = re.sub(' btch ', 'bitch ', text)\n text = re.sub(' bch ', 'bitch ', text)\n text = re.sub('h\\*ll', 'hell ', text)\n text = re.sub('h\\*\\*l', 'hell ', text)\n text = re.sub('cr\\*p', 'crap ', text)\n text = re.sub('d\\*mn', 'damn ', text)\n text = re.sub('stu\\*pid', 'stupid ', text)\n text = re.sub('st\\*pid', 'stupid ', text)\n text = re.sub('n\\*gger', 'nigger ', text)\n text = re.sub('n\\*\\*\\*ga', 'nigger ', text)\n text = re.sub('f\\*ggot', 'faggot ', text)\n text = re.sub('scr\\*w', 'screw ', text)\n text = re.sub('pr\\*ck', 'prick ', text)\n text = re.sub('g\\*d', 'god ', text)\n text = re.sub('s\\*x', 'sex ', text)\n text = re.sub('a\\*s', 'ass ', text)\n text = re.sub('a\\*\\*hole', 'asshole ', text)\n text = re.sub('a\\*\\*\\*ole', 'asshole ', text)\n text = re.sub('a\\*\\*', 'ass ', text) \n text = re.sub(r\"im \", \"i am \", text)\n text = re.sub(r\"what's\", \"what is \", text)\n text = re.sub(r\"\\'s\", \" \", text)\n text = re.sub(r\"\\'ve\", \" have \", text)\n text = re.sub(r\"can't\", \"can not \", text)\n text = re.sub(r\"n't\", \" not \", text)\n text = re.sub(r\"i'm\", \"i am \", text)\n text = re.sub(r\"\\'re\", \" are \", text)\n text = re.sub(r\"\\'d\", \" would \", text)\n text = re.sub(r\"\\'ll\", \" will \", text)\n text = re.sub(r\"\\'scuse\", \" excuse \", text)\n text = re.sub('\\W', ' ', text)\n text = re.sub('\\s+', ' ', text)\n text = text.strip(' ')\n \n return text\n\ndef preprocessing(comment):\n if type(comment) == str:\n return clean_text(comment)\n elif type(comment) == list:\n comments = []\n for text in comment:\n if text == 'removed' or text == '[removed]' or text == ['removed']:\n continue\n text = clean_text(text)\n comments.append(text)\n return ' [SEP] '.join(comments)\n else:\n print(type(comment))\n\n\n# + id=\"qIvnnxKjFDiG\" outputId=\"48ffbd00-d5b1-4e36-8223-ad47e4b47ae2\"\nimport time\n\nstart = time.time()\ntest['cleaned_comment'] = test['cmmt_list'].apply(lambda x: preprocessing(x))\nprint(f'Preprocessing is finished: {time.time()-start:.2f} secs are taken')\n\n# + id=\"jdQQMKQKFDiI\" outputId=\"8531bb3e-3a38-4958-99aa-f1b73353dce0\"\norg_len = len(test)\ntest = test[(test.cleaned_comment != '')]\nprint(f'Total {org_len-len(test)} of datas are removed')\n\n# + id=\"0dMag03bFDiJ\" outputId=\"0f6dbee3-3f5a-42a4-e1f0-6c06f3f83a0f\"\ntest['char_length'] = test['cleaned_comment'].apply(lambda x: len(str(x)))\ntest_trim = test[(test.char_length <= 512)]\ntest_trim = test_trim[['target','cleaned_comment']]\n\ntest_trim.to_csv('test_ver2.csv', index=False)\nprint(len(test_trim))\nprint(test_trim['target'].value_counts())\n","repo_name":"Gyeong-Hyeon/TOXIC_SPEECH_DETECTION","sub_path":"collecting_preprocessing_data.ipynb","file_name":"collecting_preprocessing_data.ipynb","file_ext":"py","file_size_in_byte":53426,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"21"} +{"seq_id":"36349768731","text":"import re\n\nmatch = re.search(r'home','I am at home and home1')\nmatch.group()\n\n\ndef find(pat,text):\n match = re.search(pat,text)\n if (match.group()):print ('Matched %s in Text: %s'%(match.group(),text))\n else:print ('Not matched') \n\n\nfind(r'test','I have test today')\n\nfind(r't..t','I have test today')\n\n\ndef found(pat,text):\n matchy = re.search(pat,text)\n if matchy:\n print('Found')\n else:\n print('Not Found')\n\n\nfound(r'devops','trying to learn devops')\n\n# +\npatterns = [ 'this', 'that']\ntext = 'I have this and that also'\n\nfor pattern in patterns:\n print('Checking for %s in %s'%(pattern,text))\n if re.search(pattern,text):\n print ('Found')\n else:\n print ('Not FOund')\n# -\n\npattern1 = 'devops'\ntext = 'we have started devops training form today'\nmatch = re.search(pattern1,text)\ns = match.start()\ne = match.end()\nprint ('The %s is found at %s form:%d till %d:(\"%s\")'%(match.re.pattern,match.string,s,e,match.string[s:e]))\n\nmatch.string\n\n# +\nimport re\ntext = 'ababababbabbabbabbbabba'\npattern = r'ab'\n\nmat = re.findall(pattern,text)\nmat\n\nfor match in re.findall(pattern,text):\n #print ('%s is found at %d:%d'%(match,match.start,match.end))\n print ('match:%s'%match)\n\n# -\n\nmat\n\n# +\ntext = 'abababbababbbbabbabbaaa'\npattern = r'ab'\n\noccur = len(re.findall(pattern,text))\ne = 0\nwhile(occur>0):\n match = re.search(pattern,text[e:])\n s = match.start()\n e = match.end()\n print ('Found %s start:%d and end:%d'%(match.re.pattern,s+e,e+e))\n occur -= 1\n\n# +\npattern = r'an+'\ntext = 'annnaaaaaaaannannnnajhjnnannnannn'\n\nfor match in re.finditer(pattern,text):\n s = match.start()\n e = match.end()\n print ('Found %s from:%d till %d'%(text[s:e],s,e))\n\n# +\ntext = 'anannnannnaaaaaaannnannaananan'\npattern = r'an+'\n\nfor match in re.finditer(pattern,text):\n s = match.start()\n e = match.end()\n print ('Found %s from : %d:%d as text:%s'%(match.re.pattern,s,e,text[s:e]))\n\n# +\ntext = 'krishnadevopskrishnadevopskrishnadevopskrishnadevopskrishnadevops'\npattern = r'devops'\n\ni = 0\nfor match in re.finditer(pattern,text):\n s = match.start()\n e = match.end()\n i += 1\n print ('Found %s between:%d:%d matching %s'%(text[s:e],s,e,match.re.pattern))\nprint ('Found string %d times:'%i)\n# -\n\nlen(re.findall(pattern,text))\n\n# +\npattern = ['term1','term2']\ntext = 'I this term1 I need to score 70 to get into next term'\n\nfor pattern in pattern:\n print ('Looking for string %s in \"%s\"'%(pattern,text))\n if re.search(pattern,text):\n print ('Found string:%s in \"%s\"'%(pattern,text))\n else:\n print ('String %s not found in \"%s\"'%(pattern,text))\n\n# +\npattern = 'text'\ntext = 'Text books has some text'\n\nmatch = re.search(pattern,text)\nmatch\ntype(match)\n# -\n\nmatch.re.pattern\n\nmatch.string\n\nstring = 'best effort for best result'\npattern = r'best'\nmatch = re.search(pattern,string)\nmatch.group()\nmatch.start()\nmatch.end()\nmatch.re.pattern\nmatch.re.pattern.capitalize()\nmatch.string\nmatch.string.capitalize()\n\nstring = 'best effort for best result'\npattern = r'best'\nmatch = re.findall(pattern,string)\nmatch\n\n# +\nstring = 'best effort for best result'\npattern = r'best'\n\nfor match in re.finditer(pattern,string):\n s = match.start()\n e = match.end()\n print (s,e)\n# -\n\npattern = ['a','b','c']\nfor i in pattern:\n print ('%r'%i)\n\ntext = 'sumanteam@gmail.com'\nmatch = re.split('@',text)\nmatch\n\n\ndef multi_find(patterns,phrase):\n for pattern1 in patterns:\n print ('Searching for %r in %s'%(pattern1,phrase))\n print (re.findall(pattern1,phrase))\n \n\n\nphrase = 'sd...sdddd.s....sddddds.d...sdsdsdsd.....sssssddddddd'\npattern = ['sd.','sd+','sd*','sd?','sd{3}','sd{2,4}']\nmulti_find(pattern,phrase)\n\nl1 = list(range(1,10))\n\nl1\n\nimport re\ntext = 'I am a school going school kid'\nmatch = re.search(r'school',text)\nmatch.group(0)\n\n\ndef matching(pattern,text):\n for pattern in pattern:\n print ('Searching for %r in %s'%(pattern,text))\n print (re.findall(pattern,text))\n \n\n\npattern = ['ad+','ad*','ad?','ad{2}','ad{2,3}']\ntext = 'adddd...ddd.a.a.a.aaaaaaadddddd...addd.a.d.a.d.adadad..adddd....ad'\nmatching(pattern,text)\n\ntext = 'sumansanvithsumansanvithsumansanvithsumansanvithsumansanvithsumansanvithsumansanvithsumansanvith'\npattern = r'suman'\ncount = 0\nfor i in re.finditer(pattern,text):\n count += 1\n s = i.start()\n e = i.end()\n print ('String %s is matched %d time between %d:%d'%(i.re.pattern,count,s,e))\nprint ('%r is found:%d times'%(pattern,count)) \n\n\ndef palindrome(x):\n y = []\n for i in x:\n if (i == i[::-1]):\n y.append(i)\n return y \n \n\n\nop = palindrome(['liril','rinir','margo','biscuit'])\n\nop\n\nl1 = [1,2,3,4,45,55,65]\n\nl1[len(l1)-1]\n\n#Reglular Expression\nimport re\npattern = ['ad+','ad*','ad?','ad{2}','ad{2,3}']\nphrase = 'adadaddddd......ada.d...adddd..adad...aaadddd.....adadada...adddddd..ada.d...adadddd.adddd'\nfor match in pattern:\n print ('Searching for %r in: %s'%(match,phrase))\n print (re.findall(match,phrase))\n\npatten = 'morning'\ntext = 'very good morning'\nmatch = re.search(patten,text)\nmatch.group()\n\nmatch.re.pattern.capitalize()\n\nmatch.string.capitalize()\n\na = 'good morning'\nre.sub(r'morning','evening',a)\n\ntext = ' 1. apple'\n\nmatch = re.search(r'\\s?\\d+\\.',text)\nmatch\n\n\nclass pet:\n Number_of_legs = 0\n def legs(self):\n print ('I have %d legs'%self.Number_of_legs)\n \n\n\ndough = pet()\n\ndough.legs()\n\ndough.Number_of_legs = 10\n\ntommy = pet()\n\ntommy.Number_of_legs\n\ntommy.legs()\n\n\nclass pet_class():\n no_of_legs = 0\n def sleep(self):\n print ('ZZZZZZ')\n def display_legs(self):\n print ('I have %d legs'%self.no_of_legs)\n\n\npuppy = pet_class()\n\npuppy.no_of_legs = 4\n\npuppy.display_legs()\n\ntommy = pet_class()\n\ntommy.no_of_legs = 5\n\ntommy.display_legs()\n\npuppy.sleep()\n\ntommy.sleep()\n\n\nclass pet1():\n numberoflegs = 0\n def count(suman):\n print ('I have %s legs'%suman.numberoflegs)\n\n\ntommy = pet1()\n\ntommy.numberoflegs = 4\n\ntommy.count()\n\n\nclass pet3():\n def __init__(self,species,name):\n self.species = species\n self.name = name\n \n def getName(self):\n return self.name\n \n def getSpecies(self):\n return self.species\n \n def __str__(self):\n return '%s is a %s'%(self.name,self.species)\n \n\n\npittie = pet3('parrot','polly')\n\npittie.getName()\n\npittie.getSpecies()\n\npittie\n\nprint(pittie)\n\n\nclass amitab():\n superstar = 'YES'\n money = 'billions'\nclass abhisekh(amitab):\n superstar = 'no'\n money = 'million'\n\n\naradya = abhisekh()\n\naradya.money\n\naradya.superstar\n\ni = 0\nwhile (i <= 4):\n print (i)\n i += 1\nprint ('Done') \n\n# +\nfh = open('new_file.txt','w')\nprint(\"ENter text ('@' to end the text)\")\n\nwhile(str1 != '@'):\n str1 = input()\n if (str1 != '@'):\n fh.write(str1 + \"/n\")\nfh.close()\n\n# -\n\nfh1 = open('new_file',\"r\")\n#fh1.seek(5,0)\nstr1 = fh1.read().splitlines()\nprint (str1)\nfh1.close()\n\nfh.close()\n\nfh1.close()\n\n\n","repo_name":"sumanes4u/Anaconda-Projects","sub_path":"Untitled45.ipynb","file_name":"Untitled45.ipynb","file_ext":"py","file_size_in_byte":6998,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"21"} +{"seq_id":"6425382812","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\npreprocessed_data = np.load('fulldata.npz',allow_pickle=True)\ntimes = preprocessed_data[\"times\"]\nfluxes = preprocessed_data[\"fluxes\"]\nflux_errs = preprocessed_data[\"flux_errs\"]\nfilters = preprocessed_data[\"filters\"]\nclasses = preprocessed_data[\"ids\"]\n\ntimes\n\nfluxes\n\nfilters\n\nclasses\n\nprint(len(times))\nprint(len(fluxes))\nprint(len(filters))\nprint(len(classes))\n\nvalue_counts = np.unique(classes, return_counts=True)\nvalue_counts\n\nfor c, count in zip(*value_counts):\n print(\"{}: {}\".format(int(c), int(count)))\n\n# +\nt_lens = []\nfor e_times in times:\n t_lens.append(len(e_times))\n\nt_lens\n# -\n\nprint(min(t_lens))\nprint(max(t_lens))\n\nplt.hist(t_lens, bins=30)\n\nlen(np.where(np.array(t_lens)>=10)[0])\n\n# +\ntoKeep = np.where(np.array(t_lens)>=10)[0]\n\ntimes = times[toKeep]\nfluxes = fluxes[toKeep]\nflux_errs = flux_errs[toKeep]\nfilters = filters[toKeep]\nclasses = classes[toKeep]\n# -\n\nnp.savez(\"fulldata_longcurves.npz\", times=times, fluxes=fluxes, flux_errs=flux_errs, filters=filters, ids=classes)\n\n\n","repo_name":"zaneddennis/astronomical-anomalies","sub_path":"notebooks/FullDataExploration.ipynb","file_name":"FullDataExploration.ipynb","file_ext":"py","file_size_in_byte":1054,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"21"} +{"seq_id":"70724687733","text":"# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# \"Open\n\n# + id=\"y_rfR8uDX_re\"\nimport pandas as pd\nfrom sklearn.datasets import load_iris\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.tree import export_graphviz\n\n# read file iris.csv\niris = pd.read_csv('/content/drive/My Drive/Dataset Example/Iris.csv')\niris.head()\n\n# menghilangkan kolom/ atribut yang tidak dipakai\niris.drop('Id', axis=1,inplace=True)\n\n# memisahkan atribut dan label\nX = iris [['SepalLengthCm', 'SepalWidthCm', 'PetalLengthCm', 'PetalWidthCm']]\ny = iris['Species']\n\n# membuat model DecisionTree\ntree_model = DecisionTreeClassifier()\n\n# train model thdp data\ntree_model.fit(X, y)\n\n# prediksi model (SL, SW, PL, PW)\ntree_model.predict([[6.2, 3.4, 5.4, 2.3]])\n\n# membuat visualisasi\nexport_graphviz(\n tree_model,\n out_file = \"iris_tree_graph.dot\",\n feature_names = ['SepalLengthCm', 'SepalWidthCm', 'PetalLengthCm', 'PetalWidthCm'],\n class_names = ['Iris-setosa', 'Iris-versicolor', 'Iris-virginica'],\n rounded = True,\n filled = True\n)\n","repo_name":"mrezap/python_learn","sub_path":"Dicoding_Lesson_DecisionTree.ipynb","file_name":"Dicoding_Lesson_DecisionTree.ipynb","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"21"} +{"seq_id":"70927727093","text":"# ### Import Dependencies\n\nimport os\nimport pandas as pd\nfrom sqlalchemy import create_engine\nimport psycopg2\nfrom HiddenConfig import password\n\n# +\n## establishing the connection with database. This checks whether or not the database exists before creation. If it is,\n## it will tell you. Then move onto the next cell\n## Comment out on deployment\n\n# conn = None\n# try:\n# conn = psycopg2.connect(\n# database=\"postgres\", user='postgres', password=password, host='127.0.0.1', port= '5432'\n# )\n\n# except:\n# print('Database not connected.')\n \n# if conn is not None:\n# conn.autocommit = True\n\n# #Creating a cursor object\n# cursor = conn.cursor()\n\n# cursor.execute(\"SELECT datname FROM pg_database;\")\n \n# list_database = cursor.fetchall()\n# database_name = 'climate_db'\n \n# if (database_name,) in list_database:\n# print(f\"'{database_name}' Database already exists\")\n# else:\n# #Preparing query to create a database\n# sql = '''CREATE database climate_db''';\n\n# #Creating a database\n# cursor.execute(sql)\n# print(\"Database created successfully!\")\n\n# #Closing the connection\n# conn.close()\n# -\n\nconn\n\n############## For deployment\n# rds_connection_string='DELETED'\n# rds_connection_string=f'postgresql://zbsameringjozu:{password}@ec2-54-147-126-173.compute-1.amazonaws.com:5432/dqmomgsgfgere'\nengine = create_engine(rds_connection_string)\n\n## Connect to local database\nrds_connection_string = f\"postgres:{password}@localhost:5432/climate_db\"\nengine = create_engine(f'postgresql://{rds_connection_string}')\n\n## Check to see if there are any tables already in the database\nengine.table_names()\n\n## load csvs\nregion_temp_data = os.path.join(os.getcwd(), \"Resources\", \"temp_region_mean.csv\")\nair_pollution_data = os.path.join(os.getcwd(), \"Resources\", \"PM2.5 Global Air Pollution 2010-2017.csv\")\nco2_data = os.path.join(os.getcwd(), \"Resources\", \"co2_cleaned.csv\")\nsector_co2_data = os.path.join(os.getcwd(), \"Resources\", \"GHG-Emissions-by-sector.csv\")\npollution_deaths_data = os.path.join(os.getcwd(), \"Resources\", \"death-rates-from-air-pollution.csv\")\nco2_year_data = os.path.join(os.getcwd(), \"Resources\", \"co2_by_year.csv\")\n\nregion_temp_df = pd.read_csv(region_temp_data)\nair_pollution_df = pd.read_csv(air_pollution_data)\nco2_df = pd.read_csv(co2_data)\nsector_co2_df = pd.read_csv(sector_co2_data)\npollution_deaths_df = pd.read_csv(pollution_deaths_data)\nco2_year_df = pd.read_csv(co2_year_data)\n\nco2_df = co2_df.rename(columns={'Annual CO₂ emissions (tonnes )' : 'Emissions'})\n\npollution_deaths_df = pollution_deaths_df.rename(columns={'Air pollution (total) (deaths per 100,000)' : 'Air pollution', \n 'Indoor air pollution (deaths per 100,000)' : 'Indoor pollution', \n 'Outdoor particulate matter (deaths per 100,000)' : 'Outdoor pollution', \n 'Outdoor ozone pollution (deaths per 100,000)' : 'Ozone pollution'\n })\n\n# ### Load Tables into PostgreSQL Server\n\nregion_temp_df.to_sql(name='region_temp_table', con=engine, if_exists='replace', index=False)\nair_pollution_df.to_sql(name='air_pollution_table', con=engine, if_exists='replace', index=False)\nco2_df.to_sql(name='co2_table', con=engine, if_exists='replace', index=False)\nsector_co2_df.to_sql(name='sector_co2_table', con=engine, if_exists='replace', index=False)\npollution_deaths_df.to_sql(name='pollution_deaths_table', con=engine, if_exists='replace', index=False)\nco2_year_df.to_sql(name='co2_year_table', con=engine, if_exists='replace', index=False)\n\nengine.execute('select * from region_temp_table').first()\n\nengine.execute('select * from air_pollution_table').first()\n\nengine.execute('select * from co2_table').first()\n\nengine.execute('select * from sector_co2_table').first()\n\nengine.execute('select * from pollution_deaths_table').first()\n\nengine.execute('select * from co2_year_table').first()\n","repo_name":"JosiahR89/Pollution_Project","sub_path":"init_database.ipynb","file_name":"init_database.ipynb","file_ext":"py","file_size_in_byte":4011,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"21"} +{"seq_id":"1445719363","text":"# +\n# load the necessary packages\nimport numpy as np\nfrom scipy.integrate import odeint\nimport matplotlib.pyplot as plt\n\n# define the function that returns dz/dt\ndef myModel(y, t):\n #\n # parameters\n mu = 0.1\n #\n # get the individual variables - for readability\n y1 = y[0]\n y2 = y[1]\n #\n # individual derivatives\n dy1dt = mu * ( y1 - np.power(y1,3)/3 - y2 )\n dy2dt = y1 / mu\n #\n return [ dy1dt, dy2dt ]\n\n# define the initial condition\ny0 = [ 2, 2 ]\n\n# define the time points where the solution is computed\nn = 100\ntmax = 20\nt = np.linspace(0, tmax, n)\n\n# solve the ODE\ny = odeint(myModel, y0, t)\n\n# get the individual variables\ny1 = y[:,0]\ny2 = y[:,1]\n\n# plot the time evolution\nplt.subplot(1,2,1)\nplt.plot(t, y1, label='y_1', linewidth=1)\nplt.plot(t, y2, label='y_2', linewidth=1)\nplt.grid()\nplt.legend(loc = 'upper right')\nplt.xlabel('time evolution')\n\n# plot the phase portrait\nplt.subplot(1,2,2)\nplt.plot(y1, y2, linewidth=1)\nplt.grid()\nplt.xlabel('y_1')\nplt.ylabel('y_2')\nplt.title('phase portrait')\n\nplt.show()\n\n\n","repo_name":"damianovar/TTK4225-2020","sub_path":"Jupyter/Van-der-Pol-introduction.ipynb","file_name":"Van-der-Pol-introduction.ipynb","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"20"} +{"seq_id":"27149514112","text":"# ## 5.1 20 뉴스그룹 데이터 준비 및 특성 추출\n# ### 5.1.1 데이터셋 확인 및 분리\n\n# +\nfrom sklearn.datasets import fetch_20newsgroups\n\n# 20개의 토픽 중 선택하고자 하는 토픽을 리스트로 생성\ncategories = ['alt.atheism', 'talk.religion.misc', 'comp.graphics', 'sci.space']\n\n# 학습 데이터셋을 가져옴\nnewsgroups_train = fetch_20newsgroups(subset='train',\n remove=('headers', 'footers', 'quotes'),\n categories=categories)\n\n# 평가 데이터셋을 가져옴\nnewsgroups_test = fetch_20newsgroups(subset='test',\n remove=('headers', 'footers', 'quotes'),\n categories=categories)\n\nprint('#Train set size : {}'.format(len(newsgroups_train.data)))\nprint('#Test set size : {}'.format(len(newsgroups_test.data)))\nprint('#Selected categories : {}'.format(newsgroups_train.target_names))\nprint('Train labels : {}'.format(set(newsgroups_train.target)))\n# -\n\nprint('#Train set text samples :', newsgroups_train.data[0])\nprint('#Train set label samples :', newsgroups_train.target[0])\nprint('#Test set text samples :', newsgroups_test.data[0])\nprint('#Test set label samples :', newsgroups_test.target[0])\n\n# ### 5.1.2 카운트 기반 특성 추출\n\n# +\nX_train = newsgroups_train.data\ny_train = newsgroups_train.target\n\nX_test = newsgroups_test.data\ny_test = newsgroups_test.target\n\nfrom sklearn.feature_extraction.text import CountVectorizer\n\ncv = CountVectorizer(max_features=2000, \n min_df=5, # 최소 이 개수만큼의 문서에 나타나야 한다.\n max_df=0.5) # 문서의 50%를 초과해 나타나는 단어들은 제외\n\nX_train_cv = cv.fit_transform(X_train) # train set을 변환\nprint('Train set dimension:', X_train_cv.shape) \n\nX_test_cv = cv.transform(X_test) # test set을 변환\nprint('Test set dimension:', X_test_cv.shape)\n# -\n\nfor word, count in zip(cv.get_feature_names_out()[:100], X_train_cv[0].toarray()[0, :100]):\n print(word, ':', count, end=', ')\n\n# ## 5.2 머신러닝과 문서 분류 과정에 대한 이해\n# 1. 데이터 정제\n# 2. 데이터 분리\n# 3. 머신러닝 학습\n# 4. 평가\n# 5. 최종모형 도출\n# 6. 예측\n\n# ## 5.3 나이브베이즈 분류기를 이용한 문서 분류\n\n# +\nfrom sklearn.naive_bayes import MultinomialNB\n\n# 분류기 선언\nNB_clf = MultinomialNB()\n\n# train set을 이용해 분류기 학습\nNB_clf.fit(X_train_cv, y_train)\n\n# train set에 대한 예측 정확도를 확인\nprint('Train set score : {:.3f}'.format(NB_clf.score(X_train_cv, y_train)))\n\n# test set에 대한 예측 정확도를 확인\nprint('Test set score : {:.3f}'.format(NB_clf.score(X_test_cv, y_test)))\n\n# +\nprint('#First document and label in test data:', X_test[0], y_test[0])\nprint('#Second document and label in test data:', X_test[1], y_test[1])\n\npred = NB_clf.predict(X_test_cv[:2])\nprint('#Predicted labels:', pred)\nprint('#Predicted categories:', newsgroups_train.target_names[pred[0]], newsgroups_train.target_names[pred[1]])\n\n# +\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\n#CountVectorizer와 동일한 인수를 사용\ntfidf = TfidfVectorizer(max_features=2000, min_df=5, max_df=0.5) \nX_train_tfidf = tfidf.fit_transform(X_train) # train set을 변환\nX_test_tfidf = tfidf.transform(X_test) # test set을 변환\n\nNB_clf.fit(X_train_tfidf, y_train) #tfidf train set을 이용하여 분류기(classifier)를 새로 학습\nprint('Train set score: {:.3f}'.format(NB_clf.score(X_train_tfidf, y_train))) #train set에 대한 예측정확도를 확인\nprint('Test set score: {:.3f}'.format(NB_clf.score(X_test_tfidf, y_test))) #test set에 대한 예측정확도를 확인\n\n# +\nprint('#First document and label in test data:', X_test[0], y_test[0])\nprint('#Second document and label in test data:', X_test[1], y_test[1])\n\npred2 = NB_clf.predict(X_test_tfidf[:2])\nprint('#Predicted labels:', pred2)\nprint('#Predicted categories:', newsgroups_train.target_names[pred2[0]], newsgroups_train.target_names[pred2[1]])\n\n# +\n# 카테고리별로 계수가 큰 10개 특성들을 추출\nimport numpy as np\n\ndef top10_features(classifier, vectorizer, categories):\n feature_names = np.asarray(vectorizer.get_feature_names_out())\n for i, category in enumerate(categories):\n # 역순으로 정렬하기 위해 계수에 음수를 취해서 정렬 후 앞에서부터 10개의 값을 반환\n top10 = np.argsort(-classifier.feature_log_prob_[i])[:10] # coef_ 사라짐\n # 카테고리와 영향이 큰 특성 10개를 출력\n print(\"%s: %s\" % (category, \", \".join(feature_names[top10])))\n\ntop10_features(NB_clf, tfidf, newsgroups_train.target_names)\n# -\n\n# ## 5.4 로지스틱 회귀분석을 이용한 문서 분류\n\n# +\nfrom sklearn.linear_model import LogisticRegression\n\nLR_clf = LogisticRegression()\nLR_clf.fit(X_train_tfidf, y_train)\n\nprint('Train set score : {:.3f}'.format(LR_clf.score(X_train_tfidf, y_train)))\nprint('Test set score : {:.3f}'.format(LR_clf.score(X_test_tfidf, y_test)))\n# -\n\n# ### 5.4.1 릿지회귀를 이용한 과적합 방지\n\n# +\nfrom sklearn.linear_model import RidgeClassifier\n\nridge_clf = RidgeClassifier()\nridge_clf.fit(X_train_tfidf, y_train)\n\nprint('Train set score : {:.3f}'.format(ridge_clf.score(X_train_tfidf, y_train)))\nprint('Test set score : {:.3f}'.format(ridge_clf.score(X_test_tfidf, y_test)))\n\n# +\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\n\nX_train_ridge, X_val_ridge, y_train_ridge, y_val_ridge = train_test_split(\n X_train_tfidf, y_train, test_size=0.2, random_state=42)\n\nmax_score = 0\nmax_alpha = 0\nfor alpha in np.arange(0.1, 10, 0.1): # alpha를 0.1부터 10까지 0.1씩 증가\n ridge_clf = RidgeClassifier(alpha=alpha) #릿지 분류기 선언\n ridge_clf.fit(X_train_ridge, y_train_ridge) #학습\n score = ridge_clf.score(X_val_ridge, y_val_ridge) #검정 데이터셋에 대해 정확도를 측정\n if score > max_score: #정확도가 이전의 정확도 최대값보다 크면 최대값을 변경한다.\n max_score = score\n max_alpha = alpha\nprint('Max alpha {:.3f} at max validation score {:.3f}'.format(max_alpha, max_score))\n\n# +\nridge_clf = RidgeClassifier(alpha=1.6) #릿지 분류기 선언\nridge_clf.fit(X_train_tfidf, y_train) #학습\n\nprint('Train set score: {:.3f}'.format(ridge_clf.score(X_train_tfidf, y_train)))\nprint('Test set score: {:.3f}'.format(ridge_clf.score(X_test_tfidf, y_test)))\n\n\n# +\ndef top10_features(classifier, vectorizer, categories):\n feature_names = np.asarray(vectorizer.get_feature_names_out())\n for i, category in enumerate(categories):\n # 역순으로 정렬하기 위해 계수에 음수를 취해서 정렬 후 앞에서부터 10개의 값을 반환\n top10 = np.argsort(-classifier.coef_[i])[:10]\n # 카테고리와 영향이 큰 특성 10개를 출력\n print(\"%s: %s\" % (category, \", \".join(feature_names[top10])))\n\ntop10_features(ridge_clf, tfidf, newsgroups_train.target_names)\n# -\n\n# ### 5.4.2 라쏘 회귀를 이용한 특성 선택\n\n# +\nfrom sklearn.linear_model import LogisticRegression\n\nlasso_clf = LogisticRegression(penalty='l1', solver='liblinear', C=1)\nlasso_clf.fit(X_train_tfidf, y_train)\n\nprint('#Train set score : {:.3f}'.format(lasso_clf.score(X_train_tfidf, y_train)))\nprint('#Test set score : {:.3f}'.format(lasso_clf.score(X_test_tfidf, y_test)))\n\n# 계수 중에서 0이 아닌 것들의 개수를 출력\nprint('#Used feature count : {}'.format(np.sum(lasso_clf.coef_ != 0)), 'out of', X_train_tfidf.shape[1])\n\n# -\n\ntop10_features(lasso_clf, tfidf, newsgroups_train.target_names)\n\n# ## 5.5 결정트리 등을 이용한 기타 문서 분류 방법\n\n# +\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier\n\ntree = DecisionTreeClassifier(random_state=7)\nforest = RandomForestClassifier(random_state=7)\ngb = GradientBoostingClassifier(random_state=7)\n\ntree.fit(X_train_tfidf, y_train)\nforest.fit(X_train_tfidf, y_train)\ngb.fit(X_train_tfidf, y_train)\n\nprint('#Decision Tree Train set score : {:3f}'.format(tree.score(X_train_tfidf, y_train)))\nprint('#Decision Tree Test set score : {:.3f}'.format(tree.score(X_test_tfidf, y_test)))\n\nprint('#Random Forest Train set score : {:3f}'.format(forest.score(X_train_tfidf, y_train)))\nprint('#Random Forest Test set score : {:3f}'.format(forest.score(X_test_tfidf, y_test)))\n\nprint('#Gradient Bppsting Train set score : {:3f}'.format(gb.score(X_train_tfidf, y_train)))\nprint('#Gradient Bppsting Test set score : {:3f}'.format(gb.score(X_test_tfidf, y_test)))\n\n# +\nsorted_feature_importance = sorted(zip(tfidf.get_feature_names_out(), gb.feature_importances_), key=lambda x:x[1], reverse=True)\n\nfor feature, value in sorted_feature_importance[:40]:\n print('%s: %.3f' %(feature, value), end=', ')\n# -\n\n# ## 5.6 성능을 높이는 방법\n\n# +\n# 필요한 library들을 import\nfrom nltk.corpus import stopwords\ncachedStopWords = stopwords.words(\"english\")\n\nfrom nltk.tokenize import RegexpTokenizer\nfrom nltk.stem.porter import PorterStemmer\nimport re\n\nRegTok = RegexpTokenizer(\"[\\w']{3,}\") # 정규포현식으로 토크나이저를 정의\nenglish_stops = set(stopwords.words('english')) #영어 불용어를 가져옴\n\ndef tokenizer(text):\n tokens = RegTok.tokenize(text.lower())\n # stopwords 제외\n words = [word for word in tokens if (word not in english_stops) and len(word) > 2]\n # portr stemmer 적용\n features = (list(map(lambda token: PorterStemmer().stem(token),words)))\n return features\n\ntfidf = TfidfVectorizer(tokenizer=tokenizer, max_features=2000, min_df=5, max_df=0.5) # 새로 정의한 토크나이저 사용\nX_train_tfidf = tfidf.fit_transform(X_train) # train set을 변환\nX_test_tfidf = tfidf.transform(X_test) # test set을 변환\n\n#tfidf vector를 이용해서 분류기 학습\nLR_clf = LogisticRegression() #분류기 선언\nLR_clf.fit(X_train_tfidf, y_train) # train data를 이용하여 분류기를 학습\nprint('#Train set score: {:.3f}'.format(LR_clf.score(X_train_tfidf, y_train))) # train data에 대한 예측정확도 \nprint('#Test set score: {:.3f}'.format(LR_clf.score(X_test_tfidf, y_test))) # test data에 대한 예측정확도\n# -\n\nlen(LR_clf.coef_[0])\n\n# +\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\ntfidf = TfidfVectorizer(tokenizer=tokenizer)\n\nX_train_tfidf = tfidf.fit_transform(X_train) \nX_test_tfidf = tfidf.transform(X_test) \n\nridge_clf = RidgeClassifier(alpha=2.4)\nridge_clf.fit(X_train_tfidf, y_train) #학습\n\nNB_clf = MultinomialNB(alpha=0.01) \nNB_clf.fit(X_train_tfidf, y_train) \n\nprint('#Train set dimension:', X_train_tfidf.shape) \nprint('#Test set dimension:', X_test_tfidf.shape)\n\nprint('#Train set score: {:.3f}'.format(ridge_clf.score(X_train_tfidf, y_train)))\nprint('#Test set score: {:.3f}'.format(ridge_clf.score(X_test_tfidf, y_test)))\n\nprint('#Train set score: {:.3f}'.format(NB_clf.score(X_train_tfidf, y_train))) \nprint('#Test set score: {:.3f}'.format(NB_clf.score(X_test_tfidf, y_test)))\n# -\n\n# ## 5.7 카운트 기반의 문제점과 N-gram을 이용한 보완\n# - BOW 방식은 단어들의 순서를 무시, 단어가 사용된 횟수를 기반으로 문서 벡터를 만듦\n# - BOW 방식을 그대로 쓰면서도 단어가 쓰여진 순서를 반영할 수 있는 방법\n\n# +\nfrom nltk.corpus import stopwords\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\ncachedStopWords = stopwords.words('english')\ntfidf = TfidfVectorizer(\n token_pattern=\"[a-zA-Z']{3,}\",\n decode_error='ignore',\n lowercase=True,\n stop_words=stopwords.words('english'),\n max_df=0.5,\n min_df=2\n)\n\nX_train_tfidf = tfidf.fit_transform(X_train)\nX_test_tfidf = tfidf.transform(X_test)\n\nprint(X_train_tfidf.shape)\n\n# +\nfrom sklearn.linear_model import RidgeClassifier\nridge_clf = RidgeClassifier()\nridge_clf.fit(X_train_tfidf, y_train)\n\nprint('Train set score : {:.3f}'.format(ridge_clf.score(X_train_tfidf, y_train)))\nprint('Test set score : {:.3f}'.format(ridge_clf.score(X_test_tfidf, y_test)))\n\n# +\ntfidf = TfidfVectorizer(\n token_pattern=\"[a-zA-Z']{3,}\",\n lowercase=True,\n stop_words=stopwords.words('english'),\n ngram_range=(1,2),\n max_df=0.5,\n min_df=2\n)\n\nX_train_tfidf = tfidf.fit_transform(X_train)\nX_test_tfidf = tfidf.transform(X_test)\n\nprint(X_train_tfidf.shape)\n\n# +\nbigram_features = [ f for f in tfidf.get_feature_names_out() if len(f.split()) > 1 ]\nprint('bi-gram samples : {}'.format(bigram_features[:10]))\n\nridge_clf.fit(X_train_tfidf, y_train)\n\nprint('Train set score : {:.3f}'.format(ridge_clf.score(X_train_tfidf, y_train)))\nprint('Test set score : {:.3f}'.format(ridge_clf.score(X_test_tfidf, y_test)))\n\n# +\ntfidf = TfidfVectorizer(token_pattern= \"[a-zA-Z']{3,}\", \n decode_error ='ignore', \n lowercase=True, \n stop_words = stopwords.words('english'),\n ngram_range=(1, 3),\n max_df=0.5,\n min_df=2)\n\nX_train_tfidf = tfidf.fit_transform(X_train)\nX_test_tfidf = tfidf.transform(X_test)\n\nprint(X_train_tfidf.shape)\n\ntrigram_features = [f for f in tfidf.get_feature_names_out() if len(f.split()) > 2]\nprint('tri-gram samples:', trigram_features[:10])\n\nridge_clf.fit(X_train_tfidf, y_train) #학습\n\nprint('Train set score: {:.3f}'.format(ridge_clf.score(X_train_tfidf, y_train)))\nprint('Test set score: {:.3f}'.format(ridge_clf.score(X_test_tfidf, y_test)))\n# -\n\n# ## 5.8 한국어 문서의 분류\n# ### 5.8.1 다음 영화 리뷰에 대한 영화 제목 예측\n\nimport pandas as pd\ndf = pd.read_csv('./data/daum_movie_review.csv')\ndf.head(5)\n\ndf['title'].value_counts()\n\n# +\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(df['review'], df['title'], random_state=0)\n\nprint('#Train set size : {}'.format(len(X_train)))\nprint('#Test set size : {}'.format(len(X_test)))\n\n# +\nfrom konlpy.tag import Okt\nokt = Okt()\n\nprint(okt.morphs(X_train[1]))\nprint(okt.nouns(X_train[1]))\n\n# +\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.linear_model import LogisticRegression\n\ntfidf = TfidfVectorizer(\n tokenizer=okt.nouns,\n max_features=2000,\n min_df=5,\n max_df=0.5\n)\n\nX_train_tfidf = tfidf.fit_transform(X_train)\nX_test_tfidf = tfidf.transform(X_test)\n\nclf = LogisticRegression(max_iter=1000)\nclf.fit(X_train_tfidf, y_train)\n\nprint('#Train set score : {}'.format(clf.score(X_train_tfidf, y_train)))\nprint('#Test set score : {}'.format(clf.score(X_test_tfidf, y_test)))\n\n# +\nprint(\"실제 영화 제목, 예측한 제목, 리뷰\")\n\nfor content in zip(y_test[:10], clf.predict(X_test_tfidf[:10]), X_test[:10]):\n print(content)\n\n# +\npred_df = pd.DataFrame(columns=[\"실제 영화 제목\", \"예측한 제목\", \"리뷰\"])\nidx = 0\n\nfor i in range(10):\n real_title = y_test[i:i+1]\n pred_title = clf.predict(X_test_tfidf[i:i+1])\n review = X_test[i:i+1]\n \n pred_df.loc[idx] = [real_title, pred_title, review]\n \n idx += 1\n\npred_df\n# -\n\n# ### 5.8.2 성능을 개선하기 위한 노력\n\n# +\n# 명사 대신 모든 형태소를 사용\ntfidf = TfidfVectorizer(tokenizer=okt.morphs, max_features=2000, min_df=5, max_df=0.5)\nX_train_tfidf = tfidf.fit_transform(X_train)\nX_test_tfidf = tfidf.transform(X_test)\n\n# 충분한 학습을 위해 max_iter를 1,000으로 설정, 기본은 100\nclf = LogisticRegression(max_iter=1000)\nclf.fit(X_train_tfidf, y_train)\n\nprint('#Train set score: {:.3f}'.format(clf.score(X_train_tfidf, y_train)))\nprint('#Test set score: {:.3f}'.format(clf.score(X_test_tfidf, y_test)))\n\n\n# +\ndef twit_tokenizer(text): #전체를 다 사용하는 대신, 명사, 동사, 형용사를 사용\n target_tags = ['Noun', 'Verb', 'Adjective']\n result = []\n for word, tag in okt.pos(text, norm=True, stem=True):\n if tag in target_tags:\n result.append(word)\n return result\n\ntfidf = TfidfVectorizer(tokenizer=twit_tokenizer, max_features=2000, min_df=5, max_df=0.5)\nX_train_tfidf = tfidf.fit_transform(X_train)\nX_test_tfidf = tfidf.transform(X_test)\n\nclf = LogisticRegression(max_iter=1000)\nclf.fit(X_train_tfidf, y_train)\n\nprint('#Train set score: {:.3f}'.format(clf.score(X_train_tfidf, y_train)))\nprint('#Test set score: {:.3f}'.format(clf.score(X_test_tfidf, y_test)))\n\n\n# +\n# 모든 형태소를 다 사용하고 품사를 알 수 있도록 하면?\ndef twit_tokenizer2(text):\n result = []\n for word, tag in okt.pos(text, norm=True, stem=True):\n result.append('/'.join([word, tag])) #단어의 품사를 구분할 수 있도록 함\n return result\n\nprint(twit_tokenizer2(X_train[1]))\n\n# +\ntfidf = TfidfVectorizer(tokenizer=twit_tokenizer2, max_features=2000, min_df=5, max_df=0.5)\nX_train_tfidf = tfidf.fit_transform(X_train)\nX_test_tfidf = tfidf.transform(X_test)\n\nclf = LogisticRegression(max_iter=1000) \nclf.fit(X_train_tfidf, y_train)\n\nprint('#Train set score: {:.3f}'.format(clf.score(X_train_tfidf, y_train))) \nprint('#Test set score: {:.3f}'.format(clf.score(X_test_tfidf, y_test)))\n\n\n# +\n# 명사, 형용사, 동사만 선택하고 품사를 붙인 후 로지스틱 회귀분석 실시\n\ndef twit_tokenizer3(text):\n target_tags = ['Noun', 'Verb', 'Adjective']\n result = []\n for word, tag in okt.pos(text, norm=True, stem=True):\n if tag in target_tags:\n result.append('/'.join([word, tag]))\n return result\n\ntfidf = TfidfVectorizer(tokenizer=twit_tokenizer3, max_features=2000, min_df=5, max_df=0.5)\nX_train_tfidf = tfidf.fit_transform(X_train)\nX_test_tfidf = tfidf.transform(X_test)\n\nclf = LogisticRegression(max_iter=1000) \nclf.fit(X_train_tfidf, y_train)\n\nprint('#Train set score: {:.3f}'.format(clf.score(X_train_tfidf, y_train))) \nprint('#Test set score: {:.3f}'.format(clf.score(X_test_tfidf, y_test)))\n\n# +\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\n\nX_train_ridge, X_val_ridge, y_train_ridge, y_val_ridge = train_test_split(\n X_train_tfidf, y_train, test_size=0.2, random_state=42)\n\nmax_score = 0\nmax_alpha = 0\nfor alpha in np.arange(0.1, 10, 0.1): # alpha를 0.1부터 10까지 0.1씩 증가\n ridge_clf = RidgeClassifier(alpha=alpha) #릿지 분류기 선언\n ridge_clf.fit(X_train_ridge, y_train_ridge) #학습\n score = ridge_clf.score(X_val_ridge, y_val_ridge) #검정 데이터셋에 대해 정확도를 측정\n if score > max_score: #정확도가 이전의 정확도 최대값보다 크면 최대값을 변경한다.\n max_score = score\n max_alpha = alpha\nprint('#Max alpha {:.3f} at max validation score {:.3f}'.format(max_alpha, max_score))\n\n# +\nfrom sklearn.linear_model import RidgeClassifier\n\nridge_clf = RidgeClassifier(alpha=1.6)\nridge_clf.fit(X_train_tfidf, y_train)\n\nprint('#Ridge Train set score: {:.3f}'.format(ridge_clf.score(X_train_tfidf, y_train)))\nprint('#Ridge Test set score: {:.3f}'.format(ridge_clf.score(X_test_tfidf, y_test)))\n\nfrom sklearn.linear_model import LogisticRegression\nimport numpy as np\n\nlasso_clf = LogisticRegression(penalty='l1', solver='liblinear', C=0.5)\nlasso_clf.fit(X_train_tfidf, y_train)\n\nprint('#Lasso Train set score: {:.3f}'.format(lasso_clf.score(X_train_tfidf, y_train)))\nprint('#Lasso Test set score: {:.3f}'.format(lasso_clf.score(X_test_tfidf, y_test)))\nprint('#Used features count: {}'.format(np.sum(lasso_clf.coef_ != 0)), 'out of', X_train_tfidf.shape[1])\n\n# +\nfrom sklearn.naive_bayes import MultinomialNB\n\nNB_clf = MultinomialNB(alpha=0.1)\nNB_clf.fit(X_train_tfidf, y_train)\n\nprint('Train set score: {:.3f}'.format(NB_clf.score(X_train_tfidf, y_train)))\nprint('Test set score: {:.3f}'.format(NB_clf.score(X_test_tfidf, y_test)))\n# -\n\n\n","repo_name":"yoonjong8739/textmining_python","sub_path":"05. BOW 기반의 문서 분류.ipynb","file_name":"05. BOW 기반의 문서 분류.ipynb","file_ext":"py","file_size_in_byte":19782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"20"} +{"seq_id":"6868046429","text":"# +\n#Look at sensor format and measurement types\n#Create Spark DStream of weather data\n#Read measurements and create sliding window of data\n#Define function to display maximum and minimum values\n#Start and stop stream processing\n# -\n\n# Parse a line of weather station data, returning the average wind direction measurement \nimport re\ndef parse(line):\n match = re.search(\"Dm=(\\d+)\", line)\n if match:\n val = match.group(1)\n return [int(val)]\n return []\n\n\n# +\n#Import and create streaming context; create DStream of weather data\n# -\n\nfrom pyspark.streaming import StreamingContext\nssc = StreamingContext(sc,1)\n\nlines = ssc.socketTextStream(\"rtd.hpwren.ucsd.edu\", 12028)\n\n# +\n#Read measurement and create sliding window of data\n# -\n\nvals = lines.flatMap(parse)\n\nwindow = vals.window(10, 5)\n\n\n# +\n#Define and call analysis function\n# -\n\ndef stats(rdd):\n print(rdd.collect())\n if rdd.count() > 0:\n print(\"max = {}, min = {}\".format(rdd.max(), rdd.min()))\n\n\nwindow.foreachRDD(lambda rdd: stats(rdd))\n\n# +\n#Start and stop the stream processing\n# -\n\nssc.start()\n\nssc.stop()\n\n\n","repo_name":"scours/big-data-coursera","sub_path":"course-3-big-data-integration-and-processing/week_5_data_processing_in_Spark/SparkStreaming.ipynb","file_name":"SparkStreaming.ipynb","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"20"} +{"seq_id":"28519240509","text":"# + [markdown] id=\"wrqDIWfTh9Jq\"\n# **gerekli kutuphanelerin eklenmesi**\n#\n# ---\n#\n#\n\n# + id=\"ycjue3-fEO5E\"\nimport numpy as np\nimport pandas as pd \nimport matplotlib.pyplot as plt\nimport random\nimport os\n\nfrom keras.preprocessing.image import ImageDataGenerator, load_img\nfrom sklearn.model_selection import train_test_split\n\nimport pickle\nimport cv2 as cv\nimport tensorflow as tf\nfrom google.colab.patches import cv2_imshow\n\n# + [markdown] id=\"t5VOF28RiA34\"\n# verilerin drivedan cekilmesi\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"lw0eB-kTT8_A\" outputId=\"dd55ac0f-6cfc-43e1-ff75-1e0776bfd4cf\"\nfrom google.colab import drive\ndrive.mount('/content/drive')\n\n# + id=\"uR0ifHeqUAy3\"\n# once tek bir resim uzerinde denemeler yapalim\npath_to_image = \"/content/drive/MyDrive/transfer_learning/catsanddogs/PetImages/Dog/16.jpg\"\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 398} id=\"9tCq_kN3UJi_\" outputId=\"700d1ef0-e70f-4405-cf5e-60baa19f15d1\"\nimage = cv.imread(path_to_image, cv.IMREAD_COLOR)\ncv2_imshow(image)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"cRSO-ayrVGiQ\" outputId=\"2c9b2835-5a1f-47f0-861a-c756a6ecdf47\"\ntype(image)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"-xngeB3mVHlK\" outputId=\"b04c6658-8a07-45f7-ce15-a3c433b3946b\"\nimage\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"aYI44kjDVJ68\" outputId=\"d0c98e21-edc1-443b-d3a9-f0ce514aed41\"\nimage.shape\n\n# + [markdown] id=\"ACFajGZkVMqu\"\n# **Resizing and Normalization**\n#\n# ---\n#\n#\n\n# + id=\"OBucCZ8hVO7A\"\nresized = cv.resize(image, (128,128))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"p5N62TmxWTwQ\" outputId=\"1a012893-6dfd-42b4-ba96-468d83721be7\"\ntype(resized)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"oSXv19KqWUL9\" outputId=\"353799b0-2c95-4a0f-a58d-3750d209dedb\"\nresized\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 145} id=\"uPuQPN1pWXwf\" outputId=\"b3eba04a-2fde-4d07-d6a9-6547f9f9a4e7\"\ncv2_imshow(resized)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"NGti4kTAWgX3\" outputId=\"4c3e7b6f-6213-4c5c-eda3-d27b7b315e30\"\nresized.shape\n\n# + [markdown] id=\"zLi1K0GcWjmH\"\n# **On Isleme**\n#\n# ---\n#\n#\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"llJFwawfWkoo\" outputId=\"3055c613-0c0c-4c84-88ef-c7ed5f96e435\"\npath_to_dataset = \"/content/drive/MyDrive/transfer_learning/catsanddogs/PetImages\"\n\n# dataseti bu sekilde 2 kategoriye ayiralim: kediler ve kopekler\ncategories = [\"Cat\", \"Dog\"]\n\n# verileri normalize edecegimiz fonksiyonu yazalim.\ndef normalize(x):\n x = (x-x.min())/(x.max()-x.min())\n return x\n\nimages = []\nerrors_file = open(\"errors.txt\", \"a\")\nerror = 0\nnumber = 0\n\nfor category in categories:\n img_per_category = 0\n idx = categories.index(category)\n for image in os.listdir(f\"{path_to_dataset}/{category}\"):\n if img_per_category == 1000:\n break\n path_to_image = f\"{path_to_dataset}/{category}/{image}\"\n try:\n img = cv.imread(path_to_image, cv.IMREAD_COLOR)\n img = cv.resize(img, (128,128))\n img = normalize(img)\n images.append([img, idx])\n img_per_category += 1\n\n except Exception as e:\n error += 1\n errors_file.write(f\"{error}) {e}\\n\")\n finally:\n number += 1\n print(f\"\\rCalistirilan: {number} | Hatalar: {error}\", end=\"\")\n\nerrors_file.close()\n\n# + id=\"PDv5dtY0W1GR\"\nwith open(\"images_list.pickle\", \"wb\") as f:\n pickle.dump(images, f)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"8i_jxnkfW13C\" outputId=\"c7ce65ff-7153-4d15-c776-0f1508e64872\"\nimages[0][0].shape\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"EVPu8PqsW5uq\" outputId=\"cef5e4b2-457f-4c71-b2de-e37752f989db\"\nprint(np.array(images)[:,1])\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"KL4swb1YW6MJ\" outputId=\"63f432c0-cf0c-4eee-f04b-6a5df87217c8\"\nfor _ in range(10):\n random.shuffle(images)\n\nnp.array(images)[:,1]\n\n# + id=\"yPW6Ys6fW-XA\"\nX = []\ny = []\nfor image, idx in images:\n X.append(image)\n y.append(idx)\n\n# x_train, y_train, x_val, y_val, x_tres, y_test verileri icin listeler olusturalim.\nX_train = []\ny_train = []\n\nX_val = []\ny_val = []\n\nX_test = []\ny_test = []\n\n# + id=\"tnGncFZvXBn5\"\nX_train = X[:1600]\ny_train = y[:1600]\n\nX_val = X[1600:1800]\ny_val = y[1600:1800]\n\nX_test = X[1800:]\ny_test = y[1800:]\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"_sa3H0p1XGNs\" outputId=\"ec9ed70c-6fc9-45bf-b64e-7915e5ca7ef2\"\nX_train = np.array(X_train)\ny_train = np.array(y_train)\n\nX_val = np.array(X_val)\ny_val = np.array(y_val)\n\nX_test = np.array(X_test)\ny_test = np.array(y_test)\n\n# dataseti ayirarak olusturdugumuz verileri yazdiralim.\nprint(\"x_train: \", len(X_train))\nprint(\"y_train: \", len(y_train))\n\nprint(\"x_val: \", len(X_val))\nprint(\"y_val: \", len(y_val))\n\nprint(\"x_test: \", len(X_test))\nprint(\"y_test: \", len(y_test))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"JIkr0RCBXIAT\" outputId=\"26092cb0-e2cf-4a06-e432-10e5edd6c91c\"\n# x_train, x_val ve x_test verilerinin boyutunu gorelim.\nprint(X_train[0].shape)\nprint(X_val[0].shape)\nprint(X_test[0].shape)\n\n# + id=\"tpFAQ3ukXMtO\"\n# x_train, y_train, x_val, y_val, x_test, y_test verilerini daha sonra kullanabilmek icin kaydedelim.\nwith open(\"X_train.pickle\", \"wb\") as f:\n pickle.dump(X_train, f) \nwith open(\"y_train.pickle\", \"wb\") as f:\n pickle.dump(y_train, f)\n\nwith open(\"X_val.pickle\", \"wb\") as f:\n pickle.dump(X_val, f) \nwith open(\"y_val.pickle\", \"wb\") as f:\n pickle.dump(y_val, f)\n\nwith open(\"X_test.pickle\", \"wb\") as f:\n pickle.dump(X_test, f) \nwith open(\"y_test.pickle\", \"wb\") as f:\n pickle.dump(y_test, f)\n","repo_name":"sudeakinay/AI-Summer-Camp-22-GlobalAIHub","sub_path":"Transfer-Learning-Project/TL_preprocess.ipynb","file_name":"TL_preprocess.ipynb","file_ext":"py","file_size_in_byte":5519,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"20"} +{"seq_id":"74341007409","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport plotly.express as px\n\ndf = pd.read_csv('data/pred.csv')\n\ndf\n\ndf.plot(kind='scatter', x='lon', y='lat',alpha=0.1)\nplt.show()\n\nfig = px.scatter_mapbox(df, lat=\"lat\", lon=\"lon\", \n color_discrete_sequence=[\"green\"], zoom=3, height=300)\nfig.update_layout(mapbox_style=\"open-street-map\")\nfig.update_layout(margin={\"r\":0,\"t\":0,\"l\":0,\"b\":0})\nfig.show()\n\n\n","repo_name":"kmcinturf/South_American_Deforestation-","sub_path":"Notebooks/plot-amazon-Jimenez.ipynb","file_name":"plot-amazon-Jimenez.ipynb","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-jupyter-script","pt":"20"} +{"seq_id":"72665307888","text":"# # Data Problem #30\n\n# This question was asked by: Walmart \n#\n# Given a list of scrambled airplane tickets, each with a starting city and end city, reconstruct the path of the trip so the trip tickets are in order.\n\ninput_cities = [\n ['Chennai', 'Bangalore'], \n ['Bombay', 'Delhi'], \n ['Goa', 'Chennai'], \n ['Delhi', 'Goa'], \n ['Bangalore', 'Beijing']\n]\noutput = [\n ['Bombay', 'Delhi'], \n ['Delhi', 'Goa'], \n ['Goa', 'Chennai'], \n ['Chennai', 'Bangalore'], \n ['Bangalore', 'Beijing'],\n]\n\n# Primeira parte do código ele verifica quais cidades foram marcadas apenas uma vez nos bilhetes, tanto na cidade inicial, quanto na cidade final, marcando assim o primeiro e o último bilhete na lista.\n\n# +\noutput = [[]]*5\ntam = len(input_cities)\ncontagem = 0\n\nfor x in range(tam):\n input_city = input_cities[x][0]\n output_city = input_cities[x][1]\n \n contagem1 = 0\n contagem2 = 0\n contagem3 = 0\n contagem4 = 0\n \n for y in range(tam):\n contagem1 += input_cities[y][0].count(input_city)\n contagem2 += input_cities[y][1].count(input_city)\n contagem3 += input_cities[y][0].count(output_city)\n contagem4 += input_cities[y][1].count(output_city)\n \n contagem_input = contagem1 + contagem2\n contagem_output = contagem3 + contagem4\n \n if contagem_input == 1:\n output[0] = input_cities[x]\n elif contagem_output == 1:\n output[4] = input_cities[x]\n \noutput\n \n \n# -\n\n# Na segunda parte do código, é organizado a ordem dos bilhetes de acordo com as combinações certas de ida e destino para que fique totalmente ordenado.\n\n# +\ny = 0\n\nwhile (y<3):\n for x in range(tam):\n if input_cities[x][0] == output[y][1]:\n output[y+1] = input_cities[x]\n y+=1\noutput \n","repo_name":"ciaciafelipe/DataInterviewQuestions","sub_path":"Data Problem #30.ipynb","file_name":"Data Problem #30.ipynb","file_ext":"py","file_size_in_byte":1811,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"20"} +{"seq_id":"986194827","text":"# # GCN Deep Graph Infomax on CORA\n#\n# This demo demonstrates how to perform unsupervised training of a GCN model using the Deep Graph Infomax algorithm (https://arxiv.org/pdf/1809.10341.pdf) on the CORA dataset. \n#\n# As with all StellarGraph workflows: first we load the dataset, next we create our data generators, and then we train our model. We then take the embeddings created through unsupervised training and predict the node classes using logistic regression.\n\n# +\nfrom stellargraph.mapper import CorruptedGenerator, FullBatchNodeGenerator\nfrom stellargraph import StellarGraph\nfrom stellargraph.layer import GCN, DeepGraphInfomax\n\nfrom stellargraph import datasets\nfrom stellargraph.utils import plot_history\n\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nfrom sklearn import model_selection\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.manifold import TSNE\nfrom IPython.display import display, HTML\n\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.callbacks import EarlyStopping\nimport tensorflow as tf\nfrom tensorflow.keras import Model\n# -\n\ndataset = datasets.Cora()\ndisplay(HTML(dataset.description))\nG, node_subjects = dataset.load()\n\n# ## Data Generators\n# \n# Now we create the data generators using `CorruptedGenerator`. `CorruptedGenerator` returns shuffled node features along with the regular node features and we train our model to discriminate between the two. \n# \n# Note that:\n# \n# - We typically pass all nodes to `generator.flow` because this is an unsupervised task\n# - We don't pass `targets` to `generator.flow` because these are binary labels (true nodes, false nodes) that are created by `CorruptedGenerator`\n\ngenerator = FullBatchNodeGenerator(G, sparse=False)\ncorrupted_generator = CorruptedGenerator(generator)\ngen = corrupted_generator.flow(G.nodes())\n\n# ## Model Creation and Training\n#\n# We create and train our `DeepGraphInfomax` model. Note that the loss used here must always be `tf.nn.sigmoid_cross_entropy_with_logits`.\n\n# +\ngcn = GCN([512], activations=[tf.keras.layers.PReLU()], generator=generator)\n\ninfomax = DeepGraphInfomax(gcn)\nx_in, x_out = infomax.build()\n\nmodel = Model(inputs=x_in, outputs=x_out)\nmodel.compile(loss=tf.nn.sigmoid_cross_entropy_with_logits, optimizer=Adam(lr=1e-3))\n# -\n\nmodel = Model(inputs=model.input, outputs=x_out)\nmodel.compile(loss=tf.nn.sigmoid_cross_entropy_with_logits, optimizer=Adam(lr=1e-3))\n\nes = EarlyStopping(monitor=\"loss\", min_delta=0, patience=20)\nhistory = model.fit(gen, epochs=200, verbose=0, callbacks=[es])\nplot_history(history)\n\n# ## Extracting Embeddings and Logistic Regression\n#\n# We create an embedding model using `DeepGraphInfomax.embedding_model` to obtain the node embeddings. Then we use logistic regression to predict which class the node belongs to.\n#\n# Note that the results here differ from the paper due to different train/test/val splits.\n\nx_emb_in, x_emb_out = infomax.embedding_model(model)\nemb_model = Model(inputs=x_emb_in, outputs=x_emb_out)\n\n# +\ntrain_subjects, test_subjects = model_selection.train_test_split(\n node_subjects, train_size=0.1, test_size=None, stratify=node_subjects\n)\n\ntest_gen = generator.flow(test_subjects.index)\ntrain_gen = generator.flow(train_subjects.index)\n\ntest_embeddings = emb_model.predict(test_gen)\ntrain_embeddings = emb_model.predict(train_gen)\n\nlr = LogisticRegression(multi_class=\"auto\", solver=\"lbfgs\")\nlr.fit(train_embeddings, train_subjects)\n\ny_pred = lr.predict(test_embeddings)\nprint(\"Test classification accuracy:\", (y_pred == test_subjects).mean())\n# -\n\n# ## Visualisation with TSNE\n#\n# Here we visualize the node embeddings with TSNE. As you can see below, the Deep Graph Infomax model produces well separated embeddings using unsupervised training.\n\n# +\nall_embeddings = emb_model.predict(generator.flow(G.nodes()))\n\ny = node_subjects.astype(\"category\")\ntrans = TSNE(n_components=2)\nemb_transformed = pd.DataFrame(trans.fit_transform(all_embeddings), index=G.nodes())\nemb_transformed[\"label\"] = y\n\n# +\nalpha = 0.7\n\nfig, ax = plt.subplots(figsize=(7, 7))\nax.scatter(\n emb_transformed[0],\n emb_transformed[1],\n c=emb_transformed[\"label\"].cat.codes,\n cmap=\"jet\",\n alpha=alpha,\n)\nax.set(aspect=\"equal\", xlabel=\"$X_1$\", ylabel=\"$X_2$\")\nplt.title(\"TSNE visualization of GCN embeddings for cora dataset\")\nplt.show()\n","repo_name":"ameyabhope/stellargraph","sub_path":"demos/node-classification/deep-graph-infomax/gcn-deep-graph-infomax-cora-example.ipynb","file_name":"gcn-deep-graph-infomax-cora-example.ipynb","file_ext":"py","file_size_in_byte":4341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-jupyter-script","pt":"20"} +{"seq_id":"5006889316","text":"# # Analyse des données de la FAO pour une étude de santé publique\n\n# importation des différentes librairies et base de données\n# %matplotlib inline\nimport numpy as np\nimport pandas as pd\npopulation = pd.read_csv(\"csv/fr_population.csv\")\nsousalimentation = pd.read_csv(\"csv/fr_sousalimentation.csv\")\nanimaux = pd.read_csv(\"csv/fr_animaux.csv\")\nvegetaux = pd.read_csv(\"csv/fr_vegetaux.csv\")\ncereales = pd.read_csv(\"csv/fr_céréales.csv\")\n\nimport matplotlib.pyplot as plt\n\n# ### Explorons notre table population\n\npopulation.head(2)\n\n# ### Explorons notre table animaux\n\nanimaux.head(2)\n\n# ### Explorons notre table vegetaux\n\nvegetaux.head(2)\n\n# ### Explorons notre table sousalimentation\n\nsousalimentation.head(2)\n\n# ### Explorons notre table cereales\n\ncereales.head(2)\n\npopulation .shape\n\npopulation.describe()\n\npopulation.columns\n\n\n# +\n#déterminons la clé primaire de nos tables\ndef check_keys(dataset,keys):\n nbr_rows = len(dataset)\n unique_values = len(dataset.groupby(keys).size())\n if nbr_rows == unique_values:\n print(\"{} est une clé primaire de notre table.\".format(keys))\n return True\n else:\n print(\"{} n'est pas une clé primaire de notre table .\" .format(keys))\n return False\n \n \n# -\n\n# clé de la table population\ncheck_keys(population,'Code zone')\n\n# clé de la table animaux\ncheck_keys(animaux,['Code zone','Code Élément','Code Produit'])\n\n# clé de la table vegetaux\ncheck_keys(vegetaux,['Code zone','Code Élément','Code Produit'])\n\n# clé de la table sousalimentation\ncheck_keys(sousalimentation,['Code zone','Code année'])\n\n# clé de la table cereales\ncheck_keys(cereales,['Code zone','Code Produit'])\n\n# ## Question 1: Calculons le nombre total d'humain\n\n# convertissons d'abord la population qui est en milliers d'habitant\npopulation['Valeur']*=1000\n\n# +\n# sommons les valeurs pour avoir la population mondiale\n\npopulation['Valeur'].sum()\n# -\n\n# Critique : d'apès wikipédia la population mondiale en 2013 était de **7 milliards** ce qui ne cadre pas avec notre résultat qui est de 8 milliards qui est trop élevée.\n# vérifions si il existe des redondances dans notre table.\n\n# recherchons les duplications\npopulation.duplicated().value_counts()\n\n# Pas de doublon à priori\n\n# regardons maintenant les pays dont la population est la plus élevée\npopulation.loc[0:,['Code zone','Zone','Valeur']].sort_values(by = 'Valeur',ascending = False).head(4)\n\n# Ici on constate que la chine et la chinecontinentale font tous deux parties de nos données ce qui est problématique\n\n# trouvons tous les pays qui représentent la chine dans notre table\npopulation[population['Zone'].str.startswith('Chine')].head()\n\n# Dans les données statistiques de la FAO nous constatons qu'il y a bel et bien des redondances. La chine y est représenté en même temps que ses subdivisions. on choisi de conserver la chine et de supprimer ses subdivisions\n\n# suppression des subdivisions de la chine de notre table population\nchn = [\"Chine - RAS de Hong-Kong\",\"Chine - RAS de Macao\", \"Chine, continentale\",\"Chine, Taiwan Province de\"]\npopulation.drop(population.loc[population['Zone'].isin(chn)].index, inplace = True)\n\n# vérification de la supression\npopulation[population['Zone'].str.startswith('Chine')].head()\n\n# population mondiale correct\npop_mondiale = population['Valeur'].sum()\nprint('La population mondiale est de :{}'.format(pop_mondiale))\n\n# ## Question 2: Retrouvons les redondances des éléments qui constituent le bilan alimenatire\n# Identifions les redondances, en donnant une réponse sous forme de formule mathématique qui fait intervenir les 11 éléments cités\n#\n\n# Les redondances observées dans nos tables sont traduitent par l'équation suivante:\n# > Disponibilité intérieure = Nourriture + Semences + Pertes + Traitements + Alimentations pour animaux + Autres utilisations(non alimentaires) = production +(Importations - Quantité)+ (variation de stocks)- (Exportations - Quantité)\n\n# Vérifions notre équation en prennant le cas du blé.\n\n# +\n#sélectionnons uniquement le blé produit en France\nvegetaux_France = vegetaux[(vegetaux['Zone']=='France') & (vegetaux['Produit']=='Blé')]\n\ndef valeur_element(element):\n return float(vegetaux_France[vegetaux_France['Élément']== element].Valeur)\n\n\nprint(valeur_element('Disponibilité intérieure')*1000000)\nprint((valeur_element('Production') + valeur_element('Importations - Quantité') + valeur_element('Variation de stock') - valeur_element('Exportations - Quantité'))*1000000)\nprint((valeur_element('Nourriture') + valeur_element('Semences') + valeur_element('Pertes')+ valeur_element('Traitement') + valeur_element('Aliments pour animaux') +valeur_element('Autres utilisations (non alimentaire)'))*1000000)\n# -\n\n# ## Question 3:\n# Calculons (pour chaque pays et chaque produit) la disponibilité alimentaire en kcal puis en kg de protéines.\n\n# Reunissons les données des tables animaux, végétaux, population\n\n# créons la colonne qui spécifiera l'origine des éléments de notre table \nanimaux['Origine'] = 'animal'\nvegetaux['Origine']= 'végétal'\n\n# assemblons les tables animaux et végétaux dans une table commune par le biais d'une concaténation\nanimaux_vegetaux = pd.concat([animaux,vegetaux])\n\n# +\n# transformation par un pivot table\ntable = animaux_vegetaux.pivot_table(index = ['Zone','Code zone','Code Produit','Année','Produit','Origine'], columns = ['Élément'], values = 'Valeur')\ntable.reset_index(inplace=True)\n\n# suppriomons les duplications de pays dans notre table concaténée\ntable.drop(table.loc[table['Zone'].isin(chn)].index, inplace = True)\n\n\n# +\n#convertissons chaque élément en son unité pour homogéniser nos valeurs et ne pas avoir à multiplier par 1000000 chaque fois\n\nlist=['Production','Disponibilité intérieure','Nourriture','Importations - Quantité','Aliments pour animaux','Autres utilisations (non alimentaire)','Exportations - Quantité','Pertes','Semences','Variation de stock']\nfor l in list:\n table[l] *=1000000\ntable.head(2)\n# -\n\n# jointure de notre nouvelle table(animaux+végétaux) et la table population\ntable_jointe= pd.merge(table,population[['Zone','Valeur']] , on = ['Zone'], how = 'inner')\n\n# renomnons la nouvelle colonne intégrée à notre table\ntable_jointe = table_jointe.rename({'Valeur': 'population'}, axis = 1)\n\n# calcul de la disponibilité alimentaire en kcal\ntable_jointe['dispo_alim_kcal']= table_jointe['Disponibilité alimentaire (Kcal/personne/jour)']*365*table_jointe['population']\n\n# calcul de la disponibilité en kg de protéines\ntable_jointe['dispo_alim_kgprot']= (table_jointe['Disponibilité de protéines en quantité (g/personne/jour)']*0.001*365)*table_jointe['population']\n#table_jointe[table_jointe['Zone']=='Inde']['dispo_alim_kgprot'].sum()\n\n# ## Question 4: \n# Trouvons le ratio energie / poids en kcal/kg. sachant que ratio energie/poids = disponibilité alimentaire en kcal/nourriture\n\n# sélectionnons les colonnes qui nous interessent:\ntable_ratio = table_jointe[['Produit','dispo_alim_kcal','dispo_alim_kgprot','Nourriture']].copy()\ntable_ratio.head(2)\n\n#remplacement des 0 par des NaN pour éviter la division par 0\ntable_ratio.replace(0, np.nan, inplace=True)\n\n# +\n#ratio energie poids\ntable_ratio['ratio_kcal']= table_ratio['dispo_alim_kcal']/table_ratio['Nourriture']\n\n\n#calculons le ration energie poids en kg de proteine = dispo_alim_kg de proteine/nourriture\ntable_ratio['ratio_prot']= table_ratio['dispo_alim_kgprot']/table_ratio['Nourriture']\ntable_ratio\n# -\n\n#verification avec le ratio de l'oeuf égale en moyenne à 1470kcal/kg\ntable_ratio_kcal_produit = table_ratio[['Produit','ratio_kcal','ratio_prot']].groupby(['Produit']).mean()\ntable_ratio_kcal_produit.reset_index(inplace = True)\ntable_ratio_kcal_produit[table_ratio_kcal_produit['Produit'] =='Oeufs']\n\n#vérifions le ratio proteique de l'avoine \ntable_ratio_prot_produit = table_ratio[['Produit','ratio_kcal', 'ratio_prot']].groupby(['Produit']).mean()\ntable_ratio_prot_produit.reset_index(inplace = True)\ntable_ratio_prot_produit[table_ratio_prot_produit['Produit']=='Avoine']\n\n# ### Question 5 : Citez 5 aliments parmi les 20 aliments les plus caloriques, en utilisant le ratio énergie/poids\n\ntable_ratio_kcal_produit.sort_values('ratio_kcal', ascending = False).head(20)\n\n# Les premiers aliments parmis les 20 les plus calorifique sont: **Huiles de Foie de Poisso, Huile de Son de Riz, Huile de Sésame, Huiles de Poissons, Huile d'Arachide**\n\n# ### Citez 5 aliments parmi les 20 aliments les plus riches en protéines\n\ntable_ratio_prot_produit.sort_values('ratio_prot',ascending = False).head(20)\n\n# Les 5 premiers aliments parmis les 20 les plus riches en proteine sont:**Graines Colza/Moutarde, Soja, Arachides Decortiquees, Pois, Légumineuses Autres**.\n\n# ## Question 6\n# Calculons, pour les produits végétaux uniquement, la disponibilité intérieure mondiale exprimée en kcal\n\n# sélectionnons uniquement les produits d'origine végétale.\ntable_jointe_veg = table_jointe.loc[table_jointe['Origine']== 'végétal', :]\n\n\n# La disponibilité intérieur devant être donnée en kcal nous aurons besoin de la table des ratios.\n# faisons une jointure de nos deux tables\ntable_jointe_veg = pd.merge(table_jointe_veg,table_ratio_prot_produit, on = 'Produit', how = 'left')\ntable_jointe_veg['dispo_int_kcal'] = table_jointe_veg['Disponibilité intérieure'] * table_jointe_veg['ratio_kcal']\ndispo_int_kcal= table_jointe_veg['dispo_int_kcal'].sum()\ndispo_int_kcal\n\ntable_jointe_veg['dispo_int_kcal'].describe()\n\n# Calculons également, pour les produits végétaux uniquement, la disponibilité intérieure mondiale exprimée en kg\n\n# Avec la disponibilité intérieure d'origine végétale et le ratio en prot trouvons le résultat en kg de proteine\ndispo_int_kg = (table_jointe_veg['Disponibilité intérieure']*table_jointe_veg['ratio_prot']).sum()\ndispo_int_kg\n\n# ## Question 7:\n# Combien d'humains pourraient être nourris si toute la disponibilité intérieure mondiale de produits végétaux était utilisée pour de la nourriture?\n#\n\n# on prendra comme valeur d'apport energétique quotidien nécessaire 2500kcal/j pour avoir le résultat en terme de calorie\nbesoin_cal_annuel_pers = 2500*365\nhumains_nouris_kcal = dispo_int_kcal/besoin_cal_annuel_pers\nhumains_nouris_kcal\n\nprint(\"l'équivalent en calories du nombre d'humain que l'on pourrait nourrir est de {} , soit {} % de la population mondiale.\".format(round(humains_nouris_kcal, 2), round(humains_nouris_kcal*100/pop_mondiale, 1)))\n\n#poids moyen d'un humain:65kg\n#considérons le besoin en protéines moyen pour une personne= 0.9g/kg/jour à utiliser pour avoir le résultat en terme de kg\nbesoin_prot_annuel_pers = 0.9*65*0.001*365\nhumains_nouris_kg = dispo_int_kg/besoin_prot_annuel_pers\nhumains_nouris_kg\n\nprint(\"on peut nourrir {} d'humains en terme de protéine,soit {} % de la population mondiale en 2013\".format(humains_nouris_kg,round((humains_nouris_kg/pop_mondiale)*100, 2)))\n\n# ### Question 8:\n#\n# Combien d'humains pourraient être nourris si toute la disponibilité alimentaire en produits végétaux la nourriture végétale destinée aux animaux et les pertes de produits végétaux étaient utilisés pour de la nourriture ? Donnez les résultats en termes de calories, puis de protéines, et exprimez ensuite ces 2 résultats en pourcentage de la population mondiale.\n\n# +\n#créons une liste qui regroupe les trois élément en vue de faciliter la somme de ces élemnets qui représenterons la nourriture totale\n#col_list=['Nourriture', 'Aliments pour animaux', 'Pertes']\n#table_jointe_veg = table_jointe_veg.copy()\n\ntable_jointe_veg['nour_total'] = table_jointe_veg[['Nourriture','Aliments pour animaux', 'Pertes']].sum(axis=1)\n# -\n\n# trouvons la nourriture total en kcal\nnour_kcal=(table_jointe_veg['nour_total']*table_jointe_veg['ratio_kcal']).sum()/besoin_cal_annuel_pers\nnour_kcal\n\n# trouvons la nourriture total en kg de proteines\nnour_kgprot=(table_jointe_veg['nour_total']*table_jointe_veg['ratio_prot']).sum()/besoin_prot_annuel_pers\n\nprint(\"on peut nourrir {} d'humain en équivalent calorifique soit {}% de la population en 2013\".format(nour_kcal,round((nour_kcal/pop_mondiale)*100, 1)))\nprint(\"on peut nourrir {} d'humain en équivalent proteines soit {}% de la population en 2013\".format(nour_kgprot,round((nour_kgprot/pop_mondiale)*100, 1)))\n\n# ## Question 9 : \n# Combien d'humains pourraient être nourris avec la disponibilité alimentaire mondiale ? Donnez les résultats en termes de calories, puis de protéines, et exprimez ensuite ces 2 résultats en pourcentage de la population mondiale.\n\n#trouvons le nombre de personnes que l'on pourrait nourrir avec la disponibilité alimentaire mondiale en calories\ndispo_ali_kcal = table_jointe['dispo_alim_kcal'].sum()\nnbr_humain_disp_al_kcal = dispo_ali_kcal/besoin_cal_annuel_pers\nprint(\"on peut nourrir {} d'humain en terme de calorie soit {} % de la population mondiale en 2013\".format(round(nbr_humain_disp_al_kcal, 2),round((nbr_humain_disp_al_kcal/pop_mondiale)*100, 1)))\n\n\n#trouvons le nombre de personne que l'on pourrait nourrir avec la disponibilité alimentaire mondiale en proteines\ndispo_ali_kgprot = table_jointe['dispo_alim_kgprot'].sum()\nnbr_humain_disp_al_prot = dispo_ali_kgprot/besoin_prot_annuel_pers\nprint(\"on peut nourrir {} d'humain en terme de proteines soit {} % de la population mondiale en 2013\".format(round(nbr_humain_disp_al_prot, 2),round((nbr_humain_disp_al_prot/pop_mondiale)*100, 1)))\n\n# ## Question 10:\n# A partir des données téléchargées qui concernent la sous-nutrition, determinons la proportion de la population mondiale considérée comme étant en sous-nutrition ?\n\n# +\n#supprimons les dupplications de pays dans notre table sous alimentation\n\nsousalimentation.drop(sousalimentation.loc[sousalimentation['Zone'].isin(chn)].index, inplace = True)\n\n# +\n#changeons le format des années\n\nsousalimentation['Année']= sousalimentation['Année'].replace({'2012-2014':'2013','2013-2015':'2014','2014-2016':'2015','2015-2017':'2016','2016-2018':'2017'})\nsousalimentation.head(2)\n\n# +\n#convertissons notre colonne Valeur qui est de types OBJET en numeric pour gérer les cas de valeur <0.1 present dans nos données\n\nsousalimentation['Valeur'] = pd.to_numeric(sousalimentation['Valeur'],errors = 'coerce')\n\n# convertissons la valeur de la population sous alimenté car elle est en million d'habitant\nsousalimentation['Valeur']=sousalimentation['Valeur']*1000000\n\n\n# prenons uniquement les sous-alimentations sur l'année 2013\nsousal_annee= sousalimentation[sousalimentation['Année']=='2013']\nsousal_annee = sousal_annee.copy()\n\nnbr_pers_sousalimente = sousal_annee['Valeur'].sum()\nprint(\"{} d'humain soit, {}% de la population mondiale est considérée comme étant sous-nutrition en 2013\".format(round(nbr_pers_sousalimente),round((nbr_pers_sousalimente/pop_mondiale)*100, 2)))\n# -\n\n\"\"\"\nplt.rcdefaults()\n\nvalues = [round((nbr_pers_sousalimente/pop_mondiale)*100), prop_anim_cer]\ncolors = ['m','g']\nexplode = [ 0, 0.01]\nlabels = [\"Proportion de céréale pour l'alimentation humaine\", \"Proportion de céréale pour l'alimentation animale\"]\nplt.pie(values, colors= colors, labels=labels, explode = explode, autopct='%1.1f%%', shadow=True)\nplt.title('Repartion de céréale')\nplt.show()\n\"\"\"\n\n# #### travail sur la table céréales\n\n# supprimons les duplications de pays dans notre table céréales\ncereales.drop(cereales.loc[cereales['Zone'].isin(chn)].index, inplace = True)\n\n# Sur la table céréale, affichons les codes produits et produits\ncereales_reduit = cereales[[\"Code Produit\",\"Produit\"]].drop_duplicates(subset=[\"Code Produit\", \"Produit\"])\ncereales_reduit\n\n# créons une colonne nommée 'is-cereal' dans notre table jointe\ntable_jointe['is_cereal'] = table_jointe['Produit'].isin( cereales_reduit['Produit'])\n\n# #### Liste des produits considérés comme des céréales selon la FAO\n\n#filtrons uniquement les éléments ayant une correspondance avec les céréales\ntable_cereal=table_jointe[table_jointe[\"is_cereal\"]==True]\ntable_cereale= table_cereal.groupby(['Produit','Code Produit']).size().reset_index().rename(columns={0:'count'})\ntable_cereale[['Produit','Code Produit']]\n\n# ## Question 11:\n# En ne prenant en compte que les céréales destinées à l'alimentation (humaine et animale), quelle proportion (en termes de poids) est destinée à l'alimentation animale ?\n\n#trouvons la quantité de céréales destinées à l'alimentation humaine\nnour_cer = table_cereal['Nourriture'].sum()\n\n#trouvons la quantité de céréales destinées l'alimentation animale\nanim_cer = table_cereal['Aliments pour animaux'].sum()\n\nproportion_cereale_humaine = round(nour_cer/(nour_cer+anim_cer),2)\nproportion_cereale_humaine\n\n#proportion de céréale destinée à l'alimentation animale\nprop_anim_cer = round(anim_cer/(nour_cer+anim_cer),2)\nprint(\"{} % de céréales sont destinées à l'alimentation pour animaux en ne prenant en compte que les céréales destinées à l'alimentation humaine et animale\".format(prop_anim_cer*100))\n\n\n# +\n\n\nplt.rcdefaults()\n\nvalues = [proportion_cereale_humaine, prop_anim_cer]\ncolors = ['b','g']\nexplode = [ 0, 0.01]\nlabels = [\"Proportion de céréale pour l'alimentation humaine\", \"Proportion de céréale pour l'alimentation animale\"]\nplt.pie(values, colors= colors, labels=labels, explode = explode, autopct='%1.1f%%', shadow=True)\nplt.title(\"Repartion de céréale produite entre nourriture humaine et l'aliment pour animaux\")\nplt.show()\n\n# -\n\n# Sélectionnez parmi les données des bilans alimentaires les informations relatives aux pays dans lesquels la FAO recense des personnes en sous-nutrition.\n\n# trouvons la liste des pays ou l'on recence des personnes en sous-nutrition\nsousalimentation_pays = sousalimentation.loc[sousalimentation['Valeur']> 0 ,'Zone'].unique()\nsousalimentation_pays\n\n#\n# Repérez les 15 produits les plus exportés par ce groupe de pays\n\n# Sélectionnons les lignes qui correspondent aux pays ressencés pour la sous nutrition \ntable_jointe_groupe_pays_sousal=table_jointe.loc[table_jointe['Zone'].isin (sousalimentation_pays), :]\ntable_jointe_groupe_pays_sousal.head(2)\n\n# Sélectionnons uniquement les exportations par produit\nexportation = table_jointe_groupe_pays_sousal[['Exportations - Quantité','Produit']].groupby(['Produit']).sum()\ntable_exportation = exportation.sort_values('Exportations - Quantité', ascending =False).head(15)\ntable_exportation.reset_index(inplace =True)\ntable_exportation\n\n# liste de ces produits importés \nliste_produit = table_exportation['Produit']\n\n# sélectionnez les 200 plus grandes importations de ces produits (1 importation = une quantité d'un produit donné importée par un pays donné)\n\n# trouvons la correspondance des produits de notre liste dans notre table jointe\ntable_jointe_export_pays_sousal = table_jointe.loc[table_jointe['Produit'].isin(liste_produit), :]\n\n#sélectionnons uniquement les 200 premières importations\nimportation_pays_sousali = table_jointe_export_pays_sousal.sort_values('Importations - Quantité',ascending =False).head(200)\nimportation_pays_sousali[['Produit','Importations - Quantité']]\n\n# +\n# sélectionnons les colonnes qui nous seront utiles pour la suite de nos calculs\nimportation_pays_sousali = importation_pays_sousali[['Produit','Importations - Quantité','Nourriture','Aliments pour animaux','Autres utilisations (non alimentaire)','Disponibilité intérieure']]\n\n#Groupons ces importations par produit\nimportation_pays_sousali = importation_pays_sousali.groupby('Produit').sum()\nimportation_pays_sousali.reset_index(inplace=True)\n\n# -\n\n# affichons les 15 produits des 200 les plus importés et ayant les plus grandes exportations\nimportation_pays_sousali[['Produit','Importations - Quantité']]\n\n# calculons le ratio entre la quantité destinés aux \"Autres utilisations\" (Other uses) et la disponibilité intérieure.\nimportation_pays_sousali['ratio_autre_uti_dispo_int']=importation_pays_sousali['Autres utilisations (non alimentaire)']/importation_pays_sousali['Disponibilité intérieure']\nimportation_pays_sousali.head()\n\n# Calculons le ratio entre la quantité destinée à la nourriture animale et la quantité destinée à la nourriture (animale + humaine)\nimportation_pays_sousali['ratio_alianimaux_alimentanihumain'] = importation_pays_sousali['Aliments pour animaux']/(importation_pays_sousali['Aliments pour animaux']+importation_pays_sousali['Nourriture'])\nimportation_pays_sousali\n\n# ### Question 12 :\n# Donnez les 3 produits qui ont la plus grande valeur pour chacun des 2 ratios (vous aurez donc 6 produits à citer)\n\n#liste des 3 premiers hauts ratio autres utilisations/disponibilité intérieure\nimportation_pays_sousali.sort_values('ratio_autre_uti_dispo_int', ascending = [False]).loc[:,['Produit','ratio_autre_uti_dispo_int']].head(3)\n\n#liste des 3 premiers hauts ratio aliments pour animaux/aliments pour animaux + la nourriture\nimportation_pays_sousali.sort_values('ratio_alianimaux_alimentanihumain', ascending = [False]).loc[:,['Produit','ratio_alianimaux_alimentanihumain']].head(3)\n\n\n# ## Question 13 : \n# Combien de tonnes de céréales pourraient être libérées si les USA diminuaient leur production de produits animaux de 10% ?\n\n# +\n#trouvons la production animale libérée si baisse de 10%\nquant_lib_alim_animaux= (table_cereal[table_cereal['Zone']==\"États-Unis d'Amérique\"]['Aliments pour animaux']).sum()*0.1\n\nprint('si la production de produit animaux des USA était diminué de 10% cela libèrerait {} tonnes de céréales'.format(quant_lib_alim_animaux/1000))\n# -\n\n# ## Question 14:\n# En Thaïlande, quelle proportion de manioc est exportée ? Quelle est la proportion de personnes en sous-nutrition?\n\n#Trouvons la quantité de manioc exporté en Thaïlande\nmanioc_expot_thai =int(animaux_vegetaux.loc[(animaux_vegetaux['Zone']=='Thaïlande') & (animaux_vegetaux['Produit']=='Manioc') & (animaux_vegetaux['Élément']=='Exportations - Quantité'),'Valeur'])\nmanioc_expot_thai\n\n#Trouvons la production de manioc en Thaïlande\nmanioc_production_thai =int(animaux_vegetaux.loc[(animaux_vegetaux['Zone']=='Thaïlande') & (animaux_vegetaux['Produit']=='Manioc') & (animaux_vegetaux['Élément']=='Production'),'Valeur']) \nmanioc_production_thai\n\n#Trouvons le nombre de personnes sous alimenté en Thaïlande\nnbr_sousaliment_thaïlande = float(sousal_annee.loc[(sousal_annee['Zone']=='Thaïlande'),'Valeur'])\nnbr_sousaliment_thaïlande\n\n# +\n#La population de la Thaïlande\npopulation_thaïlande= int(population.loc[population['Zone']=='Thaïlande', 'Valeur'])\npopulation_thaïlande\n\nprint('la Thaïlande a exporté {} de tonnes de manioc soit {} % par rapport à la production totale en 2013 et {} % de la population de ce pays sont en sous alimentation'.format(manioc_expot_thai/1000,round((manioc_expot_thai/manioc_production_thai)*100, 2), round((nbr_sousaliment_thaïlande/population_thaïlande)*100, 1)))\n# -\n\n# ## Question 15-18: Transformation des tables pour les requetes SQL\n# Créons les tables qui alimenterons notre base de données:\n#\n\n# * Une table appelée population, contenant la population de chaque pays pour 2013. Elle contient 4 colonnes : pays, code_pays, annee, population.\n\n# +\n# sélectionnons les colonnes dont on a besoin\n\npopu= population[['Zone','Code zone','Année','Valeur']]\n\n# renommons nos colonnes\npopu.columns =['pays','code_pays','annee','population']\n\n# déterminons la clé primaire de la table popu\ncheck_keys(popu,'pays')\n\n# exportons notre dataframe via un fichier csv \npopu.to_csv('population.csv',index= False)\n# -\n\n# * la table appelée dispo_alim contenant pour chaque pays et pour chaque produit en 2013, les informations suivantes:\n# les colonnes : pays, code_pays, année, produit, code_produit, origin, dispo_alim_tonnes, dispo_alim_kcal_p_j, dispo_prot, dispo_mat_gr .\n\n# +\n#sélectionnons les colonnes qui nous interessent dans la table \ndispo_alim = table[['Zone','Code zone','Année','Produit','Code Produit','Origine','Disponibilité alimentaire en quantité (kg/personne/an)','Disponibilité alimentaire (Kcal/personne/jour)','Disponibilité de protéines en quantité (g/personne/jour)','Disponibilité de matière grasse en quantité (g/personne/jour)']]\n\n# renommons nos colonnes\ndispo_alim.columns=['pays','code_pays','annee','produit','code_produit','origin','dispo_alim_tonnes','dispo_alim_kcal_p_j','dispo_prot', 'dispo_mat_gr']\n\n# déterminons la clé primaire de la table dispo_alim\ncheck_keys(dispo_alim,['pays','produit'])\n\n# exportons notre dataframe via un fichier csv \ndispo_alim.to_csv('dispo_alim.csv',index=False)\n# -\n\n# * la table appelée equilibre_prod contenant pour chaque pays et pour chaque produit en 2013, les colonnes suivantes : pays, code_pays, année, produit, code_produit, dispo_int, alim_ani, semences, pertes, transfo, nourriture, autres_utilisations.\n\n# +\n# sélectionnons les colonnes pertinantes dans la table \nequilibre_prod = table[['Zone','Code zone','Année','Produit','Code Produit','Disponibilité intérieure','Aliments pour animaux','Semences','Pertes','Traitement','Nourriture','Autres utilisations (non alimentaire)']]\n\n# renommons nos colonnes\nequilibre_prod.columns=['pays','code_pays','annee','produit','code_produit','dispo_int','alim_ani','semences','pertes', 'transfo','nourriture','autres_utilisations']\n\n# déterminons la clé primaire de la table equilibre_prod\ncheck_keys(equilibre_prod,['pays','produit'])\n\n#exportons notre dataframe via un fichier csv \nequilibre_prod.to_csv('equilibre_prod.csv', index = False)\n# -\n\n# * la table appelée sous_nutrition, contenant le nombre de personnes en sous-alimentation pour chaque pays en 2013. Avec 4 colonnes : pays, code_pays, année, nb_personnes.\n\n# +\n# sélectionnons les colonnes de notre futur table dans la table sousalimentation_annee\nsous_alimentation = sousal_annee[['Zone','Code zone','Année','Valeur']]\nsous_alimentation.columns =['pays','code_pays','annee','nb_personnes']\n\n# déterminons la clé primaire de la table sousalimentation_pays\ncheck_keys(sous_alimentation,'pays')\n\n# exportons notre dataframe via un fichier csv \nsous_alimentation.to_csv('sous_alimentation.csv',index = False)\n# -\n\n# ### Question 20\n# Pour quelques uns des produits identifiés dans la dernière requête SQL, les \"autres utilisations\" possibles des produits figurants sur la liste sont: (Issu de la recherche internet)\n#\n# - **L'alcool non commestible** est utisé à des fins médicales.\n# - **Les plantes aquatiques** servent aux maintien de l'écosysthème aquatique(fournissent de l'oxygène et luttent contre la prolifération des algues. \n# - **L'huile de palme** est utilisée comme agro-carburant et dans l'oléochimie pour fabrication des produits cosmétiques. \n# - **L'huile de pante Oleifère** : usage phamaceutique,cosmétique.\n#\n","repo_name":"MarieMefoo/Realisez_une_etude_de_sante_publique","sub_path":"P3_01_CodeReponses_1_14_20.ipynb","file_name":"P3_01_CodeReponses_1_14_20.ipynb","file_ext":"py","file_size_in_byte":26847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"20"} +{"seq_id":"38090607432","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.preprocessing import StandardScaler, LabelEncoder\nfrom sklearn.model_selection import train_test_split\nfrom keras.models import Sequential, Model\nfrom keras.layers import Input, Dense\nfrom sklearn.metrics import mean_squared_error\n\n# Load the log dataset (replace with your dataset file)\ndata = pd.read_csv('../dataset/log_data.csv')\n\n# Convert timestamp to datetime objects\ndata['timestamp'] = pd.to_datetime(data['timestamp'])\n\n# Calculate time difference in seconds from the minimum timestamp\nmin_timestamp = data['timestamp'].min()\ndata['time_diff'] = (data['timestamp'] - min_timestamp).dt.total_seconds()\n\n# Select relevant features for anomaly detection\n# In this case, we'll use time_diff, activity, and username\nfeatures = data[['time_diff', 'activity', 'username']]\n\n\n# Convert categorical features to numerical using label encoding\nlabel_encoders = {}\nfor col in ['activity', 'username']:\n label_encoders[col] = LabelEncoder()\n features[col] = label_encoders[col].fit_transform(features[col])\n\n# Standardize the features\nscaler = StandardScaler()\nscaled_features = scaler.fit_transform(features)\n\n# Split the data into train and test sets\nX_train, X_test = train_test_split(scaled_features, test_size=0.2, random_state=42)\n\n\n# ... Build the autoencoder model ...\ninput_dim = X_train.shape[1]\nencoding_dim = 10 # Adjust based on your data complexity\nautoencoder = Sequential()\nautoencoder.add(Dense(encoding_dim, input_shape=(input_dim,), activation='relu'))\nautoencoder.add(Dense(input_dim, activation='linear'))\nautoencoder.compile(optimizer='adam', loss='mean_squared_error')\n\n# ... Train the autoencoder model ...\nautoencoder.fit(X_train, X_train, epochs=50, batch_size=32, shuffle=True, validation_data=(X_test, X_test))\n\n\n# Reconstruct the data using the trained autoencoder\nreconstructed_data = autoencoder.predict(scaled_features)\nmse = np.mean(np.power(scaled_features - reconstructed_data, 2), axis=1)\n\n# Define a threshold to identify anomalies\nthreshold = np.percentile(mse, 95) # Adjust based on your data\n\n# Identify anomalies\nanomalies = data[mse > threshold]\n\n# Define actionable insights templates\ninsight_templates = {\n 'Unauthorized Access Detected': {\n 'severity': 'High',\n 'rule': 'Access Control Enforcement',\n 'template': \"Anomaly Details:\\n- Timestamp: {timestamp}\\n- User: {username}\\n- Activity: {activity}\\n- Recommendation: Investigate the unauthorized access by user '{username}' at the given timestamp. Check for signs of compromise and take appropriate action to secure the account and prevent further breaches.\"\n },\n # Define more templates for other compliance rules\n}\n\n# Generate actionable insights\nactionable_insights = []\nfor _, anomaly_row in anomalies.iterrows():\n insight_template = insight_templates.get('Unauthorized Access Detected') # Replace with relevant template\n if insight_template:\n actionable_insights.append(insight_template['template'].format(\n timestamp=anomaly_row['timestamp'],\n username=anomaly_row['username'],\n activity=anomaly_row['activity']\n ))\n\n# Print actionable insights\nprint(\"Actionable Insights:\")\nfor insight in actionable_insights:\n print(insight)\n\n","repo_name":"ArunHarbola/ComplianceManagementSystem_Flipkart","sub_path":"model/autoencoder_compliance_mapping.ipynb","file_name":"autoencoder_compliance_mapping.ipynb","file_ext":"py","file_size_in_byte":3276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"20"} +{"seq_id":"41183577588","text":"# +\n# In this we will look those function which is not common in Pandas Series and DataFrame, lets look....\n# -\n\nimport pandas as pd\n\nmovies_data = pd.read_csv('tmdb_5000_movies.csv')\n\nmovies_data\n\nmovies_data.head()\n\n# +\n# Ab upar k dataFrame me se kisi yek column ko utha lenge to wo hoga apna Series.\n\n# +\n# Lets pick runtime from the dataframe which is a column in that:\n# -\n\nser = movies_data['runtime']\n\nser\n\ntype(ser)\n\nser.head()\n\nser.sum() # it will sum of all the values in runtime\n\nser.size # it tells ki kitni values hai humare is series me\n\nser.count()\n\n# +\n# But why count() and size gives different values ?\n# Becoz, size all consider the NaN or undefined values but cout() doesn't counts the NaN or undefined values\n# -\n\n# Now, we can easily find the number of undefined values or missing values or non-representable values in the runtime series:\nser.size - ser.count()\n\n# +\n# now to find mean, std, etc...\n# -\n\nser.mean()\n\nser.median() # found median of the series\n\nser.std() # standard deviation\n\nser.min()\n\nser.max() # here, found the maximum runtime\n\n# +\n# Now, lets see method which can be used only in series...\n# -\n\nser.unique() # it will remove the repetetive values of runtime series.\n\nlen(ser.unique())\n\nser.nunique()\n\n# +\n# Now, why is there a difference b/w the two above ?\n# Becoz, unique() method considers nan value also as uniqueness but nunique() doesn't considers that.\n# -\n\n# But we can increase the value of ser.nunique(), for this we do this:\nser.nunique(dropna = False) # by-default its value is turned True to ignore/drop the nan value\n\n# But this unique() doesn't apply to a dataFrame: Hence, we get the error.. Thus, this unique method is used with series only.\nmovies_data.unique()\n\nmovies_data.value_counts() # this has to throw error,but hasn't thrown why ?\n\nmovies_data.nunique() # here, we are not getting error, so it can be used here.\n\n# this gives output in Descending order as shown below:\nser.value_counts() # its tell ki there are 163 movies whose runtime is 90 minutes...similarly others...\n\nser.value_counts(ascending = True) # Now, its got sorted in ascending order\n\nser.value_counts(ascending = False , bins = 3) # bins here is to create 3 intervals of runtime and corresponding #movies\n# i.e from -0.339 minutes to 112.667 minutes there are 3245 movies. \n# also ( this bracket implies its not included and ] this implies its icluded (just like in maths)\n\n# similarly we can do the same for 5 intervals:\nser.value_counts(ascending = False, bins = 5)\n\n\n","repo_name":"rahulraj22/Data-Analysis-Visualization","sub_path":"23-37_5000_tmdb_movies_metadata/tut-32_Pandas-Series.ipynb","file_name":"tut-32_Pandas-Series.ipynb","file_ext":"py","file_size_in_byte":2519,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"20"} +{"seq_id":"39273473232","text":"# # Naive Bayes\n\nclassifier_naive_bayes_gaussian = GaussianNB()\nclassifier_naive_bayes_gaussian.fit(X_train_validation,y_train_validation) \n#Get training probabilities for probability calibration\nprobabilities_train = classifier_naive_bayes_gaussian.predict_proba(X_train_validation)[:,1]\n#Calibrate probabilities with isotonic regression\nir.fit(probabilities_train,y_train_validation) \n#Calibrate probabilities with platt's method\nlr.fit(probabilities_train.reshape( -1, 1 ),y_train_validation) \n\n#Use the naive Bayes model on the test set and get uncalibrated probabilities\nprobabilities_test = classifier_naive_bayes_gaussian.predict_proba(X_test)[:,1]\n#Use the cost sensitive threshold to predict the outcome\npredictions_test_cost = [0 if x < threshold_cost else 1 for x in probabilities_test]\n#Use the 50% threshold to predict the outcome\npredictions_test_50 = [0 if x < threshold_05 else 1 for x in probabilities_test]\n#Calibrate the probabilities by isotonic regression \nprobas_calibrated_isotonic = ir.transform(probabilities_test)\n#Use the cost sensitive threshold to predict the outcome\npredictions_test_calibrated_isotonic_cost = [0 if x < threshold_cost else 1 for x in probas_calibrated_isotonic]\n#Use the 50% threshold to predict the outcome\npredictions_test_calibrated_isotonic_50 = [0 if x < threshold_05 else 1 for x in probas_calibrated_isotonic]\n#Calibrate the probabilities by isotonic regression \nprobas_calibrated_platt = lr.predict_proba(probabilities_test.reshape( -1, 1 ))[:,1]\n#Use the cost sensitive threshold to predict the outcome\npredictions_test_calibrated_platts_cost = [0 if x < threshold_cost else 1 for x in probas_calibrated_platt]\n#Use the 50% threshold to predict the outcome\npredictions_test_calibrated_platts_50 = [0 if x < threshold_05 else 1 for x in probas_calibrated_platt]\n\n#Print the expected cost and the classification report for uncalibrated probabilities, \n#isotonic calibrated probabilities and platts calibrated probabilities\n#with cost-sensitive threshold and 50% threshold\nprint('Uncalibrated probabilities, cost sensitive threshold: %i ' % expected_cost(y_test, predictions_test_cost))\nprint(classification_report(y_test, predictions_test_cost,target_names = ['Pay','Default']))\nprint('Uncalibrated probabilities, 50pct threshold: %i ' % expected_cost(y_test, predictions_test_50))\nprint(classification_report(y_test, predictions_test_50,target_names = ['Pay','Default']))\nprint('Isotonic calibrated probabilities, cost sensitive threshold: %i ' % expected_cost(y_test, predictions_test_calibrated_isotonic_cost))\nprint(classification_report(y_test, predictions_test_calibrated_isotonic_cost,target_names = ['Pay','Default']))\nprint('Isotonic calibrated probabilities, 50pct threshold: %i ' % expected_cost(y_test, predictions_test_calibrated_isotonic_50))\nprint(classification_report(y_test, predictions_test_calibrated_isotonic_50,target_names = ['Pay','Default']))\nprint('Platts calibrated probabilities, cost sensitive threshold: %i ' % expected_cost(y_test, predictions_test_calibrated_platts_cost))\nprint(classification_report(y_test, predictions_test_calibrated_platts_cost,target_names = ['Pay','Default']))\nprint('Platts calibrated probabilities, 50pct threshold: %i ' % expected_cost(y_test, predictions_test_calibrated_platts_50))\nprint(classification_report(y_test, predictions_test_calibrated_platts_50,target_names = ['Pay','Default']))\nprint('Dummy classifier: %i ' % expected_cost(y_test, clf_predictions))\nprint(classification_report(y_test, clf_predictions,target_names = ['Pay','Default']))\n\n#Compute ROC curve and the area under the curve\n#Start cross validation and draw the ROC curves\nmean_tpr = 0.0\nmean_fpr = np.linspace(0, 1, 100)\nfpr, tpr, thresholds = roc_curve(y_test, predictions_test_calibrated_isotonic_cost)\nmean_tpr += interp(mean_fpr, fpr, tpr)\nmean_tpr[0] = 0.0\nroc_auc = auc(fpr, tpr)\nplt.figure(10) \nplt.plot(fpr, tpr, lw=1, label='Naive Bayes Gaussian ROC (area = %0.2f)' % roc_auc)\nplt.xlim([0, 1])\nplt.ylim([0, 1])\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.plot([0, 1], [0, 1], '--', color=(0.6, 0.6, 0.6), label='Luck')\nplt.title('Naive Bayes')\nplt.legend(loc=\"lower right\")\nplt.savefig('Naive Bayes ROC')\n\n# +\n#Plot the confusion matrix \ncm = confusion_matrix_custom(y_test,predictions_test_calibrated_isotonic_cost)\ncm = np.round(cm, decimals = 3)\nfig, ax = plt.subplots()\nax.axis('tight')\nax.axis('off')\nax.table(cellText=cm,\n rowLabels=['Test positive','Test negative'],\n colLabels=['Default','Pay'],\n cellLoc='center',colWidths=[0.25, 0.25],\n loc='center')\nplt.tight_layout()\n\nfig, ax = plt.subplots()\nim = ax.imshow(cm, cmap=plt.cm.Blues, interpolation='none')\nfig.colorbar(im)\nlocs = np.arange(len(np.unique(y_test)))\nax.xaxis.tick_top()\nax.xaxis.set_label_position('top')\nax.xaxis.set_ticks(locs + 0.5)\nax.xaxis.set(ticks=locs, ticklabels=['Pay','Default'])\nax.yaxis.set_ticks(locs + 0.5)\nax.yaxis.set(ticks=locs, ticklabels=['Positive','Negative'])\nplt.xlabel('True label', fontsize=20)\nplt.ylabel('Prediction', fontsize=20)\nplt.tick_params(axis='both', labelsize=20)\nplt.tight_layout()\nax.grid(False) \n","repo_name":"MustafaOguz/Machine-Learning","sub_path":"4_Naive_Bayes.ipynb","file_name":"4_Naive_Bayes.ipynb","file_ext":"py","file_size_in_byte":5201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"20"} +{"seq_id":"13564645414","text":"# ## Constructing CS for weighted sampling without replacement \n#\n# To construct the CS, we need to specify the following terms: \n# * `N`: int, denoting the total number of transactions \n# * `M`: numpy array, containing the reported transaction values \n# * `f`: numpy array, containing the true misspecified fractions in [0,1].\n# For simplicity, we have assumed that `f` takes the form \n# of a numpy array, and it is accessed via its index when \n# needed. A more general implementation should have `f` as \n# a function handle, representing the oracle (i.e., human auditor), \n# that takes in as input an index in the range `{1, 2, ..., N}`, and \n# outputs the true misstated fraction for that index. \n# * `S`: numpy array, containing the side-information in [0,1].\n# This represents the predicted f-values, generated by an AI model \n# trained on historical data. \n#\n\n# ### Generating synthetic data \n# Our CS construction works for arbitrary `M, f, S` values (assuming `f` and `S` are [0,1]-valued). However, for empirically testing the performance, we have included a function `generate_MFS` for generating `M, f, S` triplets synthetically. We begin by describing how to use that function to generate the problem data. \n#\n# * **Generating `M`**: This function generates the data with `N` transactions, of which `N1` have \"large values\" and `N2` have small values. The precise range of these large and small values area specified in the input parameter `M_ranges`. \n# * **Generating `f`**: The function takes another paramter `f_ranges` that specifies the in intervals within which `f` lies uniformly for small and large `M` values. \n# * **Generating `S`**: Finally, the side-information is generated to lie within a ratio `[1-a, 1+a]` for `a` in (0,1) of the ground truth `f`-values. This is specfied by the input parameter `f_over_S_range`. \n\n# +\nimport numpy as np \nimport matplotlib.pyplot as plt \nfrom utils import generate_MFS\n\nN = 200\nN1 = 20\nN2 = N - N1\na = 0.4\nf_over_S_range = [1 - a, 1 + a]\nf_ranges = [[0.4, 0.5], [1e-3, 2 * 1e-3]]\nM_ranges = [ [1e5, 1e6], [1e4, 5*1e4]]\nM, f, S = generate_MFS(N_vals=(N1, N2), N=N, M_ranges=M_ranges,f_ranges=f_ranges, a=a)\n\n\nNN = np.arange(1, N+1)\nplt.figure()\nplt.bar(NN, M, label='reported', alpha=0.5)\nplt.bar(NN, M*f, label='misspecified amount', alpha=0.4)\nplt.bar(NN, S*f, label='predicted', alpha=0.4)\nplt.yscale('log')\nplt.ylabel('Monetary Value (log scale)')\nplt.xlabel('Transaction Index')\nplt.legend()\n\n\n# -\n\n# ### Constructing the CSs \n#\n# To construct the CS, we mainly need to specify the following: \n# * `cs`: choose between `Bet`, `Emp. Bern.`, or `Hoef.`\n# * `method_name`: this can be `propM`, `propMS`, or `uniform`\n# * `use_CV`: this is a bool, which decides whether control-variates should be used or not. Only use this option with the `proM` method. \n#\n# Below, we demonstrate how to construct betting-based, empirical-Bernstein, and Hoeffding CSs, using propM sampling strategy, with and without control variates\n\n# +\nfrom weightedCSsequential import run_one_expt\nfrom constants import ColorsDict\nnG = 100\nlambda_max = 1.5 \nbeta_max = 1.5\n\ndef func(M, f, S, nG, lambda_max, beta_max, cs):\n result_propMS = run_one_expt(M, f, S, \n cs=cs,\n method_name='propM',\n lambda_max=lambda_max,\n beta_max=beta_max,\n nG=nG,\n use_CV=False,\n f_over_S_range=f_over_S_range,\n alpha=0.05,\n logical_CS=False,\n intersect=False,\n return_payoff=False)\n grid, _, L1, U1, _, _, _ = result_propMS\n\n\n result_CV = run_one_expt(M, f, S, \n cs=cs,\n method_name='propM',\n lambda_max=lambda_max,\n beta_max=beta_max,\n nG=nG,\n use_CV=True,\n f_over_S_range=f_over_S_range,\n alpha=0.05,\n logical_CS=False,\n intersect=False,\n return_payoff=False)\n _, _, L2, U2, _, _, _ = result_CV\n return L1, U1, L2, U2\n\n# call the function \nplt.figure()\n\nfor cs in ['Bet', 'Hoef.', 'EB']:\n L1, U1, L2, U2 = func(M, f, S, nG, lambda_max, beta_max, cs)\n plt.plot(NN, np.minimum(U1-L1, 1), label=cs)\n plt.plot(NN, np.minimum(U2-L2, 1), label=f'{cs}+CV')\nplt.ylabel('Width of CS')\nplt.xlabel('Number of transactions audited')\nplt.legend()\nplt.show()\n\n# -\n\n# Finally, note that we can also extract the first time when the CS falls below a level $\\epsilon$, by calling the function `first_threshold_crossing`. By repeating this whole process several times, we can obtain the distribution of the stopping times of the two methods. \n#\n\n# +\nfrom tqdm import tqdm \nfrom utils import first_threshold_crossing\n\ncses = ['Bet', 'Hoef.', 'EB']\nnum_trials = 100 \nepsilon = 0.05 # the threshold for stopping \n# initialize the arrays to store the stopping times \n# repeat the experiment `num_trials` times to get the array of stopping times \nplt.figure()\nfor cs in cses:\n\n StoppingTimes_propM = np.zeros((num_trials,))\n StoppingTimes_CV = np.zeros((num_trials,))\n for trial in tqdm(range(num_trials)):\n # generate M, F, S \n M, f, S = generate_MFS(N_vals=(N1, N2), N=N, M_ranges=M_ranges,f_ranges=f_ranges, a=a)\n # get the L, U, values for the two methods \n L1, U1, L2, U2 = func(M, f, S, nG, lambda_max, beta_max, cs)\n # get the two stopping times \n st1 = first_threshold_crossing(U1-L1, th=epsilon, upward=False)\n st2 = first_threshold_crossing(U2-L2, th=epsilon, upward=False)\n StoppingTimes_propM[trial] = st1\n StoppingTimes_CV[trial] = st2\n # plot the histogram \n plt.hist(x=StoppingTimes_propM, label=cs, alpha=0.6)\n plt.hist(x=StoppingTimes_CV, label=f'{cs}+CV', alpha=0.6)\nplt.title(\"Stopping Time Distribution\")\nplt.ylabel(\"Density\")\nplt.xlabel(\"Stopping Times\")\nplt.legend()\nplt.show()\n# -\n\n\n","repo_name":"sshekhar17/WeightedWoRConfSeq","sub_path":"src/example.ipynb","file_name":"example.ipynb","file_ext":"py","file_size_in_byte":6400,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"20"} +{"seq_id":"37609514378","text":"# + [markdown] editable=true\n# This notebook will test the SQL in sql_queries.py on single files to ensure that the code is working as intended before executing\n\n# + editable=true\nfrom time import time\nimport configparser\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport boto3\n\n# %load_ext sql\n\n# + [markdown] editable=true\n# #### Connect to Redshift DWH\n\n# + editable=true\nconfig = configparser.ConfigParser()\nconfig.read_file(open('dwh.cfg'))\nKEY=config.get('AWS','key')\nSECRET= config.get('AWS','secret')\n\nDWH_DB= config.get(\"DWH\",\"DWH_DB\")\nDWH_DB_USER= config.get(\"DWH\",\"DWH_DB_USER\")\nDWH_DB_PASSWORD= config.get(\"DWH\",\"DWH_DB_PASSWORD\")\nDWH_PORT = config.get(\"DWH\",\"DWH_PORT\")\nDWH_ENDPOINT= config.get(\"CLUSTER\",\"HOST\")\nDWH_ROLE_ARN= config.get(\"IAM_ROLE\",\"ARN\")\n\nLOG_DATA = config.get(\"S3\", \"LOG_DATA\")\nLOG_PATH = config.get(\"S3\", \"LOG_JSONPATH\")\nSONG_DATA = config.get(\"S3\", \"SONG_DATA\")\n\n# + editable=true\nconn_string=\"postgresql://{}:{}@{}:{}/{}\".format(DWH_DB_USER, DWH_DB_PASSWORD, DWH_ENDPOINT, DWH_PORT,DWH_DB)\nprint(conn_string)\n# %sql $conn_string\n\n# + [markdown] editable=true\n# #### Test Create Table SQL Queries\n\n# + editable=true language=\"sql\"\n# DROP TABLE IF EXISTS staging_events;\n# CREATE TABLE IF NOT EXISTS staging_events\n# (\n# artist VARCHAR(50),\n# auth VARCHAR(20),\n# firstName VARCHAR(50),\n# gender VARCHAR(1),\n# itemInSession INTEGER,\n# lastName VARCHAR(50),\n# length FLOAT,\n# level VARCHAR(4),\n# location VARCHAR,\n# method VARCHAR(3),\n# page VARCHAR(8),\n# registration FLOAT,\n# sessionId INTEGER,\n# song VARCHAR(50),\n# status INTEGER,\n# ts BIGINT,\n# userAgent VARCHAR,\n# userId INTEGER\n# );\n\n# + editable=true language=\"sql\"\n# DROP TABLE IF EXISTS staging_songs;\n# CREATE TABLE IF NOT EXISTS staging_songs\n# (\n# num_songs INTEGER,\n# artist_id VARCHAR(18),\n# artist_latitude FLOAT,\n# artist_longitude FLOAT,\n# artist_location VARCHAR,\n# artist_name VARCHAR(50),\n# song_id VARCHAR(18),\n# title VARCHAR(50),\n# duration FLOAT,\n# year INT\n# );\n\n# + editable=true language=\"sql\"\n# DROP TABLE IF EXISTS fact_songplay;\n# CREATE TABLE IF NOT EXISTS fact_songplay\n# (\n# songplay_id INTEGER IDENTITY(0,1),\n# start_time TIMESTAMP,\n# user_id INTEGER sortkey distkey,\n# level VARCHAR(4),\n# song_id VARCHAR(18),\n# artist_id VARCHAR(18),\n# session_id INTEGER,\n# location VARCHAR,\n# user_agent VARCHAR\n# );\n\n# + editable=true language=\"sql\"\n# DROP TABLE IF EXISTS dim_users;\n# CREATE TABLE IF NOT EXISTS dim_users\n# (\n# user_id INTEGER PRIMARY KEY sortkey distkey,\n# first_name VARCHAR(50),\n# last_name VARCHAR(50),\n# gender VARCHAR(1),\n# level VARCHAR(4)\n# );\n\n# + editable=true language=\"sql\"\n# DROP TABLE IF EXISTS dim_songs;\n# CREATE TABLE IF NOT EXISTS dim_songs\n# (\n# song_id VARCHAR(18) PRIMARY KEY,\n# title VARCHAR(50),\n# artist_id VARCHAR(18) sortkey distkey,\n# year INTEGER,\n# duration FLOAT\n# );\n\n# + editable=true language=\"sql\"\n# DROP TABLE IF EXISTS dim_artists;\n# CREATE TABLE IF NOT EXISTS dim_artists\n# (\n# artist_id VARCHAR(18) PRIMARY KEY sortkey distkey,\n# name VARCHAR(50),\n# location VARCHAR,\n# lattitude FLOAT,\n# longitude FLOAT\n# );\n\n# + editable=true language=\"sql\"\n# DROP TABLE IF EXISTS dim_time;\n# CREATE TABLE IF NOT EXISTS dim_time\n# (\n# start_time TIMESTAMP PRIMARY KEY sortkey distkey, \n# hour INTEGER, \n# day INTEGER, \n# week INTEGER, \n# month INTEGER, \n# year INTEGER, \n# weekday INTEGER\n# );\n\n# + [markdown] editable=true\n# #### Test copying data to the events staging table\n\n# + editable=true\n# Look at the data in the log_data directory of the S3 bucket\ns3 = boto3.resource('s3',\n region_name=\"us-west-2\",\n aws_access_key_id=KEY,\n aws_secret_access_key=SECRET\n )\n\nsampleDbBucket = s3.Bucket(\"udacity-dend\")\n\nfor obj in sampleDbBucket.objects.filter(Prefix=\"log_data\"):\n print(obj)\n\n# + editable=true\n# Try to copy one json file\nstaging_events_copy = (\"\"\"\n copy {} from 's3://udacity-dend/log_data/2018/11/2018-11-01-events.json'\n credentials 'aws_iam_role={}'\n region 'us-west-2'\n FORMAT AS JSON 's3://udacity-dend/log_json_path.json';\n\"\"\").format('staging_events', DWH_ROLE_ARN)\n\n# + editable=true\n# %sql $staging_events_copy\n\n# + editable=true language=\"sql\"\n# SELECT *\n# FROM staging_events\n# LIMIT 10\n\n# + [markdown] editable=true\n# #### Test copying data to the songs staging table\n\n# + editable=true\nstaging_songs_copy = (\"\"\"\n copy {} from '{}'\n credentials 'aws_iam_role={}'\n region 'us-west-2'\n FORMAT AS JSON 'auto';\n\"\"\").format('staging_songs', 's3://udacity-dend/song_data/A/B/C/TRABCEI128F424C983.json', DWH_ROLE_ARN)\n\n# + editable=true\n# %sql $staging_songs_copy\n\n# + editable=true language=\"sql\"\n# SELECT *\n# FROM staging_songs\n\n# + [markdown] editable=true\n# #### Test inserting the data and creating the schema\n\n# + editable=true language=\"sql\"\n# INSERT INTO fact_songplay(start_time, user_id, level, song_id, artist_id, session_id, location, user_agent)\n# SELECT DISTINCT TIMESTAMP 'epoch' + se.ts/1000 * INTERVAL '1 second' AS start_time,\n# se.userId AS user_id,\n# se.level AS level,\n# ss.song_id AS song_id,\n# ss.artist_id AS artist_id,\n# se.sessionId AS session_id,\n# se.location as location,\n# se.userAgent as user_agent\n# FROM staging_events as se\n# JOIN staging_songs as ss ON se.song = ss.title AND se.artist = ss.artist_name;\n\n# + editable=true language=\"sql\"\n# INSERT INTO dim_users(user_id, first_name, last_name, gender, level)\n# SELECT DISTINCT se.userId AS user_id,\n# se.firstName AS first_name,\n# se.lastName AS last_name,\n# se.gender AS gender,\n# se.level AS level\n# FROM staging_events as se\n# WHERE user_id IS NOT NULL;\n#\n# SELECT *\n# FROM dim_users\n# LIMIT 10;\n\n# + editable=true language=\"sql\"\n# INSERT INTO dim_songs(song_id, title, artist_id, year, duration)\n# SELECT DISTINCT ss.song_id AS song_id,\n# ss.title AS title,\n# ss.artist_id AS artist_id,\n# ss.year AS year,\n# ss.duration AS duration\n# FROM staging_songs as SS\n# WHERE song_id IS NOT NULL;\n#\n# SELECT *\n# FROM dim_songs\n# LIMIT 10;\n\n# + editable=true language=\"sql\"\n# INSERT INTO dim_artists(artist_id, name, location, lattitude, longitude)\n# SELECT DISTINCT ss.artist_id AS artist_id,\n# ss.artist_name AS name,\n# ss.artist_location AS location,\n# ss.artist_latitude AS lattitude,\n# ss.artist_longitude AS longitude\n# FROM staging_songs as SS\n# WHERE artist_id IS NOT NULL;\n#\n# SELECT *\n# FROM dim_artists\n# LIMIT 10;\n\n# + editable=true language=\"sql\"\n# INSERT INTO dim_time(start_time, hour, day, week, month, year, weekday)\n# SELECT DISTINCT TIMESTAMP 'epoch' + se.ts/1000 * INTERVAL '1 second' AS start_time,\n# EXTRACT(hour from start_time) as hour,\n# EXTRACT(day from start_time) as day,\n# EXTRACT(week from start_time) as week,\n# EXTRACT(month from start_time) as month,\n# EXTRACT(year from start_time) as year,\n# EXTRACT(weekday from start_time) as weekday\n# FROM staging_events AS se\n# WHERE start_time IS NOT NULL;\n#\n# SELECT * \n# FROM dim_time\n# LIMIT 10\n","repo_name":"ifu97224/udacity_data_engineer_dwh_project","sub_path":"test_create_and_copy.ipynb","file_name":"test_create_and_copy.ipynb","file_ext":"py","file_size_in_byte":8011,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"20"} +{"seq_id":"18583026195","text":"# Q1\n'''Exception is an event, which occurs during the execution of a program,\n that provide the normal flow of the program's instructions.\n it means when a Python script encounters a situation that it cannot run with, it raises an exception.\n An exception is a Python object that represents an error.'''\n#difference between syntax error and Exception\n'''A syntax error systemic error or the error implies a problem that mostly arises due to the shortage of system resources.\n On the other hand,the except help to run the code in case of error or the exceptions occur during runtime.'''\n'''Errors mostly happen at compile-time like syntax error. however it can happen at runtime as well. \n Whereas an Exception occurs at runtime or checked exceptions can be detected at compile time.'''\n\n# +\n# Q2\n''' If the exception is not handled,\n the exception is re-raised after the finally clause has been executed.'''\n#example\n\nbool_return()\ndef divide(x, y):\n try:\n result = x / y\n except ZeroDivisionError:\n print(\"division by zero!\")\n else:\n print(\"result is\", result)\n finally:\n print(\"executing finally clause\")\n\n\n# -\n\ndivide(2,5)\n\ndivide(5,0)\n\n# Q3\n''' we catch exceptions and handle them using try and except code blocks.\n The try clause contains the code that can raise an exception,\n while the except clause contains the code lines that handle the exception.'''\n#example\ntry: \n a = [\"Python\", \"Exceptions\", \"try and except\"]\n for i in range( 4 ): \n print( \"The index and element from the array is\", i, a[i] ) \nexcept: \n print (\"Index out of range\") \n\n# +\n# Q4\n'(a)'\n'''The try block lets you test a block of code for errors.\n The else block lets you execute code when there is no error.'''\n# there is one more which is except: The except block lets you handle the error\n#example\ntry:\n f= open(\"text1.txt\",'r')\n f.write(\"this is my msg\")\n \nexcept Exception as e:\n print(\"there is issue in my code\", e)\nelse:\n f.close()\n print(\"this block will execute once try will exceute itself without an exception\")\n\n\n# +\ntry:\n f= open(\"text.txt\",'w')\n f.write(\"this is my msg\")\n \nexcept Exception as e:\n print(\"there is some issue with my code\", e)\nelse:\n f.close()\n print(\"this block will execute once try will exceute itself without an exceotion\")\n# -\n\n#(B)\n'''The finally block will be executed regardless if the try block raises an error or not.'''\n#example\ntry:\n f = open(\"file.txt\", 'w')\n \n f.write(\"lotus lake\")\nexcept:\n print(\"Something went wrong when writing to the file\")\nfinally:\n print(\"this is end\")\n f.close()\n\n\ntry:\n f = open(\"file.txt\", 'r')\n \n f.read(\"lotus lake\")\nexcept:\n print(\"Something went wrong when writing to the file\")\nfinally:\n print(\"this is end\")\n f.close()\n# in both case (error or not) the finally in executed\n\n# +\n#(C)\n'''Raise Keyword is used to raise exceptions or errors.\n The raise keyword raises an error and stops the control flow of the program.'''\n#example\ns = 'apple'\n \ntry:\n num = int(s)\nexcept ValueError:\n raise ValueError(\"String can't be changed into integer\")\n\n\n# +\n#Q5\n'''Custom exception mean an Exception object that can include extra data about the cause of the error:\na string, maybe also some other arbitrary object relevant to the exception.'''\n# need of custom exception\n'''Built-in exceptions offer information about Python-related problems,\n and custom exceptions will add information about project-related problems.\n That way, you can design your code in a way that combines Python code with the language of the project.'''\nclass validateage(Exception):\n def __init__(self, msg):\n self.msg=msg\n \n \ndef validate_age(age):\n if age < 10:\n raise validateage(\"age should not be lesser then zero\")\n elif age>65:\n raise validateage(\"age is too high\")\n else:\n print(\"age is valid\")\ntry:\n age = int(input(\"enter your age\"))\n validate_age(age)\nexcept validateage as e:\n print(e)\n\n\n# +\n# Q6\nclass class1(Exception):\n def __init__(self, name):\n self.name = name\n \ndef class_pw(degree):\n if degree == \"Bachelor degree\" or degree == \"Master degree\" or degree==\"phd\":\n raise class1(\"Qualified\")\n else:\n print (\"Disqualified\")\ntry:\n degree = input(\"enter your highest degree name (as Bachelor , master degree or phd)\")\n class1(degree)\nexcept class1 as f:\n print(f)\n# -\n\n\n","repo_name":"amankumarmaurya928/python-29-jan","sub_path":"12 feb.ipynb","file_name":"12 feb.ipynb","file_ext":"py","file_size_in_byte":4478,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"20"} +{"seq_id":"14436673596","text":"# Predicting post-peak light-curve evolution using pre-peak data\n\n# +\nimport time \nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom scipy import stats\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\n\nimport tensorflow as tf\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Activation, Dropout, LeakyReLU\n\nsns.set_style('darkgrid')\ndf = pd.read_csv('lc_gp.csv', index_col='ztfname')\n\n\n# -\n\nclass PredictLC:\n def __init__(self, df):\n self.df = df\n self.predict_range = [0, 15]\n self.X = self.get_inputs()\n g_targets = df.columns[13+self.predict_range[0]:13+self.predict_range[1]]\n r_targets = df.columns[46:46+self.predict_range[1]]\n targets = np.append(g_targets.values, r_targets.values)\n self.models = dict(zip(targets, [None]*len(targets)))\n self.y_test_names = None\n \n self.model_pipeline()\n \n def get_inputs(self):\n data = self.df.drop(['t0g', 't0r', 'Av', 'z'], axis=1)\n gd = data.iloc[:, :13]\n rd = data.iloc[:, 33:46]\n dfx = pd.concat([gd, rd], axis=1)\n\n x_norm = dfx.values.flatten().min()\n x_mean = dfx.values.flatten().mean()\n return (dfx-x_mean)/(x_norm-x_mean)\n \n def generate_model(self, phase):\n tf.random.set_seed(42)\n y = self.df[phase]\n cond = (self.df.g0 < -18.5) & (self.df.g0 > -20)\n Xd, yd = self.X[cond], y[cond]\n X_, X_t, y_, y_t = train_test_split(Xd, yd, test_size=0.15, random_state=24)\n self.y_test_names = y_t.index.values\n X_train, X_test, y_train, y_test = X_.values, X_t.values, y_.values, y_t.values\n model = Sequential()\n l_r, b_1, b_2, eps, lrelu = (0.0009, 0.9, 0.999, 1e-8, 0.01)\n activation = LeakyReLU(lrelu)\n\n model.add(Dense(len(self.X.columns), activation=activation))\n model.add(Dense(48,activation=activation))\n model.add(Dropout(0.2))\n model.add(Dense(32,activation=activation))\n model.add(Dropout(0.1))\n model.add(Dense(16,activation=activation))\n model.add(Dense(1,activation='linear'))\n\n\n optimizer = Adam(\n learning_rate=l_r,\n beta_1=b_1,\n beta_2=b_2,\n epsilon=eps,\n amsgrad=False)\n\n model.compile(optimizer=optimizer,loss='mse')\n model.fit(x=X_train, y=y_train,\n validation_data=(X_test, y_test),\n batch_size=64,epochs=400, verbose=0)\n predictions = model.predict(X_test)\n print(f'Phase: {phase}, RMSE: {np.sqrt(np.mean((predictions-y_test)**2))}')\n \n errors = y_test - predictions.flatten()\n offset = stats.norm.fit(errors)[0]\n self.models[phase] = [model, offset]\n \n def model_pipeline(self):\n for phase in self.models.keys():\n self.generate_model(phase)\n \n \n def lc_pred(self, sn_name):\n if type(sn_name) == int:\n sn_name = self.y_test_names[sn_name]\n else:\n print('(!)Model trained on this LC(!)')\n early_lc = self.X.loc[sn_name]\n forcast = np.zeros(len(self.models))\n \n for i, key in enumerate(self.models.keys()):\n model, offset = self.models[key]\n forcast[i] = model.predict(np.expand_dims(early_lc, axis=0)) + offset\n \n lc = df.drop(['t0g', 't0r', 'Av', 'z'], axis=1).loc[sn_name]\n g_calli = lc.gm1 - forcast[0]\n r_calli = lc.r0 - forcast[self.predict_range[1]]\n g_pred = forcast[:self.predict_range[1]] + g_calli\n r_pred = forcast[self.predict_range[1]:] + r_calli\n \n fig, (ax1, ax2) = plt.subplots(figsize=(12, 12), nrows=2)\n x_lc = np.arange(-12, self.predict_range[1]+1)\n \n ax1.plot(x_lc, lc[:13+self.predict_range[1]], 'g.-', label='observed LC')\n ax2.plot(x_lc, lc[33:46+self.predict_range[1]], 'r.-', label='observed LC')\n ax1.plot(x_lc[:13], lc[:13], marker='s', linestyle='', color='g', \n markersize=7, label='training data')\n ax2.plot(x_lc[:13], lc[33:46], marker='s', linestyle='', color='r', \n markersize=7, label='training data')\n ax1.plot(x_lc[13:], g_pred, color='black', marker='o', linestyle='', \n label=f'predicted LC') # , shift: {g_calli:.2f}\n ax2.plot(x_lc[13:], r_pred, color='black', marker='o', linestyle='', \n label=f'predicted LC, shift: {r_calli:.2f}')\n ax1.invert_yaxis()\n ax2.invert_yaxis()\n ax1.legend()\n ax2.legend()\n return forcast\n\nann = PredictLC(df)\n\nann.lc_pred(15)\n\n\n","repo_name":"RobertSenzel/Summer-Research-Supernovae","sub_path":"machine_learning_2.ipynb","file_name":"machine_learning_2.ipynb","file_ext":"py","file_size_in_byte":4766,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"41116142142","text":"# # 1. Import Libarary\n\n# +\n# # !pip install jcopml --q #install jcopml sebagai library tambahan\n\n# Basic\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# SKlearn\nfrom sklearn import preprocessing\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.model_selection import train_test_split, GridSearchCV\nfrom sklearn.metrics import confusion_matrix, classification_report\nfrom keras.wrappers.scikit_learn import KerasClassifier\nfrom sklearn.neural_network import MLPClassifier\n\n# JCOP ML\nfrom jcopml.plot import plot_missing_value\nfrom jcopml.pipeline import num_pipe, cat_pipe\nfrom jcopml.tuning import grid_search_params as gsp\n# from jcopml.feature_importance import mean_score_decrease\n\n# Tensorflow\nfrom tensorflow.keras.optimizers import SGD, RMSprop, Adagrad, Adadelta, Adam, Adamax, Nadam\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.models import Sequential, Model\nfrom tensorflow.keras.layers import Dense, Dropout\nfrom keras.constraints import maxnorm\n\n# ignore warning\nimport warnings\nwarnings.filterwarnings('ignore')\nwarnings.filterwarnings(action=\"ignore\", message=\"^internal gelsd\")\n# -\n\n# # 2. Data Loading\n\n# ## 2.1 Import Data\n\ndata = pd.read_csv('telco-customer-churn.csv')\ndf = data.copy()\n\n# ## 2.2 BackUp Data\n\ndf = df.drop('customerID', axis=1)\n\ndf.head()\n\n# ## 2.3 Check Missing Value\n\nplot_missing_value(df)\n\n# `tidak terlihat adanya` missing value `, namun harus diwaspadai pada `Fitur Kategorik` dimana ada data kosong berbentuk string ' ', sehingga data harus diisi dengan modus dari setiap fitur` \n\ndf.loc[df['TotalCharges'] == ' '].head()\n\n# `contoh data kosong ' ' pada fitur TotalCharges`\n\n# ## 2.4 Replace Data\n\ntotal_charges = df['TotalCharges']\ndf = df.drop('TotalCharges', axis=1)\n\n# `Fitur TotalCharges dipisahkan karena diduga kuat memiliki data kosong ' '`\n\n# ##### Split Data (Numerik and Kategorik)\n\nkategorik = [ i for i in df.columns if df[i].dtype =='O']\nnumerik = [i for i in df.columns if df[i].dtype !='O']\nprint('tipe data kategorik:',kategorik, '\\n')\nprint('tipe data numerik:',numerik)\n\nfor x in df[numerik].columns:\n df[numerik][x] = np.where(df[numerik][x] == ' ', df[x].median(), df[numerik][x])\n\n# `data numerik tidak akan diproses karena jika data numerik memiliki data kosong ' ', maka akan terdeteksi sebagai missing value`\n\nfor x in df[kategorik].columns:\n df[kategorik][x] = np.where(df[kategorik][x] == ' ', df[kategorik][x].mode(), df[kategorik][x])\n\n# `memastikan semua data kategorik tidak memiliki data kosong ' ', sehingga jika ada data kosong maka akan diganti dengan modus dari setiap fitur`\n\ntotal_charges = np.where(total_charges == ' ', total_charges.mode()[1], total_charges)\n\n# `mengganti data kosong pada fitur TotalCharges menjadi modus`\n\n# #### Combine All Data\n\ndf['TotalCharges'] = total_charges\n\n# ## 2.5 Check Data Type\n\ndf.info()\n\n# - `Fitur `TotalCharges` akan diubah float sehinga dapat diolah lebih lanjut`\n\ndf['TotalCharges'] = df['TotalCharges'].astype('float')\n\n# # 3. Exploratory Data Analysis\n\nax = sns.countplot('Churn', data = df)\n# ax.bar_label(container=ax.containers[0])\n\n# `berdasarkan data, Customer `tetap / setia lebih banyak (5174) ` dibanding dengan customer yang ` pindah (1869)\n\nplt.figure(figsize=(20,8))\nsns.countplot('tenure', data = df, hue = 'Churn')\n\n# - `banyak customer yang pindah setelah bulan pertama, sehingga diperlukan pemeriksaan lebih lanjut`\n# - `Costumer churn rate akan terus berkurang seiring penpanjangan service`\n# - `setelah masuk bulan ke 70, costumer akan semakin setia`\n\n# +\ncat_var = ['gender', 'Contract', 'StreamingMovies', 'PhoneService', 'InternetService', 'StreamingTV', 'OnlineSecurity', 'DeviceProtection', 'TechSupport']\n\nfig, axes = plt.subplots(3,3, figsize=(15,15))\n\nfor cat, ax in zip(cat_var, axes.flatten()):\n sns.countplot(cat, data=df, hue='Churn', ax= ax)\n# -\n\n# - `berdasarkan plot, lebih dari` 50% customer `baik laki-laki maupun perempuan menjadi pelanggan tetap dan menikmati beberapa produk yang ditawarkan`\n# - `berdasarkan` contract `,lebih banyak customer yang memilih` month-to-month `, biasanya adalah pelanggan yang baru mencoba produk dan `40% dari customer ` month-to-month ` meniggalkan ` service kita pada bulan pertamanya`\n\n# +\nplt.figure(figsize=(20,5))\n\nplt.subplot(1,2,1)\nsns.boxplot(x = df['MonthlyCharges'])\n\nplt.subplot(1,2,2)\nsns.boxplot(x = df['TotalCharges'])\n# -\n\n# tidak ada outliers `pada fitur MonthlyCharges dan TotalCharges`\n\n# # 4. Preprocessing Data\n\n# ## 4.1 Data Splitting\n\n# +\nX = df.drop('Churn', axis=1)\ny = df['Churn']\n\nX_train_full, X_test, y_train_full, y_test = train_test_split(X, y, stratify=y, test_size=0.1, random_state=42) #train\nX_train, X_valid, y_train, y_valid = train_test_split(X_train_full, y_train_full, random_state=42) #train val\n# -\n\n# ## 4.2 Data Encoding\n\n# +\npreprocessor = ColumnTransformer([\n ('cat_1', cat_pipe(encoder='onehot'), ['MultipleLines','InternetService','OnlineSecurity', 'OnlineBackup', 'DeviceProtection', 'TechSupport','StreamingTV','StreamingMovies','Contract','PaymentMethod']),\n ('cat_2', cat_pipe(encoder='ordinal'), ['gender','Partner','Dependents', 'PhoneService', 'PaperlessBilling']),\n ('num', num_pipe(scaling = 'minmax'), ['SeniorCitizen', 'tenure','MonthlyCharges','TotalCharges'])\n])\n\ndef label_x():\n preprocessor.fit(X_train)\n return preprocessor.transform(X_train), preprocessor.transform(X_test), preprocessor.transform(X_valid)\n\ndef label_y():\n label = preprocessing.LabelEncoder()\n label.fit(y_train)\n return label.transform(y_train), label.transform(y_test), label.transform(y_valid)\n\nX_train_new, X_test_new, X_valid_new = label_x()\ny_train_new, y_test_new, y_valid_new = label_y()\n\n\n# -\n\n# # 5. Data Modelling\n\n# ## 5.1 Extract & Transform Process\n\ndef ET(train, test):\n return tf.data.Dataset.from_tensor_slices((train, test)).shuffle(buffer_size=16).batch(8)\n\n\ntrain_dataset = ET(X_train_new, y_train_new)\ntest_dataset = ET(X_test_new, y_test_new)\nvalid_dataset = ET(X_valid_new, y_valid_new)\n\n\n# ## 5.2 Load Process & Data Architecture\n\n# +\ndef model(): \n data_input = tf.keras.Input(shape= 40)\n hidden = tf.keras.layers.Dense(8, activation = 'relu', name= 'hidden_1')(data_input)\n # hidden = tf.keras.layers.Dense(8, activation = 'relu', name= 'hidden_2')(hidden)\n output_lay = tf.keras.layers.Dense(1, activation = 'sigmoid', name= 'predict')(hidden)\n\n model = Model(inputs = data_input, outputs = output_lay)\n \n model.compile(loss = 'binary_crossentropy', #untuk binary classification\n optimizer='adam',\n metrics=['accuracy'])\n \n return model\n\ndef running():\n # run the model\n run = model()\n history = run.fit(train_dataset, epochs = 30, batch_size= 8, validation_data=(valid_dataset))\n return run, history\n\ndef grafik(data):\n # show the graph\n metrics = pd.DataFrame(data.history)\n return metrics[['loss', 'val_loss']].plot(), metrics[['accuracy', 'val_accuracy']].plot();\n\n\n# -\n\n# # 5.2 Compiling and Fitting Model\n\nrun, history = running()\n\ngrafik(history)\n\n# ## 5.3 Prediction\n\nres = run.predict(X_test_new)\nres_1 = (res > 0.5)\nres_1_1 = np.where(res >= 0.5, 'no', 'yes')\npd.DataFrame(res_1_1).transpose()\n\n\ncm = confusion_matrix(y_test_new, res_1)\ncr = classification_report(y_test_new, res_1)\nprint('Classification Report')\nprint(cr,'\\n \\n')\nprint('Confusion Matrix')\ncm\n\n\n# # 6. Parameter Tuning\n\n# ## 6.1 Using Grid Search\n\n# +\n# good_model = KerasClassifier(build_fn=model, verbose=0)\n\n# # define the grid search parameters\n# batch_size = [10, 40, 80, 100]\n# epochs = [10, 50, 100]\n\n# param_grid = dict(batch_size = batch_size, epochs=epochs)\n# grid = GridSearchCV(estimator = good_model, param_grid=param_grid, n_jobs=-1, cv=3)\n# grid_result = grid.fit(X_train_new, y_train_new)\n\n# # summarize results\n# print(\"Best: %f using %s\" % (grid_result.best_score_, grid_result.best_params_))\n\n# +\n# good_model = KerasClassifier(build_fn=model_coba, epochs=40, batch_size=10, verbose=0)\n# # define the grid search parameters\n# optimizer = ['SGD', 'Adam', 'Nadam']\n\n# learn_rate = [0.001, 0.01, 0.1, 0.2, 0.3]\n# momentum = [0.0, 0.2, 0.4, 0.6, 0.8, 0.9]\n\n# init_mode = ['uniform', 'lecun_uniform', 'normal', 'zero', 'glorot_normal', 'glorot_uniform', 'he_normal', 'he_uniform']\n\n# weight_constraint = [1, 2, 3, 4, 5]\n# dropout_rate = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]\n\n# neurons = [1,2]\n\n# param_grid = dict(\n# # Training Optimizer\n# optimizer=optimizer,\n \n# # Learning Rate and Momentum\n# learn_rate=learn_rate, momentum=momentum,\n \n# # Network Weight Initialization\n# init_mode=init_mode,\n \n# # Dropout Regularization\n# dropout_rate=dropout_rate, weight_constraint=weight_constraint,\n \n# # Number of Neurons in the Hidden Layer\n# neurons=neurons\n# )\n# grid = GridSearchCV(estimator=good_model, param_grid=param_grid, n_jobs=-1, cv=3)\n# grid_result = grid.fit(X_train, y_train)\n\n# # summarize results\n# print(\"Best: %f using %s\" % (grid_result.best_score_, grid_result.best_params_))\n# -\n\n# ### `saya tidak merekomendasikan menggunakan grid search jika anda sedang terburu - buru karena terlalu banyak menghabiskan resources`\n\n# ## 6.2 Trial and Error\n\n# +\ndef model_baru(activation_hidden, optim, learn_ra, DO, epo, basi):\n model = Sequential()\n model.add(Dense(64, activation = activation_hidden, name= 'hidden_1', input_shape=(40,)))\n model.add(Dropout(DO))\n # model.add(keras.layers.BatchNormalization()),\n \n model.add(Dense(16, activation = activation_hidden, name= 'hidden_2'))\n model.add(Dropout(DO))\n # model.add(keras.layers.BatchNormalization()),\n \n model.add(Dense(8, activation = activation_hidden, name= 'hidden_3'))\n model.add(Dropout(DO))\n model.add(keras.layers.BatchNormalization())\n \n model.add(Dense(1, activation = 'sigmoid', name= 'predict'))\n \n opt = optim(lr=learn_ra)\n model.compile(loss = 'binary_crossentropy', #untuk binary classification\n optimizer= opt,\n metrics=['accuracy'])\n \n run = model\n history = model.fit(train_dataset, epochs = epo, batch_size= basi, validation_data=(valid_dataset))\n return run, history\n\n\ndef grafik(data):\n # show the graph\n metrics = pd.DataFrame(data.history)\n return metrics[['loss', 'val_loss']].plot(), metrics[['accuracy', 'val_accuracy']].plot();\n\n\n# -\n\n# Contoh :\n#\n# - activation = ['softmax', 'softplus', 'softsign', 'relu', 'tanh', 'sigmoid', 'hard_sigmoid', 'linear']\n# - init_mode = ['uniform', 'lecun_uniform', 'normal', 'zero', 'glorot_normal', 'glorot_uniform', 'he_normal', 'he_uniform']\n# - weight_constraint = [1, 2, 3, 4, 5]\n# - dropout_rate = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]\n# - optimizer = ['SGD', 'RMSprop', 'Adagrad', 'Adadelta', 'Adam', 'Adamax', 'Nadam']\n# - learn_rate = [0.001, 0.01, 0.1, 0.2, 0.3]\n# - momentum = [0.0, 0.2, 0.4, 0.6, 0.8, 0.9]\n\nrun2, history2 = model_baru(activation_hidden = 'relu',\n optim = Adam,\n learn_ra = 0.0001,\n DO = 0.3, \n epo = 16, \n basi = 8)\n\ngrafik(history2)\n\nres2 = run2.predict(X_test_new)\nres_2 = (res2 > 0.5)\nres_2_2 = np.where(res2 >= 0.5, 'no', 'yes')\npd.DataFrame(res_2_2).transpose()\n\n# +\ncm2 = confusion_matrix(y_test_new, res_2)\ncr2 = classification_report(y_test_new, res_2)\n# print('Classification Report Before Tuning\\n', cr,'\\n \\n')\nprint('Classification Report After Tuning\\n', cr2,'\\n \\n')\n\n# print('Confusion Matrix Before Tuning\\n', cm)\nprint('Confusion Matrix After Tuning\\n', cm2)\n\n# -\n\n# `tidak ada perbedaan sebelum dan sesudah di tuning`\n\n# ## 6.3 MLPClassifier\n\n# +\npipeline = Pipeline([\n ('prep', preprocessor),\n ('mlp', MLPClassifier(random_state=42))\n])\n\nparameter = {\n \"mlp__alpha\": [0.0001, 0.0003, 0.001, 0.003],\n \"mlp__hidden_layer_sizes\": [(16,), (32, 16), (32, 16, 8)],\n \"mlp__learning_rate_init\": [0.001, 0.005, 0.01],\n \"mlp__learning_rate_init\": [0.001, 0.01, 0.1, 0.2],\n \"mlp__activation\": [\"relu\", \"logistic\", \"tanh\"]\n}\n\nmodel = GridSearchCV(pipeline, parameter, cv=3, n_jobs=-1, verbose=1)\nmodel.fit(X_train, y_train)\n\nprint(model.best_params_)\nprint(model.score(X_train, y_train), model.best_score_, model.score(X_test, y_test))\n\n# +\n# df_imp = mean_score_decrease(X_train, y_train, model, plot=True)\n# -\n\n# # 7 Model Inference\n\n# ## 7.1 Basic Model\n\n# untuk memperoleh data baru, disini saya menyatukan 100 data dari setiap data X kemudian membuat fungsi random untuk mendapatkan 10 data baru.\n\n# +\ntrainx = pd.DataFrame(X_train_new)\ntestx = pd.DataFrame(X_test_new)\nvalx = pd.DataFrame(X_valid_new)\n\ntesting = pd.concat([trainx.sample(100), testx.sample(100), valx.sample(100)], ignore_index = True)\ndummy = testing.sample(10)\n# -\n\n# melakukan proses prediksi menggunakan data baru\n\nmodel_pred = run.predict(dummy)\n# model_pred_data = (model_pred > 0.5)\nmodel_pred_1 = np.where(model_pred >= 0.5, 'yes', 'no')\npd.DataFrame(model_pred_1).transpose()\n\n# ## 7.2 MLPClassifier Model\n\n# +\ntrainx = pd.DataFrame(X_train)\ntestx = pd.DataFrame(X_test)\nvalx = pd.DataFrame(X_valid)\n\ntesting = pd.concat([trainx.sample(100), testx.sample(100), valx.sample(100)], ignore_index = True)\ndummy = testing.sample(10, random_state= 42)\n# -\n\nmodel_pred2 = model.predict(dummy)\npd.DataFrame(model_pred2).transpose()\n\n# # 9. Conclusion\n\n# ## 9.1 EDA Analysis\n#\n# - `berdasarkan analisis lebih dari ` 50% customer ` baik laki-laki maupun perempuan menyukai produk yang ditawarkan dan menjadi pelanggan tetap`\n# - `Costumer churn rate akan terus berkurang seiring customer melakukan penpanjangan service yang artinya customer menyukai produk yang ditawarkan`\n# - `diperlukan analisis lebih lanjut pada bulan pertama ketika customer berlangganan, dimana lebih dari 350 customer churn pada bulan pertama mereka berlangganan`\n\n# ## 9.2 Model Analysis\n#\n# - `Basic model` (1 hidden layer dan 30 neuron serta epoch = 10 dan batch_size = 8) ` memiliki model yang tidak overfit dan accuracy yang lumayan baik dimana nilai accuracy adalah 0.80`\n#\n# - `Parameter Tuning bisa dilakukan dengan 3 cara, Keras Library, Trial and Error, dan Scikit Learn`\n#\n# - `kombinasi parameter yang digunakan pada Trial and Error adalah sebagi berikut:`\n# - Batch = 8\n# - Epoch = 16\n# - Training Optimizer = Adam\n# - Hidden Layer = 3\n# - Learning Rate = 0.0001\n# - Dropout Rate = 0.3\n# - Activation func (hidden layer) = relu\n# - Activation func (output layer) = sigmoid\n#\n# - `Dengan membandingkan 3 model yang telah digunakan (Basic Model, Trial and Error, dan Skicit Learn), didapatkan bahwa model Scikit Learn dan basic model adalah model terbaik, keduanya tidak memiliki perbedaan loss yang significant`\n#\n# - `Menggunakan Skicit Learn sebenarnya bisa dilakukan, namun memiliki banyak keterbatasan dalam Deep Learning, salah satunya adalah tidak bisa meng``handle`` dataset dengan jumlah yang banyak (bigdata)`\n\n#\n","repo_name":"rizanias/Telco_Customer_Churn_Prediction","sub_path":"presentation.ipynb","file_name":"presentation.ipynb","file_ext":"py","file_size_in_byte":15519,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"28383045847","text":"# # 👩🏻‍💻 freeCodeCamp: Demographic Data Analyzer\n#\n# In this challenge you must analyze demographic data using Pandas. You are given a dataset of demographic data that was extracted from the 1994 Census database. Here is a sample of what the data looks like:\n#\n# You must use Pandas to answer the following questions:\n#\n# 1. How many people of each race are represented in this dataset? This should be a Pandas series with race names as the index labels. (race column)\n# 2. What is the average age of men?\n# 3. What is the percentage of people who have a Bachelor's degree?\n# 4. What percentage of people with advanced education (Bachelors, Masters, or Doctorate) make more than 50K?\n# 5. What percentage of people without advanced education make more than 50K?\n# 6. What is the minimum number of hours a person works per week?\n# 7. What percentage of the people who work the minimum number of hours per week have a salary of more than 50K?\n# 8. What country has the highest percentage of people that earn >50K and what is that percentage?\n# 9. Identify the most popular occupation for those who earn >50K in India.\n#\n# Link: [https://www.freecodecamp.org/learn/data-analysis-with-python/data-analysis-with-python-projects/demographic-data-analyzer](https://www.freecodecamp.org/learn/data-analysis-with-python/data-analysis-with-python-projects/demographic-data-analyzer)\n\nimport pandas as pd\nimport numpy as np\n\n# +\ndf = pd.read_csv(\"/Users/katiehuang/Documents/Data Science/Projects/Demographic Data Analyzer/adult_data.csv\")\n\ndf.head()\n# -\n\n# ## 1. How many people of each race are represented in this dataset? This should be a Pandas series with race names as the index labels. (race column)\n#\n#\n\nrace_count = df[\"race\"].value_counts()\nrace_count\n\n# ## 2. What is the average age of men?\n\n# +\navg_age = round(df[df[\"sex\"] == \"Male\"][\"age\"].mean(),1)\n\nprint(f\"The average age of men is {avg_age} years old.\")\n# -\n\n# ## 3. What is the percentage of people who have a Bachelor's degree?\n#\n#\n\n# +\nbachelors = df[df.education == 'Bachelors']\n\nbachelors_pct = round(len(bachelors) / len(df),2)\nbachelors_pct\n\nprint(f\"{bachelors_pct * 100}% of people has a Bachelor's degree.\")\n# -\n\n# ## 4. What percentage of people with advanced education (Bachelors, Masters, or Doctorate) make more than 50K?\n\n# +\n# Find dfs with Bachelors, Masters, or Doctorate education\nhigher_education = df[df['education'].isin(['Bachelors', 'Masters', 'Doctorate'])]\n\n# Find dfs with Bachelors, Masters, or Doctorate education earning > 50k\nhigher_education_pct = round(len(higher_education[higher_education['salary'] == '>50K']) / len(higher_education),1)\n\nprint(f\"{adv_education_pct * 100}% of people with advanced education (Bachelors, Masters, or Doctorate) makes more than $50K.\")\n# -\n\n# ## 5. What percentage of people without advanced education make more than 50K?\n#\n#\n\n# +\n# Create a df without Bachelors, Masters, or Doctorate education\nlower_education = df[~df['education'].isin(['Bachelors', 'Masters', 'Doctorate'])]\n\n# Filter in lower_education earning > 50k then, divide by no. of rows in lower_education\nlower_education_pct = round(len(lower_education[lower_education['salary'] == '>50K']) / len(lower_education),1)\n\nprint(f\"{no_adv_education_pct * 100}% of people without advanced education makes more than $50K.\")\n# -\n\n# ## 6. What is the minimum number of hours a person works per week?\n#\n#\n\n# +\n# 'hours-per-week' represents number of hours worked in a week. Find the minimum hours in the field.\nmin_hours_work = df[\"hours-per-week\"].min()\n\nprint(f\"The minimum number of hours a person works per week is {min_hours_work} hour(s).\")\n# -\n\n# ## 7. What percentage of the people who work the minimum number of hours per week have a salary of more than 50K?\n#\n#\n\n# +\nmin_hours = df[df[\"hours-per-week\"] == min_hours_work]\n\nmin_hours_pct = round(len(min_hours[min_hours[\"salary\"] == \">50K\"]) / len(df),4)\n\nprint(f\"{min_hours_pct * 100}% of people who work the minimum number of hours per week have a salary of more than 50K.\")\n# -\n\n# ## 8. What country has the highest percentage of people that earn >50K and what is that percentage?\n\n# +\n# Find the number of countries\ncountry_count = len(df)\n\n# Find the number of countries where people earn > $50k\nrich_country_count = df[df['salary'] == '>50K']['native-country'].value_counts()\n\nhighest_earning_country = (rich_country_count / country_count * 100).idxmax()\nhighest_earning_country_percentage = round((rich_country_count / country_count * 100).max(),1)\n\n# .idxmax() returns the index for the maximum value in each column\n# Reference: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.idxmax.html\n\nprint(f\"{highest_earning_country} has the highest percentage of people that earn more than $50K at {highest_earning_country_percentage}%.\")\n# -\n\n# ## 9. Identify the most popular occupation for those who earn >50K in India.\n\n# +\n# Create df with India only\nindia = df[df['native-country'] == 'India']\n\n# Find number of people in India earning > 50k grouped by occupation and find the max value\nindia_popular_occupation = india[india['salary'] == '>50K']['occupation'].value_counts().idxmax()\n\nprint(f\"{india_popular_occupation} is the most popular occupation for those who earn >$50K in India.\")\n","repo_name":"katiehuangx/freeCodeCamp-Projects","sub_path":"Demographic Data Analyser/Demographic Data Analyzer.ipynb","file_name":"Demographic Data Analyzer.ipynb","file_ext":"py","file_size_in_byte":5256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"38284013301","text":"# # 分类器的不确定度估计\n# ---\n# scikit-learn接口的一个有用之处就是分类器能够给出预测的不确定度估计。一般来说,你感兴趣的不仅是分类器会预测一个测试点属于哪个类别,还包括它对这个预测的置信程度。在实践中,不同类型的错误会在现实应用中导致非常不同的结果。想象一个用于测试癌症的医疗应用。假阳性预测可能只会让患者接受额外的测试,但假阴性预测却可能导致重病没有得到治疗。scikit-learn中有两个函数可用于获取分类器的不确定度估计:decision_function和predict_proba。大多数分类器(但不是全部)都至少有其中一个函数,很多分类器两个都有。\n\n# +\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport mglearn\nfrom sklearn.model_selection import train_test_split\n\nimport seaborn as sns\nsns.set(style = \"white\")\n# -\n\n# 构建一个GradientBoostingClassifier分类器(同时拥有decision_function和predict_proba),查看这两个函数对一个模拟二维数据集的作用:\n\n# +\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.datasets import make_circles\n\nX, y = make_circles(noise=0.25, factor=0.5, random_state=1)\n# 为了便于说明,我们将两个类别重命名为\"blue\"和\"red\"\ny_named = np.array([\"blue\", \"red\"])[y]\n# 我们可以对任意个数组调用train_test_split\n# 所有数组的划分方式都是一致的\nX_train, X_test, y_train_named, y_test_named, y_train, y_test = train_test_split(\n X, y_named, y, random_state=0)\n# 构建梯度提升模型\ngbrt = GradientBoostingClassifier(random_state=0)\ngbrt.fit(X_train, y_train_named)\n# -\n\n# ## 决策函数\n# ---\n# 对于二分类的情况,decision_function返回值的形状是(n_samples,),为每个样本都返回一个浮点数:\n\nprint(\"X_test.shape: {}\".format(X_test.shape))\nprint(\"Decision function shape: {}\".format(gbrt.decision_function(X_test).shape))\n\n# 对于类别1来说,这个值表示模型对该数据点属于“正”类的置信程度。正值表示对正类的偏好,负值表示对“反类”(其他类)的偏好:\n\n# 显示decision_function的前几个元素\nprint(\"Decision function:\\n{}\".format(gbrt.decision_function(X_test)[:6]))\n\n# 通过仅查看决策函数的正负号来再现预测值:\nprint(\"Thresholded decision function:\\n{}\".format(\n gbrt.decision_function(X_test) > 0))\nprint(\"Predictions:\\n{}\".format(gbrt.predict(X_test)))\n\n# 对于二分类问题,“反”类始终是classes_属性的第一个元素,“正”类是classes_的第二个元素。利用classes_属性可以完全再现predict的输出:\n\n# 将布尔值True/False转换成0和1\ngreater_zero = (gbrt.decision_function(X_test) > 0).astype(int)\n# 利用0和1作为classes_的索引\npred = gbrt.classes_[greater_zero]\n# pred与gbrt.predict的输出完全相同\nprint(\"pred is equal to predictions: {}\".format(\n np.all(pred == gbrt.predict(X_test))))\n\n# decision_function可以在任意范围取值,这取决于数据与模型参数:\n\ndecision_function = gbrt.decision_function(X_test)\nprint(\"Decision function minimum: {:.2f} maximum: {:.2f}\".format(\n np.min(decision_function), np.max(decision_function)))\n\n# 由于可以任意缩放,因此decision_function的输出往往很难解释。\n\n# 利用颜色编码在二维平面中画出所有点的决策函数及决策边界。我们将训练点画成圆,将测试数据画成三角。\nfig, axes = plt.subplots(1, 2, figsize=(13, 5))\nmglearn.tools.plot_2d_separator(gbrt, X, ax=axes[0], alpha=.4,\n fill=True, cm=mglearn.cm2)\nscores_image = mglearn.tools.plot_2d_scores(\n gbrt, X, ax=axes[1], alpha=.4, cm=mglearn.ReBl)\nfor ax in axes:\n # 画出训练点和测试点\n mglearn.discrete_scatter(X_test[:, 0], X_test[:, 1], \n y_test, markers='^', ax = ax)\n mglearn.discrete_scatter(X_train[:, 0], X_train[:, 1], \n y_train, markers='o', ax = ax)\n ax.set_xlabel(\"Feature 0\")\n ax.set_ylabel(\"Feature 1\")\ncbar = plt.colorbar(scores_image, ax=axes.tolist())\naxes[0].legend([\"Test class 0\", \"Test class 1\", \"Train class 0\", \"Train class 1\"], \n ncol=4, loc=(.1, 1.1))\n\n# 上图为梯度提升模型在一个二维玩具数据集上的决策边界(左)和决策函数(右)。既给出预测结果,又给出分类器的置信程度,这样给出的信息量更大。但在上面的图像中,很难分辨出两个类别之间的边界。\n\n# ## 预测概率\n# ---\n# predict_proba的输出是每个类别的概率,通常比decision_function的输出更容易理解。对于二分类问题,它的形状始终是(n_samples, 2):\n\nprint(\"Shape of probabilities: {}\".format(gbrt.predict_proba(X_test).shape))\n\n# 每行的第一个元素是第一个类别的估计概率,第二个元素是第二个类别的估计概率。由于predict_proba的输出是一个概率,因此总是在0和1之间,两个类别的元素之和始终为1:\n\n# 显示predict_proba的前几个元素\nprint(\"Predicted probabilities:\\n{}\".format(gbrt.predict_proba(X_test[:6])))\n\n# 由于两个类别的概率之和为1,因此只有一个类别的概率超过50%。这个类别就是模型的预测结果。\n#\n# 在上一个输出中可以看到,分类器对大部分点的置信程度都是相对较高的。不确定度大小实际上反映了数据依赖于模型和参数的不确定度。过拟合更强的模型可能会做出置信程度更高的预测,即使可能是错��。复杂度越低的模型通常对预测的不确定度越大。如果模型给出的不确定度符合实际情况,那么这个模型被称为校正(calibrated)模型。在校正模型中,如果预测有70%的确定度,那么它在70%的情况下正确。\n\n# 再次给出该数据集的决策边界,以及类别1的类别概率:\nfig, axes = plt.subplots(1, 2, figsize=(13, 5))\nmglearn.tools.plot_2d_separator(\n gbrt, X, ax=axes[0], alpha=.4, fill=True, cm=mglearn.cm2)\nscores_image = mglearn.tools.plot_2d_scores(\n gbrt, X, ax=axes[1], alpha=.5, cm=mglearn.ReBl, function = 'predict_proba')\nfor ax in axes:\n # 画出训练点和测试点\n mglearn.discrete_scatter(X_test[:, 0], X_test[:, 1], \n y_test,markers='^', ax=ax)\n mglearn.discrete_scatter(X_train[:, 0], X_train[:, 1], \n y_train,markers='o', ax=ax)\n ax.set_xlabel(\"Feature 0\")\n ax.set_ylabel(\"Feature 1\")\ncbar = plt.colorbar(scores_image, ax=axes.tolist())\naxes[0].legend([\"Test class 0\", \"Test class 1\", \"Train class 0\", \"Train class 1\"], \n ncol=4, loc=(.1, 1.1))\n\n# ## 多分类问题的不确定度\n# ---\n# decision_function和predict_proba也适用于多分类问题。\n\n# +\n# 应用于三分类鸢尾花(Iris)数据集:\nfrom sklearn.datasets import load_iris\n\niris = load_iris()\nX_train, X_test, y_train, y_test = train_test_split(\n iris.data, iris.target, random_state=42)\ngbrt = GradientBoostingClassifier(learning_rate=0.01, random_state=0)\ngbrt.fit(X_train, y_train)\nprint(\"Decision function shape: {}\".format(gbrt.decision_function(X_test).shape))\n# 显示决策函数的前几个元素\nprint(\"Decision function:\\n{}\".format(gbrt.decision_function(X_test)[:6, :]))\n# -\n\n# 对于多分类的情况,decision_function的形状为(n_samples, n_classes),每一列对应每个类别的“确定度分数”,分数较高的类别可能性更大,得分较低的类别可能性较小。你可以找出每个数据点的最大元素,从而利用这些分数再现预测结果。\n\nprint(\"Argmax of decision function:\\n{}\".format(\n np.argmax(gbrt.decision_function(X_test), axis=1)))\nprint(\"Predictions:\\n{}\".format(gbrt.predict(X_test)))\n\n# predict_proba输出的形状相同,也是(n_samples, n_classes)。同样,每个数据点所有可能类别的概率之和为1。\n\n# 显示predict_proba的前几个元素\nprint(\"Predicted probabilities:\\n{}\".format(gbrt.predict_proba(X_test)[:6]))\n# 显示每行的和都是1\nprint(\"Sums: {}\".format(gbrt.predict_proba(X_test)[:6].sum(axis=1)))\n\n# 通过计算predict_proba的argmax来再现预测结果:\nprint(\"Argmax of predicted probabilities:\\n{}\".format(\n np.argmax(gbrt.predict_proba(X_test), axis=1)))\nprint(\"Predictions:\\n{}\".format(gbrt.predict(X_test)))\n\n# predict_proba和decision_function的形状始终相同,都是(n_samples, n_classes)——除了二分类特殊情况下的decision_function。对于二分类的情况,decision_function只有一列,对应“正”类classes_[1]。这主要是由于历史原因。\n#\n# 如果有n_classes列,你可以通过计算每一列的argmax来再现预测结果。但如果类别是字符串,或者是整数,但不是从0开始的连续整数的话,一定要小心。如果你想要对比predict的结果与decision_function或predict_proba的结果,一定要用分类器的classes_属性来获取真实的属性名称:\n\n# +\nfrom sklearn.linear_model import LogisticRegression\n\nlogreg = LogisticRegression(solver = \"liblinear\")\n# 用Iris数据集的类别名称来表示每一个目标值\nnamed_target = iris.target_names[y_train]\nlogreg.fit(X_train, named_target)\nprint(\"unique classes in training data: {}\".format(logreg.classes_))\nprint(\"predictions: {}\".format(logreg.predict(X_test)[:10]))\nargmax_dec_func = np.argmax(logreg.decision_function(X_test), axis=1)\nprint(\"argmax of decision function: {}\".format(argmax_dec_func[:10]))\nprint(\"argmax combined with classes_: {}\".format(\n logreg.classes_[argmax_dec_func][:10]))\n# -\n\n# # 小结与展望\n# ---\n# 对一系列用于分类和回归的机器学习模型讨论其优点和缺点,以及如何控制它们的模型复杂度。我们发现,对于许多算法而言,设置正确的参数对模型性能至关重要。有些算法还对输入数据的表示方式很敏感,特别是特征的缩放。因此,如果盲目地将一个算法应用于数据集,而不去理解模型所做的假设以及参数设定的含义,不太可能会得到精度高的模型。\n#\n# ---\n# 已学习过的基础监督学习算法总结:\n# * 最近邻(KNN)\n# --适用于小型数据集,是很好的基准模型,很容易解释。\n# * 线性模型(LM)\n# --非常可靠的首选算法,适用于非常大的数据集,也适用于高维数据。\n# * 朴素贝叶斯(NB)\n# --只适用于分类问题。比线性模型速度还快,适用于非常大的数据集和高维数据。精度通常要低于线性模型。\n# * 决���树(DT)\n# --速度很快,不需要数据缩放,可以可视化,很容易解释。\n# * 随机森林(RF)\n# --几乎总是比单棵决策树的表现要好,鲁棒性很好,非常强大。不需要数据缩放。但不适用于高维稀疏数据。\n# * 梯度提升决策树(GBDT)\n# --精度通常比随机森林略高。与随机森林相比,训练速度更慢,但预测速度更快,需要的内存也更少。比随机森林需要更多的参数调节。\n# * 支持向量机(SVM)\n# --对于特征含义相似的中等大小的数据集很强大。需要数据缩放,对参数敏感。\n# * 神经网络(NN)\n# --可以构建非常复杂的模型,特别是对于大型数据集而言。对数据缩放及参数选取敏感。大型网络需要很长的训练时间。\n# ---\n# 面对新数据集,通常最好先从简单模型开始,比如线性模型、朴素贝叶斯或最近邻分类器,看能得到什么样的结果。对数据有了进一步了解之后,可以考虑用于构建更复杂模型,如随机森林、梯度提升决策树、SVM或神经网络。在不同的数据集上实验各种算法,可以更好地感受它们所需的训练时间、分析模型的难易程度以及它们对数据表示的敏感程度。虽然我们分析了不同的参数设定对算法的影响,但在生产环境中实际构建一个对新数据泛化性能很好的模型要更复杂一些。\n\n\n","repo_name":"StevenArthesTang/Supervised-Learning","sub_path":"8、分类器的不确定度估计.ipynb","file_name":"8、分类器的不确定度估计.ipynb","file_ext":"py","file_size_in_byte":12014,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"73687452227","text":"import tensorflow as tf\nimport onnxruntime as rt\nimport tf2onnx\nimport os\nimport pandas as pd\nfrom time import time\nimport numpy as np\nos.chdir('..')\nfrom MakeModelClassifier import MakeModelClassifier as mm\n\n# ## Instantiate MakeModelClassifier with 50% sample of Stanford car data\n\nconfig = {'img_df': '/Users/josephking/Documents/sponsored_projects/MERGEN/data/vehicle_classifier/stanford_car_data/Bboxes.csv',\n 'data': '/Users/josephking/Documents/sponsored_projects/MERGEN/data/vehicle_classifier/stanford_car_data',\n 'output': '/Users/josephking/Documents/sponsored_projects/MERGEN/scripts/output',\n 'logging': False,\n 'train': False,\n 'predict': True,\n 'weights': '/Users/josephking/Documents/sponsored_projects/MERGEN/output/MakeModelClassifier/2021-11-17-00h53/training_checkpoints',\n 'min_class_img_count': 0,\n 'pixel_dilation': 0,\n 'sample' : 0.5,\n 'seed': 123,\n 'img_size': (224, 224),\n 'batch_size': 32,\n 'model': 'resnet',\n 'resnet_size': '50',\n 'dropout': 0.2,\n 'units2': 4096,\n 'units1': 2048,\n 'optimizer': 'adam',\n 'learning_rate': 0.0001\n}\n\nmmc = mm(config)\n\n_, _, test = mmc.image_pipeline(predict=True)\n\nprint(test)\n\nprint(f'\\nNumber of test images: {len(mmc.df)}')\n\n# ## Predictions with Tensorflow Keras model\n\nlatest = tf.train.latest_checkpoint(config['weights'])\nkeras_model = mmc.build_compile_model()\nkeras_model.load_weights(latest)\n\nstart = time()\nkeras_predictions = keras_model.predict(test)\nprint(\"\\nTotal prediction time in seconds: {:.2f}\\n\".format((time()-start)))\n\n# ## Convert Keras weights to Onnx\n\n# +\nspec = (tf.TensorSpec(((None,) + mmc.config['img_size'] + (3,)), tf.float32, name=\"input\"),)\nonnx_path = os.path.join(mmc.config['weights'], 'model.onnx')\n\nstart = time()\nmodel_proto, _ = tf2onnx.convert.from_keras(keras_model, input_signature=spec, opset=13, output_path=onnx_path)\noutput_names = [n.name for n in model_proto.graph.output]\nprint(\"\\nTotal time spent converting weights in seconds: {:.2f}\\n\".format((time()-start)))\n# -\n\nprint(output_names)\n\n# ## Predictions with Onnx weights\n\n# #### Convert to Numpy array\n\nconverted_test = list(test.as_numpy_iterator())\n\narray = np.array(converted_test[0][0])\nfor i in range(1, len(converted_test)):\n array = np.concatenate((array, converted_test[i][0]), axis=0)\n\n# +\nonnx_model = rt.InferenceSession(onnx_path, providers=['CPUExecutionProvider']) # run on a MacBook with no GPU\n\nstart = time()\nonnx_pred = onnx_model.run(output_names, {\"input\": array})\nprint(\"\\nTotal prediction time in seconds: {:.2f}\\n\".format((time()-start)))\n# -\n\n# ## Compare softmax probabilities\n\nassert(keras_predictions.shape == onnx_pred[0].shape)\n\nnp.testing.assert_allclose(keras_predictions, onnx_pred[0], rtol=1e-5)\n\n# ## Compare argmax(0) between models\n\n# #### True labels\n\n# +\nimages, labels = tuple(zip(*test)) # Recover labels\n\nlabel_df = pd.DataFrame()\nfor x in range(len(labels)):\n label_df = pd.concat([label_df, pd.DataFrame(labels[x].numpy())], axis=0)\nlabel_df = label_df.reset_index(drop=True)\nlabel_series = label_df.idxmax(axis=1).astype(str)\nlabel_series.replace(to_replace=mmc.label_mapping, inplace=True)\n# -\n\nlabel_series\n\n# #### Predicted class\n\ncolnames = []\nfor key in mmc.label_mapping.keys():\n colnames.append(mmc.label_mapping[key])\nkeras_pred_df = pd.DataFrame(keras_predictions, columns=colnames)\nonnx_pred_df = pd.DataFrame(onnx_pred[0], columns=colnames)\n\n(keras_pred_df.idxmax(axis=1).astype(str) == label_series).mean()\n\n(onnx_pred_df.idxmax(axis=1).astype(str) == label_series).mean()\n\nassert ((keras_pred_df.idxmax(axis=1).astype(str) == onnx_pred_df.idxmax(axis=1).astype(str)).all())\n","repo_name":"kingjosephm/vehicle_make_model_classifier","sub_path":"tests/onnx_keras_weights.ipynb","file_name":"onnx_keras_weights.ipynb","file_ext":"py","file_size_in_byte":3779,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"2302904176","text":"# 文本分类方法有:\n#\n# - TF-IDF\n# - Count Features\n# - Logistic Regression\n# - Naive Bayes\n# - SVM\n# - Xgboost\n# - Grid Search\n# - Word Vectors\n# - Dense Network\n# - LSTM\n# - GRU\n# - Ensembling\n\n# +\nimport pandas as pd\nimport numpy as np\nimport xgboost as xgb\nfrom tqdm import tqdm\nfrom sklearn.svm import SVC\nfrom sklearn import preprocessing, decomposition, model_selection, metrics, pipeline\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer\nfrom sklearn.decomposition import TruncatedSVD\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report\nfrom sklearn.naive_bayes import MultinomialNB\n\nfrom keras.models import Sequential\nfrom keras.layers.recurrent import LSTM, GRU\nfrom keras.layers.core import Dense, Activation, Dropout\nfrom keras.layers.embeddings import Embedding\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.utils import np_utils\nfrom keras.layers import GlobalMaxPooling1D, Conv1D, MaxPooling1D, Flatten, Bidirectional, SpatialDropout1D\nfrom keras.preprocessing import sequence, text\nfrom keras.callbacks import EarlyStopping\n# -\n\n# ## Data\n\ndata = pd.read_excel('./datasets/复旦大学中文文本分类语料.xlsx', sheet_name='sheet1')\n\ndata.sample(5)\n\ndata.info()\n\ndata.分类.unique()\n\n# ### 分词\n\n# 可以先过滤特殊符号,只保留汉字\n\n# +\n# 本实验运行时,没有使用\n# import re\n\n\n# def preprocessing(txt, pattern=r'[\\u4e00-\\u9fa5]+'):\n# re_tokens = re.findall(pattern, txt)\n# return re_tokens\n\n\n# data['正则结果'] = data['正文'].apply(lambda txt: ' '.join(preprocessing(txt)))\n# # 注意修改下面分词结果,在正则结果上apply\n# -\n\n# 可采用分词效果更好的分词器,如pyltp、THULAC、Hanlp等\n\n# +\nimport os\n\n# ltp模型目录的路径\nLTP_DATA_DIR = r'D:\\ProgramData\\nlp_package\\ltp_v34'\n# 分词模型路径,模型名称为`cws.model`\ncws_model_path = os.path.join(LTP_DATA_DIR, 'cws.model') \n\n# +\nfrom pyltp import Segmentor\n\n\nsegmentor = Segmentor() # 初始化实例\nsegmentor.load(cws_model_path) # 加载模型\n\ndata['分词结果'] = data['正文'].apply(lambda i: ' '.join(segmentor.segment(i)))\n# -\n\nsegmentor.release() # 释放模型\n\ndata.sample(5)\n\n\n# ### Loss\n\ndef multiclass_logloss(actual, predicted, eps=1e-15):\n \"\"\"对数损失度量(Logarithmic Loss Metric)的多分类版本。\n :param actual: 包含actual target classes的数组\n :param predicted: 分类预测结果矩阵, 每个类别都有一个概率\n \"\"\"\n # Convert 'actual' to a binary array if it's not already:\n if len(actual.shape) == 1:\n actual2 = np.zeros((actual.shape[0], predicted.shape[1]))\n for i, val in enumerate(actual):\n actual2[i, val] = 1\n actual = actual2\n \n # clip 0 and 1 for calculate\n clip = np.clip(predicted, eps, 1 - eps)\n rows = actual.shape[0]\n vsota = np.sum(actual * np.log(clip))\n return -1.0 / rows * vsota\n\n\n# ### label\n\nlabel_encoder = preprocessing.LabelEncoder()\ny = label_encoder.fit_transform(data.分类.values)\n\n# ### dataset split\n\nxtrain, xvalid, ytrain, yvalid = train_test_split(data.分词结果.values, y, \n stratify=y, \n random_state=42, \n test_size=0.1, shuffle=True)\n\nprint(xtrain.shape)\nprint(xvalid.shape)\n\n\n# ## Models\n\n# ### Basic Models\n\n# TF-IDF (Term Frequency - Inverse Document Frequency)+逻辑斯底回归(Logistic Regression)\n#\n# 将文本中的数字特征统一表示成\"#NUMBER\",达到一定的降噪效果。\n\n# +\ndef number_normalizer(tokens):\n \"\"\" 将所有数字标记映射为一个占位符(Placeholder)。\n 对于许多实际应用场景来说,以数字开头的tokens不是很有用,\n 全部视为一类‘数字’。 通过将所有数字都表示成同一个符号,可���达到降维的目的。\n \"\"\"\n return ('#NUMBER' if token[0].isdigit() else token for token in tokens)\n\n\nclass NumberNormalizingVectorizer(TfidfVectorizer):\n def build_tokenizer(self):\n tokenizer = super(NumberNormalizingVectorizer, self).build_tokenizer()\n return lambda doc: list(number_normalizer(tokenizer(doc)))\n\n\n# -\n\nwith open('datasets\\stopwords.txt', 'r', encoding='utf-8') as f: \n stopwords_list = [w.strip() for w in f.readlines()]\n\n# +\ntfidf_vectorizer = NumberNormalizingVectorizer(min_df=3, \n max_df=0.5,\n max_features=None, \n ngram_range=(1, 2), \n use_idf=True,\n smooth_idf=True,\n stop_words = stopwords_list)\n\ntfidf_vectorizer.fit(data.分词结果.values)\nxtrain_tfidf = tfidf_vectorizer.transform(xtrain)\nxvalid_tfidf = tfidf_vectorizer.transform(xvalid)\n\n# +\nclf = LogisticRegression(C=1.0,solver='lbfgs',multi_class='multinomial')\n\nclf.fit(xtrain_tfidf, ytrain)\n\n# +\npredictions = clf.predict_proba(xvalid_tfidf)\n\nprint (\"logloss: %0.3f \" % multiclass_logloss(yvalid, predictions))\n# -\n\n# ### BOW feature\n\n# +\ncount_vectorizer = CountVectorizer(min_df=3,\n max_df=5,\n ngram_range=(1, 2),\n stop_words=stopwords_list)\n\ncount_vectorizer.fit(data.分词结果.values)\nxtrain_bow = count_vectorizer.transform(xtrain)\nxvalid_bow = count_vectorizer.transform(xvalid)\n\n# +\nclf = LogisticRegression(C=1.0,solver='lbfgs',multi_class='multinomial')\n\nclf.fit(xtrain_bow, ytrain)\npredictions = clf.predict_proba(xvalid_bow)\n\nprint (\"logloss: %0.3f \" % multiclass_logloss(yvalid, predictions))\n# -\n\n# ### Naive Bayes\n\n# +\n# tf-idf feature\nclf = MultinomialNB()\nclf.fit(xtrain_tfidf, ytrain)\npredictions = clf.predict_proba(xvalid_tfidf)\n\nprint (\"logloss: %0.3f \" % multiclass_logloss(yvalid, predictions))\n\n# +\n# bow feature\nclf = MultinomialNB()\nclf.fit(xtrain_bow, ytrain)\npredictions = clf.predict_proba(xvalid_bow)\n\nprint (\"logloss: %0.3f \" % multiclass_logloss(yvalid, predictions))\n# -\n\n# ### SVM\n\n# +\n# 在使用SVM之前,我们需要将数据标准化(Standardize Data ),同时结合SVD降维\n# 对于SVM来说,SVD的components的合适调整区间一般为120~200 \nsvd = decomposition.TruncatedSVD(n_components=120)\n\nsvd.fit(xtrain_tfidf)\nxtrain_svd = svd.transform(xtrain_tfidf)\nxvalid_svd = svd.transform(xvalid_tfidf)\n# -\n\nscaler = preprocessing.StandardScaler()\nscaler.fit(xtrain_svd)\nxtrain_svd_scl = scaler.transform(xtrain_svd)\nxvalid_svd_scl = scaler.transform(xvalid_svd)\n\n# +\nclf = SVC(C=1.0, probability=True)\n\nclf.fit(xtrain_svd_scl, ytrain)\npredictions = clf.predict_proba(xvalid_svd_scl)\n\nprint (\"logloss: %0.3f \" % multiclass_logloss(yvalid, predictions))\n# -\n\n# ### XGBoost\n\n# 这部分运行很慢,lightGBM更快一些\n\n# +\n# 不使用sklearn API的用法\n\n# # tf-idf\n# xtrain_xgb = xgb.DMatrix(xtrain_tfidf, label=ytrain)\n# xvalid_xgb = xgb.DMatrix(xvalid_tfidf, label=yvalid)\n\n# # setup parameters for xgboost\n# param = {}\n# # use softmax multi-class classification\n# param['objective'] = 'multi:softmax'\n# # scale weight of positive examples\n# param['eta'] = 0.1\n# param['max_depth'] = 7\n# param['silent'] = 1\n# param['nthread'] = 4\n# param['num_class'] = len(data.分类.unique())\n# param['eval_metric'] = 'mlogloss'\n# param['colsample_bytree'] = 0.8\n# param['subsample'] = 0.8\n\n# num_round = 100\n\n# clf = xgb.train(param, xtrain_xgb, num_boost_round=num_round)\n\n# predictions = clf.predict(xvalid_xgb) # class id list\n\n# +\n# sklearn inferface\n\nclf = xgb.XGBClassifier(objective='multi:softmax',\n max_depth=7,\n n_estimators=50, \n colsample_bytree=0.8, \n subsample=0.8, \n nthread=10, \n learning_rate=0.1)\n\nclf.fit(xtrain_tfidf.tocsc(), ytrain) # Sparse col\npredictions = clf.predict_proba(xvalid_tfidf.tocsc())\n\nprint (\"logloss: %0.3f \" % multiclass_logloss(yvalid, predictions))\n\n# +\n# Bow feature\nclf = xgb.XGBClassifier(objective='multi:softmax', \n max_depth=7,\n n_estimators=50, \n colsample_bytree=0.8, \n subsample=0.8, \n nthread=10, \n learning_rate=0.1)\n\nclf.fit(xtrain_bow.tocsc(), ytrain) # Sparse col\npredictions = clf.predict_proba(xvalid_bow.tocsc())\n\nprint (\"logloss: %0.3f \" % multiclass_logloss(yvalid, predictions))\n\n# +\n# tf-idf + svd\nclf = xgb.XGBClassifier(objective='multi:softmax',\n max_depth=7,\n n_estimators=50, \n colsample_bytree=0.8, \n subsample=0.8, \n nthread=10, \n learning_rate=0.1)\n\nclf.fit(xtrain_svd.tocsc(), ytrain) # Sparse col\npredictions = clf.predict_proba(xvalid_svd.tocsc())\n\nprint (\"logloss: %0.3f \" % multiclass_logloss(yvalid, predictions))\n\n# +\n# tf-idf + svd + scaled\nclf = xgb.XGBClassifier(objective='multi:softmax',\n max_depth=7,\n n_estimators=50, \n colsample_bytree=0.8, \n subsample=0.8, \n nthread=10, \n learning_rate=0.1)\n\nclf.fit(xtrain_svd_scl.tocsc(), ytrain) # Sparse col\npredictions = clf.predict_proba(xvalid_svd_scl.tocsc())\n\nprint (\"logloss: %0.3f \" % multiclass_logloss(yvalid, predictions))\n# -\n\n# ### LightGBM\n\nimport lightgbm as lgb\n\n# +\n# For origin package use\n# xtrain_lgb = lgb.Dataset(xtrain_tfidf, ytrain)\n# xvalid_lgb = lgb.Dataset(xvalid_tfidf, yvalid, reference=xtrain_lgb)\n\nclf = lgb.LGBMClassifier(num_leaves=31,\n max_depth=7,\n n_estimators=50,\n objective='multiclass',\n subsample=0.8,\n colsample_bytree=0.8,\n learning_rate=0.1)\n\nclf.fit(xtrain_tfidf, ytrain)\n\n# +\npredictions = clf.predict_proba(xvalid_tfidf)\n\nprint (\"logloss: %0.3f \" % multiclass_logloss(yvalid, predictions))\n# -\n\n# ### Pipline Grid Search\n\n# +\n# 运行耗时较长\n\n# 自定义评分函数\nmll_scorer = metrics.make_scorer(multiclass_logloss, \n greater_is_better=False, \n needs_proba=True)\n\n#SVD初始化\nsvd = TruncatedSVD()\n \n# Standard Scaler初始化\nscl = preprocessing.StandardScaler()\n\n# 再一次使用Logistic Regression\nlr_model = LogisticRegression()\n\n# 创建pipeline \nclf = pipeline.Pipeline([('svd', svd),\n ('scl', scl),\n ('lr', lr_model)])\n\n# param for search\nparam_grid = {'svd__n_components' : [120, 180],\n 'lr__C': [0.1, 1.0, 10], \n 'lr__penalty': ['l1', 'l2']}\n\n# 网格搜索模型(Grid Search Model)初始化\nmodel = GridSearchCV(estimator=clf, param_grid=param_grid, scoring=mll_scorer,\n verbose=2, n_jobs=1, iid=True, refit=True, cv=2)\n\n#fit网格搜索模型\nmodel.fit(xtrain_tfidf, ytrain)\n\nprint(\"Best score: %0.3f\" % model.best_score_)\nprint(\"Best parameters set:\")\nbest_parameters = model.best_estimator_.get_params()\nfor param_name in sorted(param_grid.keys()):\n print(\"\\t%s: %r\" % (param_name, best_parameters[param_name]))\n# -\n\n# ### Word2Vec Feature\n\n# 一行一个单独文本\ndoc_word_list = [dwords.split() for dwords in data['分词结果']]\n\n# +\nfrom gensim.models import Word2Vec\nfrom gensim.models.word2vec import LineSentence\n\n\n# sentences = LineSentence(file_path)\nmodel = Word2Vec(doc_word_list, min_count=5, window=7, size=100, workers=4)\n\n# model.save('word2vec_model_100v.w2v')\n# -\n\nembeddings_index = dict(zip(model.wv.index2word, model.wv.vectors))\n\n\ndef sent2vec(s):\n #该函数会将语句转化为一个标准化的向量(Normalized Vector)\n from pyltp import Segmentor\n\n segmentor = Segmentor() # 初始化实例\n segmentor.load(cws_model_path) # 加载模型\n words = segmentor.segment(s)\n segmentor.release()\n words = [w for w in words if not w in stopwords_list]\n \n M = []\n for w in words:\n try:\n #M.append(embeddings_index[w])\n M.append(model.wv.get_vector(w))\n except:\n continue\n \n M = np.array(M)\n v = M.sum(axis=0)\n if type(v) != np.ndarray:\n return np.zeros(300)\n return v / np.sqrt((v ** 2).sum())\n\n\n# +\nfrom tqdm import tqdm_notebook\n\n# 耗时较长,一小时左右\nxtrain_w2v = [sent2vec(x) for x in tqdm_notebook(xtrain)]\nxvalid_w2v = [sent2vec(x) for x in tqdm_notebook(xvalid)]\n# -\n\nxtrain_w2v = np.array(xtrain_w2v)\nxvalid_w2v = np.array(xvalid_w2v)\n\n# ### Deep Model\n\n# +\n# Simple test\n\nmax_len = 70\n\n# 对标签进行binarize处理\nytrain_enc = np_utils.to_categorical(ytrain)\nyvalid_enc = np_utils.to_categorical(yvalid)\n\n# 使用 keras tokenizer\ntoken = text.Tokenizer(num_words=None)\ntoken.fit_on_texts(data.分词结果.values)\nxtrain_seq = token.texts_to_sequences(xtrain)\nxvalid_seq = token.texts_to_sequences(xvalid)\n\n# 对文本序列进行zero填充\nxtrain_pad = sequence.pad_sequences(xtrain_seq, maxlen=max_len)\nxvalid_pad = sequence.pad_sequences(xvalid_seq, maxlen=max_len)\n\nword_index = token.word_index\n\n# + code_folding=[]\n#基于已有的数据集中的词汇创建一个词嵌入矩阵(Embedding Matrix)\nembedding_matrix = np.zeros((len(word_index) + 1, 100))\n\nfor word, i in tqdm_notebook(word_index.items()):\n embedding_vector = embeddings_index.get(word)\n if embedding_vector is not None:\n embedding_matrix[i] = embedding_vector\n\n# +\n# 基��前面训练的Word2vec词向量,构建1个2层的GRU模型\nmodel = Sequential()\nmodel.add(Embedding(len(word_index) + 1,\n 100,\n weights=[embedding_matrix],\n input_length=max_len,\n trainable=False))\nmodel.add(SpatialDropout1D(0.2))\nmodel.add(GRU(128, return_sequences=True))\nmodel.add(GRU(128, dropout=0.2, recurrent_dropout=0.2))\n\nmodel.add(Dense(1024, activation='selu'))\nmodel.add(Dropout(0.8))\n\nmodel.add(Dense(256, activation='selu'))\nmodel.add(Dropout(0.8))\n\nmodel.add(Dense(19))\nmodel.add(Activation('softmax'))\nmodel.compile(loss='categorical_crossentropy', optimizer='adam')\n# -\n\n#在模型拟合时,使用early stopping这个回调函数(Callback Function)\nearlystop = EarlyStopping(monitor='val_loss', min_delta=0, patience=3, verbose=0, mode='auto')\nmodel.fit(xtrain_pad, y=ytrain_enc, batch_size=64, epochs=50, \n verbose=1, validation_data=(xvalid_pad, yvalid_enc), callbacks=[earlystop])\n\n# ### Model Ensembling\n\n# 采用Stacking的方式,对于多个效果相当的基础分类器的输出结果,在输入xgboost进行分类计算。\n\n# +\nimport numpy as np\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import StratifiedKFold, KFold\nimport pandas as pd\nimport os\nimport sys\nimport logging\n\n\nlogging.basicConfig(\n level=logging.DEBUG,\n format=\"[%(asctime)s] %(levelname)s %(message)s\",\n datefmt=\"%H:%M:%S\", stream=sys.stdout)\nlogger = logging.getLogger(__name__)\n\n\n# + code_folding=[]\nclass Ensembler(object):\n def __init__(self, model_dict, num_folds=3, task_type='classification', optimize=roc_auc_score,\n lower_is_better=False, save_path=None):\n \"\"\"\n Ensembler init function\n :param model_dict: 模型字典 \n :param num_folds: cv所用的fold数量\n :param task_type: 分类(classification) 还是回归(regression)\n :param optimize: 优化函数,比如 AUC, logloss, F1等,必须有2个函数,即y_test 和 y_pred\n :param lower_is_better: 优化函数(Optimization Function)的值越低越好还是越高越好\n :param save_path: 模型保存路径\n \"\"\"\n self.model_dict = model_dict\n self.levels = len(self.model_dict)\n self.num_folds = num_folds\n self.task_type = task_type\n self.optimize = optimize\n self.lower_is_better = lower_is_better\n self.save_path = save_path\n\n self.training_data = None\n self.test_data = None\n self.y = None\n self.lbl_enc = None\n self.y_enc = None\n self.train_prediction_dict = None\n self.test_prediction_dict = None\n self.num_classes = None\n\n def fit(self, training_data, y, lentrain):\n \"\"\"\n :param training_data: 二维表格形式的训练数据\n :param y: 二进制的, 多分类或回归\n :return: 用于预测的模型链(Chain of Models)\n \"\"\"\n self.training_data = training_data\n self.y = y\n\n if self.task_type == 'classification':\n self.num_classes = len(np.unique(self.y))\n logger.info(\"Found %d classes\", self.num_classes)\n self.lbl_enc = LabelEncoder()\n self.y_enc = self.lbl_enc.fit_transform(self.y)\n kf = StratifiedKFold(n_splits=self.num_folds)\n train_prediction_shape = (lentrain, self.num_classes)\n else:\n self.num_classes = -1\n self.y_enc = self.y\n kf = KFold(n_splits=self.num_folds)\n train_prediction_shape = (lentrain, 1)\n\n # 每层模型的输出shape\n self.train_prediction_dict = {}\n for level in range(self.levels):\n self.train_prediction_dict[level] = np.zeros((train_prediction_shape[0],\n train_prediction_shape[1] * len(self.model_dict[level])))\n\n for level in range(self.levels):\n if level == 0: # 第一层基础分类器输入\n temp_train = self.training_data\n else: # 第二层基于基础分类器结果的再分类器输入\n temp_train = self.train_prediction_dict[level - 1]\n\n for model_num, model in enumerate(self.model_dict[level]):\n validation_scores = []\n foldnum = 1\n for train_index, valid_index in kf.split(self.train_prediction_dict[0], self.y_enc):\n logger.info(\"Training Level %d Fold # %d. Model # %d\", level, foldnum, model_num)\n\n if level != 0: # 第二层基于基础分类器结果的再分类\n l_training_data = temp_train[train_index]\n l_validation_data = temp_train[valid_index]\n model.fit(l_training_data, self.y_enc[train_index])\n else: # 第一层基础分类\n l0_training_data = temp_train[0][model_num]\n if type(l0_training_data) == list:\n l_training_data = [x[train_index] for x in l0_training_data]\n l_validation_data = [x[valid_index] for x in l0_training_data]\n else:\n l_training_data = l0_training_data[train_index]\n l_validation_data = l0_training_data[valid_index]\n model.fit(l_training_data, self.y_enc[train_index])\n\n logger.info(\"Predicting Level %d. Fold # %d. Model # %d\", level, foldnum, model_num)\n\n # valid results\n if self.task_type == 'classification':\n temp_train_predictions = model.predict_proba(l_validation_data)\n self.train_prediction_dict[level][valid_index,\n (model_num * self.num_classes):((model_num + 1) * self.num_classes)] = temp_train_predictions\n\n else:\n temp_train_predictions = model.predict(l_validation_data)\n self.train_prediction_dict[level][valid_index, model_num] = temp_train_predictions\n \n validation_score = self.optimize(self.y_enc[valid_index], temp_train_predictions)\n validation_scores.append(validation_score)\n logger.info(\"Level %d. Fold # %d. Model # %d. Validation Score = %f\", level, foldnum, model_num,\n validation_score)\n foldnum += 1\n \n # 各个基础分类器的性能不要相差太大,否则模型效果不易提升\n avg_score = np.mean(validation_scores)\n std_score = np.std(validation_scores)\n logger.info(\"Level %d. Model # %d. Mean Score = %f. Std Dev = %f\", level, model_num,\n avg_score, std_score)\n\n logger.info(\"Saving predictions for level # %d\", level)\n train_predictions_df = pd.DataFrame(self.train_prediction_dict[level])\n train_predictions_df.to_csv(os.path.join(self.save_path, \"train_predictions_level_\" + str(level) + \".csv\"),\n index=False, header=None)\n\n return self.train_prediction_dict\n\n def predict(self, test_data, lentest):\n self.test_data = test_data\n if self.task_type == 'classification':\n test_prediction_shape = (lentest, self.num_classes)\n else:\n test_prediction_shape = (lentest, 1)\n\n self.test_prediction_dict = {}\n for level in range(self.levels):\n self.test_prediction_dict[level] = np.zeros((test_prediction_shape[0],\n test_prediction_shape[1] * len(self.model_dict[level])))\n self.test_data = test_data\n for level in range(self.levels):\n if level == 0:\n temp_test = self.test_data\n else:\n temp_test = self.test_prediction_dict[level - 1]\n\n for model_num, model in enumerate(self.model_dict[level]):\n\n if self.task_type == 'classification':\n if level == 0:\n temp_test_predictions = model.predict_proba(temp_test[0][model_num])\n else:\n temp_test_predictions = model.predict_proba(temp_test)\n self.test_prediction_dict[level][:, (model_num * self.num_classes): \n ((model_num + 1) * self.num_classes)] = temp_test_predictions\n else:\n if level == 0:\n temp_test_predictions = model.predict(temp_test[0][model_num])\n else:\n temp_test_predictions = model.predict(temp_test)\n self.test_prediction_dict[level][:, model_num] = temp_test_predictions\n\n test_predictions_df = pd.DataFrame(self.test_prediction_dict[level])\n test_predictions_df.to_csv(os.path.join(self.save_path, \"test_predictions_level_\" + str(level) + \".csv\"),\n index=False, header=None)\n\n return self.test_prediction_dict\n\n\n# +\n#为每个level的集成指定使用数据:\ntrain_data_dict = {0: [xtrain_tfidf, xtrain_bow, xtrain_tfidf, xtrain_bow], 1: [xtrain_w2v]}\ntest_data_dict = {0: [xvalid_tfidf, xvalid_bow, xvalid_tfidf, xvalid_bow], 1: [xvalid_w2v]}\n\nmodel_dict = {0: [LogisticRegression(),\n LogisticRegression(), \n MultinomialNB(alpha=0.1), \n MultinomialNB()],\n 1: [xgb.XGBClassifier(silent=True, \n objective='multi:softmax',\n n_estimators=25, \n max_depth=6,\n colsample_bytree=0.8, \n subsample=0.8, \n learning_rate=0.1)]}\n\nens = Ensembler(model_dict=model_dict, num_folds=3, task_type='classification',\n optimize=multiclass_logloss, lower_is_better=True, save_path='')\n\nens.fit(train_data_dict, ytrain, lentrain=xtrain_w2v.shape[0])\n\npreds = ens.predict(test_data_dict, lentest=xvalid_w2v.shape[0])\n\n# + code_folding=[]\n# 损失\nmulticlass_logloss(yvalid, preds[1])\n","repo_name":"RacleRay/TextClassification","sub_path":"分类算法在文本问题中的使用.ipynb","file_name":"分类算法在文本问题中的使用.ipynb","file_ext":"py","file_size_in_byte":24381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"28391323100","text":"import pandas as pd\nimport json\nimport requests\nimport urllib.request\nimport os\nfrom datetime import datetime\nimport cx_Oracle\nfrom IPython.display import display, HTML\n\nestado = 'Procesando'\nancho = 1800\ndisplay(HTML(f\"\"))\ndf_formulas = pd.read_csv('formulas.csv',delimiter=';')\n\n#Conexion a la base para levantar las formulas\n\"\"\"host='racexa03adm01.gobiernocba.gov.ar'\nport=1521\nsid='moremigd'\nuser='dc'\npassword='dc'\nsid = cx_Oracle.makedsn(host, port, service_name=sid)\n\nconnection = cx_Oracle.connect(user, password, sid, encoding=\"UTF-8\")\ncursor = connection.cursor()\ncursor.execute('select impuesto, cpto_origen, cpto_calculo, cpto_distri, formula_calculo, formula_distri, distribuye, cta_destino from formulas')\nresult_set = cursor.fetchall()\ndf_formulas = pd.DataFrame(result_set, columns=[col[0] for col in cursor.description])\n# Close the cursor and the database connection\ncursor.close()\nconnection.close()\"\"\"\n\n#Separo formulas de calculo y distribucion\ndf_formulas_calc = df_formulas.drop([\"FORMULA_DISTRI\",'CTA_DESTINO'], axis=1)\ndf_formulas_calc = df_formulas_calc.drop_duplicates(subset=['IMPUESTO', 'CPTO_ORIGEN', 'CPTO_CALCULO', 'CPTO_DISTRI', 'FORMULA_CALCULO', 'DISTRIBUYE'])\ndf_formulas_distr = df_formulas.drop([\"FORMULA_CALCULO\"], axis=1)\ndf_formulas_distr = df_formulas_distr.drop_duplicates(subset=['IMPUESTO', 'CPTO_ORIGEN', 'CPTO_CALCULO', 'CPTO_DISTRI', 'FORMULA_DISTRI', 'CTA_DESTINO', 'DISTRIBUYE'])\n\n#Abro archivo JSON\nf = open('AutomotorVarios.json',encoding=\"utf8\")\n#f = open('Embarcacion.json',encoding=\"utf8\")\ndata = json.load(f)\nf.close()\n\n#Se normalida para un DF\ndf=pd.json_normalize(data['boleta'])\ndatos_json = df\ndf\n\n#Solo para visualizacion\ndatos_json = data\ndatos_json\n\n# Agregar la lista 'listDetallesPago' al JSON para procesar\ndetalles_pago = datos_json['boleta']['listPagos'][0]['listDetallesPago']\n#Extraigo Lista de Pagos\nlista_pagos = datos_json['boleta']['listPagos']\n\ndetalle_pagos = lista_pagos\ndetalle_pagos\n\n# +\n#Extraigo los valores de los detalles de pago\ndf_detalles_pago = pd.DataFrame(columns=[\n 'idTransaccion',\n 'tipoMovimiento',\n 'montoPagado',\n # ... otros campos que quieran incluir ...\n])\n\n# Acceder a la lista de pagos\nlista_pagos = datos_json['boleta']['listPagos']\n\n\nfor pago in lista_pagos:\n detalles_pago = pago['listDetallesPago']\n for detalle in detalles_pago:\n\n df_detalles_pago = pd.concat([df_detalles_pago, pd.DataFrame(detalle, index=[0])], ignore_index=True)\n\n\ndf_detalles_pago\n\n# -\n\nlista_pagos\n\ndetalle_pagos = df_detalles_pago\ndetalle_pagos\n\n#extraigo de la caracteristica el tipo de mov\ndf_detalles_pago['tipo_mov'] = df_detalles_pago['caracteristica'].apply(lambda x: x['valor'])\ndetalles_pago = df_detalles_pago.drop(\"caracteristica\", axis=1)\ndetalles_pago = pd.merge(detalles_pago, df_formulas_calc, left_on='tipo_mov', right_on='CPTO_ORIGEN')\ndetalles_pago\n\n#Calculo el monto de recargos y descuentos\nindice_general = detalles_pago[detalles_pago['CPTO_CALCULO'] == 'GENERAL'].index[0]\nmonto_recargo = detalles_pago.loc[indice_general, 'montoPagado']\n\n# +\n# Calcula porcentaje de GENERAL (Redondeo) si se distribuye\nexiste_autmun = 'AUTMUN' in detalles_pago['CPTO_ORIGEN'].values\n#existe_general = 'GENERAL' in df_calculo['CPTO_CALCULO'].values\ndistribuye = 'S' in detalles_pago['DISTRIBUYE'].values\n\nif existe_autmun and distribuye:\n detalles_pago['montoRecargo'] = monto_recargo * .5\nelse:\n detalles_pago['montoRecargo'] = monto_recargo\ndf=detalles_pago\ndetalles_pago\n# -\n\n#Separo recargos de conceptos validos\ndf_recargo = detalles_pago[detalles_pago['CPTO_CALCULO'] == 'GENERAL']\ndf_calculo = detalles_pago[detalles_pago['CPTO_CALCULO'] != 'GENERAL']\ndf_calculo\n\n#Aplico formula para calculo de monto final\npd.options.mode.chained_assignment = None\ndf_list = []\nfor formula in df_calculo['FORMULA_CALCULO'].unique():\n# print(formula)\n df_new = df_calculo[df_calculo['FORMULA_CALCULO'] == formula].copy()\n df_new['montoCalculado'] = pd.eval(formula)\n df_list.append(df_new)\ndf_calculo = pd.concat(df_list, ignore_index=True)\ndf_calculo\n\ndf_calculo = df_calculo.groupby('CPTO_CALCULO')['montoCalculado'].sum().reset_index()\ncalculado = df_calculo.rename(columns={'CPTO_CALCULO': 'tipoMovimiento', 'montoCalculado': 'montoPagado'})\ncalculado['montoPagado'] = calculado['montoPagado'].round(2)\ncalculado\n\nv_salida = calculado\nv_salida['idTransaccion'] = f\"{datetime.now().year % 100}{datetime.now().month:02}{datetime.now().day:02}{datetime.now().hour:02}{datetime.now().minute:02}{datetime.now().second:02}{datetime.now().microsecond // 10000:02}\"\nv_salida['caracteristica'] = '[{''tipo'': ''CMCCCDC'', ''valor'':'' }]'\nv_salida\n\n#Elimino lista de Pagos\nif 'listDetallesPago' in datos_json['boleta']['listPagos'][0]:\n del datos_json['boleta']['listPagos'][0]['listDetallesPago']\ndf_as_list = v_salida.to_dict(orient='records')\ndatos_json['boleta']['listPagos'][0]['listDetallesPago'] = df_as_list\n#datos_json\n\nwith open(\"outputAUT.json\", \"w\") as outfile:\n#with open(\"outputEMB.json\", \"w\") as outfile:\n json.dump(datos_json, outfile, indent=4)\n\ndistri = pd.merge(calculado, df_formulas_distr, left_on='tipoMovimiento', right_on='CPTO_DISTRI')\ndistri = pd.DataFrame(distri)\ndf=distri\ndf\n\npd.options.mode.chained_assignment = None\ndf_list = []\nfor formula in distri['FORMULA_DISTRI'].unique():\n# print(formula)\n\n df_new = distri[distri['FORMULA_DISTRI'] == formula].copy()\n df_new['montoDistri'] = pd.eval(formula)\n df_list.append(df_new)\ndf_distri = pd.concat(df_list, ignore_index=True)\ndf_distri = df_distri.drop(['IMPUESTO','CPTO_CALCULO'], axis=1)\n#df_distri\n\ndistri = df_distri.groupby('CTA_DESTINO')['montoDistri'].sum().reset_index()\ndistri\n","repo_name":"palaciosleo/autemb-nano","sub_path":"PatriJson_OK.ipynb","file_name":"PatriJson_OK.ipynb","file_ext":"py","file_size_in_byte":5753,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"20902543331","text":"# +\n# open file\nfd = open(\"textfile1.txt\", \"rt\") # opening for reading as text files\n\n# read the content\n#s = fd.read() # reading whole content\ns = fd.read(5) # read 5 bytes starting from begining\nprint(s)\n\ns = fd.read(6) # read next 6 bytes\nprint(s)\n\n\n# close file\nfd.close()\n\n# +\n# how to read text file line by line\n\nfd = open(\"textfile1.txt\", \"rt\") # opening for reading as text files\n\nfor line in fd:\n print(line.strip()) # remove white characters (like new line sequence with .strip() method )\n\n# close file\nfd.close()\n\n# +\n# how to read text file as a list of lines\n\nfd = open(\"textfile1.txt\", \"rt\") # opening for reading as text files\n\n# \\n - end line for Linux-based OS\n# \\r\\n - end line for Windows OS\nlines = fd.readlines()\nfor line in lines:\n print(line.strip())\n\n# close file\nfd.close()\n\n# +\n# how to write the content to the text file\n\nfd = open(\"file-for-writing.txt\", \"wt\") # open file for writing (warning - existing file will be truncating)\n\nfd.write(\"Some data for storing in text file\\r\\n\")\nfd.write(\"additional text\\r\\n\")\n\nfd.writelines([\"Line A\\r\\n\",\"Line B\\r\\n\",\"Line C\\r\\n\"])\n\nfd.close()\n\n# +\n# how to write the content to the text file\n\nfd = open(\"file-for-append.txt\", \"at\") # open file for writing (appending content)\n\nfd.write(\"Some data for storing in text file\\r\\n\")\nfd.write(\"additional text\\r\\n\")\n\nfd.writelines([\"Line A\\r\\n\",\"Line B\\r\\n\",\"Line C\\r\\n\"])\n\nfd.close()\n\n# +\n# Context manager for automatic relasing the file handle\nwith open(\"textfile1.txt\", \"rt\") as fd:\n s = fd.read()\n print(s)\n \nprint(fd.closed)\n# -\n\n\n","repo_name":"alx2202/DataAnalysis","sub_path":"Day08/01-files.ipynb","file_name":"01-files.ipynb","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"12822044259","text":"# [AI해커톤 본선] Episode3 분석코드 (팀ID: aiplay1115)\n\n# # 0. 라이브러리 설치 및 AIDU 연동을 위한 설정\n\n# +\n#Connect with AIDU with Centro Modules\nfrom aicentro.session import Session\naidu_session = Session(verify=False)\n\nfrom aicentro.framework.keras import Keras as AiduFrm\naidu_framework = AiduFrm(session=aidu_session)\n\n#Import Base Module for Data Analysis\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense\nfrom tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping\n\nimport tensorflow as tf\n\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import StratifiedKFold, StratifiedShuffleSplit, cross_val_score, KFold\nfrom sklearn.metrics import mean_squared_error\nimport datetime\nimport os\n\nfrom sklearn.model_selection import train_test_split\nget_ipython().system('pip install xgboost')\nimport xgboost as xgb\nfrom xgboost import plot_tree\nimport sklearn\nfrom sklearn.metrics import classification_report, accuracy_score\nfrom sklearn.model_selection import GridSearchCV\n\n# get_ipython().system('pip install seaborn')\nimport seaborn as sns\n\n# get_ipython().system('pip install mglearn')\nimport mglearn\n\n# get_ipython().system('pip install biokit')\nfrom biokit.viz import corrplot\n\n# get_ipython().system('pip install dcor')\nimport dcor\n# -\n\n# # 1. 데이터 탐색 (EDA)\n\n# ## 1-0. Data Loading\n# - **Table 1** : 사용자의 VOD 구매/시청 정보\n# - **Table 2** : VOD Type별 시청정보\n# - **Table 3** : VOD Type 정의서 \n\n# +\n#--------------------------------------------------------------------\n# Data loading\n#--------------------------------------------------------------------\n# Train data\ntrain_t1 = pd.read_csv(aidu_framework.config.data_dir + '/ep3_train_t1.csv') #Table 1\ntrain_t2 = pd.read_csv(aidu_framework.config.data_dir + '/ep3_train_t2.csv') #Table 2\n\n# Test data\ntest_t1 = pd.read_csv(aidu_framework.config.data_dir + '/ep3_test_t1.csv') #Table 1\ntest_t2 = pd.read_csv(aidu_framework.config.data_dir + '/ep3_test_t2.csv') #Table 2\n\nvod_type = pd.read_csv(aidu_framework.config.data_dir + '/ep3_vod_type.csv') # Table 3\n\n# 데이터 크기 확인\nprint(train_t1.shape, train_t2.shape, test_t1.shape, test_t2.shape, vod_type.shape)\n# -\n\n# ## 1-1. 데이터 구성 및 결측 확인\n\ntrain_t1.info()\n\ntrain_t2.info()\n\ntest_t1.info()\n\ntest_t2.info()\n\n# 결측치 여부 확인\nprint(\"Any missing sample in training set:\",train_t1.isnull().values.any())\nprint(\"Any missing sample in training set:\",train_t2.isnull().values.any())\nprint(\"Any missing sample in test set:\",test_t1.isnull().values.any())\nprint(\"Any missing sample in test set:\",test_t2.isnull().values.any(), \"\\n\")\n\n# train t2에 대해서 ID가 각 30000으로 train_1과 동일\n# train t1, t2를 ID 기준으로 결합해서 최종 dataset 생성\ntrain_t2['id'].unique().shape\n\n# ## 1-2. 선호 장르 분포 확인\n\n# Frequency distribution of classes\ntrain_outcome = pd.crosstab(index=train_t1[\"favor_genre\"], # Make a crosstab\n columns=\"count\") # Name the count column\ntrain_outcome\n\n# +\n# Visualizing Outcome Distribution \ntemp = train_t1[\"favor_genre\"].value_counts()\ndf = pd.DataFrame({'labels': temp.index,\n 'values': temp.values\n })\n\nlabels = df['labels']\nsizes = df['values']\ncolors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral','cyan','lightpink']\npatches, texts = plt.pie(sizes, shadow=True, startangle=90, pctdistance=1.1, labeldistance=1.2)\nplt.pie(sizes, labels=labels, autopct='%1.0f%%', pctdistance=1.1, labeldistance=1.2)\nplt.legend(patches, labels, loc=\"lower left\")\nplt.axis('equal')\nplt.tight_layout()\nplt.show()\n# -\n\n# ## 1-3. 변수 상관분석 및 시각화\n\n# 10개의 장르에 대한 구매건수 데이터 \ndf = pd.read_csv(aidu_framework.config.data_dir + '/ep3_train_t1.csv')\nbuy_cascnt_colnames = ['favor_genre'\n, 'tot_buy_cascnt'\n,'acton_sf_buy_cascnt'\n,'crim_thrl_buy_cascnt'\n,'drama_buy_cascnt'\n,'romc_melo_buy_cascnt'\n,'cmdy_buy_cascnt'\n,'horr_buy_cascnt'\n,'chdr_famly_buy_cascnt'\n,'docu_buy_cascnt'\n,'mtart_buy_cascnt'\n,'anmt_buy_cascnt'\n]\ndf_buy = df[buy_cascnt_colnames]\n\n# ### 1-3-1. 선호 장르에 따른 장르별 구매건수의 Pair Plot\n\n# count 기반 top3 설정하기\nbuy_cascnt_colnames_plot1 = ['favor_genre'\n, 'tot_buy_cascnt'\n,'acton_sf_buy_cascnt'\n,'cmdy_buy_cascnt'\n,'romc_melo_buy_cascnt'\n]\nsns.pairplot(df_buy[buy_cascnt_colnames_plot1]\n , hue='favor_genre');\nplt.show()\n\n# ### 1-3-2. 장르별 구매건수의 Pearson Correlation\n\n# +\n# get_ipython().system('pip install biokit')\nfrom biokit.viz import corrplot\n\n## Pearson Correlation 구하고 시각화하기\n# df_buy:장르별 구매 변수들에 대한 data frame\ncorr = df_buy.corr(method='pearson')\nc = corrplot.Corrplot(corr)\nc.plot(method='ellipse', cmap='PRGn_r'\n , shrink=1, rotation=45\n , upper='text', lower='ellipse')\nfig = plt.gcf()\nfig.set_size_inches(10, 8);\n\n\n# -\n\n# ### 1-3-3. 장르별 구매건수의 Distance Correlation Plot\n\n# +\n## 함수 만들기\ndef dist_corr(X, Y, pval=True, nruns=2000):\n\t#Distance correlation with p-value from bootstrapping\n\tdc = dcor.distance_correlation(X, Y)\n\tpv = dcor.independence.distance_covariance_test(X, Y, \n exponent=1.0, num_resamples=nruns)[0]\n\tif pval:\n\t return (dc, pv)\n\telse:\n\t return dc\n\n## corrfunc\ndef corrfunc(x, y, **kws):\n\td, p = dist_corr(x,y) \n\t#print(\"{:.4f}\".format(d), \"{:.4f}\".format(p))\n\tif p > 0.1:\n\t pclr = 'Darkgray'\n\telse:\n\t pclr= 'Darkblue'\n\tax = plt.gca()\n\tax.annotate(\"DC = {:.2f}\".format(d), xy=(.1, 0.99), \n xycoords=ax.transAxes, color = pclr, fontsize = 14)\n\nbuy_cascnt_colnames2 = [\n'acton_sf_buy_cascnt'\n,'crim_thrl_buy_cascnt'\n,'drama_buy_cascnt'\n,'romc_melo_buy_cascnt'\n# ,'cmdy_buy_cascnt'\n\n]\nbuy_cascnt_colnames2\n\n# 데이터 로딩\ndf_buy2 = df[buy_cascnt_colnames2]\n\ndf_buy2=df_buy2.sample(500)\ng = sns.PairGrid(df_buy2, diag_sharey=False)\naxes = g.axes\ng.map_upper(plt.scatter, linewidths=1\n , edgecolor=\"w\", s=90, alpha = 0.5)\ng.map_upper(corrfunc)\ng.map_diag(sns.kdeplot, lw = 4, legend=False)\ng.map_lower(sns.kdeplot, cmap=\"Blues_d\")\nplt.show()\n# -\n\n# # 2. 데이터 전처리\n\n# ## 2-1. Table 2 구조 변환\n\n# 사람별 VOD Type별 시청건수 테이블 생성 \ntrain_t2_r = train_t2.groupby(['id','vod_type_cd'])['view_cnt'].sum().reset_index()\ntrain_t2_r\n\ntrain_t2_r['vod_type_cd'] = ['vod_'+str(cd) for cd in train_t2_r['vod_type_cd']] #VOD 코드 값 수정 \ntrain_t2_r = train_t2_r.pivot(index='id', columns='vod_type_cd', values='view_cnt') #VOD Type을 컬럼으로 변환\ntrain_t2_r.fillna(0, inplace=True) #결측치 => 0\nprint(train_t2_r.shape)\ntrain_t2_r\n\n# 마찬가지로 Test set 에 대해 동일하게 구조 변환 \ntest_t2_r = test_t2.groupby(['id','vod_type_cd'])['view_cnt'].sum().reset_index()\ntest_t2_r['vod_type_cd'] = ['vod_'+str(cd) for cd in test_t2_r['vod_type_cd']] #VOD 코드 값 수정 \ntest_t2_r = test_t2_r.pivot(index='id', columns='vod_type_cd', values='view_cnt') #VOD Type을 컬럼으로 변환\ntest_t2_r.fillna(0, inplace=True) #결측치 => 0\nprint(test_t2_r.shape)\n\n# +\n# test set의 vod type을 train set에 포함된 vod type으로 맞춤 \ndiff_cols_train = set(train_t2_r.columns) - set(test_t2_r.columns) #test에 0으로 추가\ndiff_cols_test = set(test_t2_r.columns) - set(train_t2_r.columns) #test에서 버림\nprint(len(diff_cols_train), len(diff_cols_test))\nfor col in diff_cols_train:\n test_t2_r[col] = 0.0\ntest_t2_r.drop(diff_cols_test, axis=1,inplace=True)\nprint(test_t2_r.shape)\n\nlen(set(train_t2_r.columns) & set(test_t2_r.columns)) #T2 최종 컬럼 수 (vod type개수)\n\n# +\n# Table1, Table2 merge\n\n# train\nprint(train_t1.shape, train_t2_r.shape , train_t1.shape[1] + train_t2_r.shape[1])\ntrain_t2_r.reset_index(level=0, inplace=True)\ntrain_t3 = train_t1.merge(train_t2_r, on='id')\nprint(\"== Final Train shape:\",train_t3.shape,'\\n')\n\n# test\nprint(test_t1.shape, test_t2_r.shape , test_t1.shape[1] + test_t2_r.shape[1])\ntest_t2_r.reset_index(level=0, inplace=True)\ntest_t3 = test_t1.merge(test_t2_r, on='id')\nprint(\"== Final Test shape:\",test_t3.shape,'\\n')\n# -\n\n# #### 위 과정을 통해 생성된 데이터 (Table 3) 저장 \n\n# +\n# train_t3.to_csv(aidu_framework.config.data_dir + '/ep3_train_t3.csv', index=False)\n# test_t3.to_csv(aidu_framework.config.data_dir + '/ep3_test_t3.csv', index=False)\n# -\n\n# ## 2-2. VOD Type Level에 따른 변수 생성\n\n# #### VOD Type Level 1\n\n#생성 변수 리스트 \ntype_lv1 = pd.DataFrame({(i,_) for i,_ in enumerate(train_t2.lvl_1_vod_type.unique())}, columns=['vtype','lvl_1_vod_type'])\nfor i,_ in type_lv1.iterrows():\n type_lv1.loc[i,'variable'] = 'vod_lv1_'+str(_.vtype)\ntype_lv1 = type_lv1.sort_values('vtype').reset_index(drop=True)\ntype_lv1.drop('vtype',1)\n# type_lv1.drop('vtype',1).to_csv(aidu_framework.config.data_dir + '/type_lv1.csv',index=False)\n\n# +\n### Train set에 대해 변수 생성\ntrain_t2_r1 = train_t2.groupby(['id','lvl_1_vod_type'])['view_cnt'].sum().reset_index()\ntrain_t2_r1 = train_t2_r1.merge(type_lv1, on='lvl_1_vod_type', how='left')\ntrain_t2_r1['vod_type_cd'] = ['vod_lv1_'+str(cd) for cd in train_t2_r1['vtype']] #VOD 코드 값 수정 \ntrain_t2_r1 = train_t2_r1.pivot(index='id', columns='vod_type_cd', values='view_cnt') #VOD 코드를 컬럼으로 변환 \ntrain_t2_r1.fillna(0, inplace=True) #결측치 => 0\ntrain_t2_r1.reset_index(level=0, inplace=True)\n\ntrain_t4 = train_t3.merge(train_t2_r1, on='id') # Table3와 Merge\ntrain_t4\n\n# +\n### Test set에 대해 변수 생성\ntest_t2_r1 = test_t2.groupby(['id','lvl_1_vod_type'])['view_cnt'].sum().reset_index()\ntest_t2_r1 = test_t2_r1.merge(type_lv1, on='lvl_1_vod_type', how='left')\ntest_t2_r1['vod_type_cd'] = ['vod_lv1_'+str(cd) for cd in test_t2_r1['vtype']] #VOD 코드 값 수정 \ntest_t2_r1 = test_t2_r1.pivot(index='id', columns='vod_type_cd', values='view_cnt') #VOD 코드를 컬럼으로 변환 \ntest_t2_r1.fillna(0, inplace=True) #결측치 => 0\ntest_t2_r1.reset_index(level=0, inplace=True)\ntest_t2_r1\n\n# Train set과 동일하게 변수 맞춤 \nonly_train = set(train_t2_r1.columns) - set(test_t2_r1.columns)\nfor c in only_train:\n test_t2_r1[c]=0\nonly_test = set(test_t2_r1.columns) - set(train_t2_r1.columns)\ntest_t2_r1=test_t2_r1.drop(only_test,axis=1)\n\ntest_t4 = test_t3.merge(test_t2_r1, on='id') # Table3와 Merge\ntest_t4\n# -\n\n# #### VOD Type Level 2\n\n#생성 변수 리스트 \ntype_lv2 = pd.DataFrame({(i,_) for i,_ in enumerate(train_t2.lvl_2_vod_type.unique())}, columns=['vtype','lvl_2_vod_type'])\nfor i,_ in type_lv2.iterrows():\n type_lv2.loc[i,'variable'] = 'vod_lv2_'+str(_.vtype)\ntype_lv2 = type_lv2.sort_values('vtype').reset_index(drop=True)\ntype_lv2.drop('vtype',1) \n# type_lv2.drop('vtype',1).to_csv(aidu_framework.config.data_dir + '/type_lv2.csv',index=False)\n\n# +\n### Train set에 대해 변수 생성\ntrain_t2_r2 = train_t2.groupby(['id','lvl_2_vod_type'])['view_cnt'].sum().reset_index()\ntrain_t2_r2 = train_t2_r2.merge(type_lv2, on='lvl_2_vod_type', how='left')\ntrain_t2_r2['vod_type_cd'] = ['vod_lv2_'+str(cd) for cd in train_t2_r2['vtype']] #VOD 코드 값 수정 \ntrain_t2_r2 = train_t2_r2.pivot(index='id', columns='vod_type_cd', values='view_cnt') #VOD 코드를 컬럼으로 변환 \ntrain_t2_r2.fillna(0, inplace=True) #결측치 => 0\ntrain_t2_r2.reset_index(level=0, inplace=True)\n\ntrain_t4 = train_t4.merge(train_t2_r2, on='id') # 이전 데이터와 Merge\ntrain_t4\n\n# +\n### Test set에 대해 변수 생성\ntest_t2_r2 = test_t2.groupby(['id','lvl_2_vod_type'])['view_cnt'].sum().reset_index()\ntest_t2_r2 = test_t2_r2.merge(type_lv2, on='lvl_2_vod_type', how='left')\ntest_t2_r2['vod_type_cd'] = ['vod_lv2_'+str(cd) for cd in test_t2_r2['vtype']] #VOD 코드 값 수정 \ntest_t2_r2['vod_type_cd'] = [_[:-2] for _ in test_t2_r2.vod_type_cd]\ntest_t2_r2 = test_t2_r2.pivot(index='id', columns='vod_type_cd', values='view_cnt') #VOD 코드를 컬럼으로 변환 \ntest_t2_r2.fillna(0, inplace=True) #결측치 => 0\ntest_t2_r2.reset_index(level=0, inplace=True)\ntest_t2_r2\n\n# Train set 과 동일하게 변수 맞춤 \nonly_train = set(train_t2_r2.columns) - set(test_t2_r2.columns)\nfor c in only_train:\n test_t2_r2[c]=0\nonly_test = set(test_t2_r2.columns) - set(train_t2_r2.columns)\ntest_t2_r2=test_t2_r2.drop(only_test,axis=1)\n\ntest_t4 = test_t4.merge(test_t2_r2, on='id') # 이전 데이터와 Merge\ntest_t4\n# -\n\n# #### 위 과정을 통해 생성된 데이터 (Table 4) 저장 \n\n# +\n#train_t4.to_csv(aidu_framework.config.data_dir + '/ep3_train_t4.csv',index=False)\n#test_t4.to_csv(aidu_framework.config.data_dir + '/ep3_test_t4.csv',index=False)\n# -\n\n# ## 2-3. VOD Type Grouping을 통한 변수 생성\n\n# +\n# VOD Type을 확인하여 의미 유사성에 따라 Grouping\n# Grouping한 항목에 대해 사람별 시청건수를 저장 \n\n###################################################\n# VOD Type (vod_type_cd)를 다음과 같이 Grouping\n###################################################\n#종교시청시간\nrelig_vuing_id = [\n140400,\n140401,\n140402,\n140403\n]\n\n# 공공시청시간\npub_vuing_id = [\n140000,\n140100,\n140200,\n140300]\n\n\nmovie_sers_vuing_id = [\n10000,\n10100,\n10200,\n10300,\n10400,\n10500,\n10600,\n10700,\n10800,\n10900,\n11000,\n11100,\n11200,\n11300,\n11400,\n11500,\n11600,\n11700,\n11800,\n11900,\n12000,\n12100,\n12200,\n12300,\n12400,\n12500,\n12600,\n30000,\n30100,\n30200,\n30300,\n30400,\n30500,\n30600,\n30700,\n30800,\n30900,\n31000,\n31100,\n31200,\n31300,\n31400,\n31500,\n31600,\n31601,\n31602,\n31603,\n31604,\n31605,\n31606,\n31607,\n31608,\n31609,\n31610,\n31611,\n31612,\n31613,\n31700,\n31800,\n31900,\n32000,\n32100,\n32200,\n32300,\n32400,\n32500]\n\n\n\n#애니메이션시청시간\nanmt_vuing_id = [\n20000,\n20100,\n20200,\n20300,\n20400,\n20500,\n20600,\n20700,\n20800,\n20900,\n21000,\n21100,\n21200,\n21300,\n21400,\n21500,\n21600,\n21700,\n21800,\n21900,\n22000,\n22100,\n22200,\n22300,\n22400,\n22500,\n22600,\n40000,\n40100,\n40200,\n40300,\n40400,\n40500,\n40600,\n40700,\n40800,\n40900,\n41000,\n41100,\n41200,\n41300,\n41400,\n41500,\n41600,\n41601,\n41602,\n41603,\n41604,\n41605,\n41606,\n41607,\n41608,\n41609,\n41610,\n41611,\n41612,\n41613,\n41700,\n41800,\n41900,\n42000,\n42100,\n42200,\n42300,\n42400,\n42500]\n\n# 액션/SF\naction_sf_vuing_id =[\n10100,\n10200,\n10300,\n11700,\n12400,\n11300,\n20100,\n20200,\n20300,\n21700,\n22400,\n21300,\n30100,\n30200,\n30300,\n31700,\n32400,\n31300,\n40100,\n40200,\n40300,\n41700,\n42400,\n41300]\n\n\n#호러\nhorr_vuing_id=[\n10800,\n20800,\n30800,\n40800]\n\n\n#공포/스릴러\ncrim_thrl_vuing_id=[\n11000,\n12200,\n21000,\n22200,\n31000,\n32200,\n41000,\n42200\n]\n\n\n# 가족\nchdr_famly_vuing_id =[\n10400,\n20400,\n30400,\n40400\n]\n\n\n# 어린이\nchild_vuing_id = [\n41600,\n41601,\n41602,\n41603,\n41604,\n41605,\n41606,\n41607,\n41608,\n41609,\n41610,\n41611,\n41612,\n41613,\n31600,\n31601,\n31602,\n31603,\n31604,\n31605,\n31606,\n31607,\n31608,\n31609,\n31610,\n31611,\n31612,\n31613,\n21600,\n11600,\n12300,\n22300,\n32300,\n42300]\n\n\n# 드라마\ndrama_vuing_id = [\n10500,\n20500,\n30500,\n40500,\n11800,\n21800,\n31800,\n41800]\n\n# 다큐\ndocu_vuing_id =[\n11400,\n21400,\n31400,\n41400\n]\n\n\n# 코메디\ncmdy_vuing_id =[\n10700,\n20700,\n30700,\n40700\n]\n\n# 로멘스\nromc_melo_vuing_id =[\n10600,\n20600,\n30600,\n40600,\n11500,\n21500,\n31500,\n41500\n]\n\n# 유아 애니메이션\nanmt_child_vuing_id= [\n21600,\n41600,\n41601,\n41602,\n41603,\n41604,\n41605,\n41606,\n41607,\n41608,\n41609,\n41610,\n41611,\n41612,\n41613\n]\n\n# 무협\nmtart_vuing_id =[\n10900,\n11100,\n11200,\n20900,\n21100,\n21200,\n30900,\n31100,\n31200,\n40900,\n41100,\n41200]\n\n# 기타\netc_vuing_id = [\n10000,\n11900,\n12000,\n12100,\n12500,\n12600,\n20000,\n21900,\n22000,\n22100,\n22500,\n22600,\n30000,\n31900,\n32000,\n32100,\n32500,\n40000,\n41900,\n42000,\n42100,\n42500\n]\n\n# +\n#생성 변수 리스트 \n\nvars=[\npub_vuing_id\n,movie_sers_vuing_id\n,anmt_vuing_id\n,action_sf_vuing_id\n,horr_vuing_id\n,crim_thrl_vuing_id\n,chdr_famly_vuing_id\n,child_vuing_id\n,drama_vuing_id\n,docu_vuing_id\n,cmdy_vuing_id\n,romc_melo_vuing_id\n,anmt_child_vuing_id\n,mtart_vuing_id\n,etc_vuing_id] \n\n# ('v0', 'relig_vuing_id'),\n# ('v1', 'pub_vuing_id'),\n# ('v2', 'movie_sers_vuing_id'),\n# ('v3', 'anmt_vuing_id'),\n# ('v4', 'action_sf_vuing_id'),\n# ('v5', 'horr_vuing_id'),\n# ('v6', 'crim_thrl_vuing_id'),\n# ('v7', 'chdr_famly_vuing_id'),\n# ('v8', 'child_vuing_id'),\n# ('v9', 'drama_vuing_id'),\n# ('v10', 'docu_vuing_id'),\n# ('v11', 'cmdy_vuing_id'),\n# ('v12', 'romc_melo_vuing_id'),\n# ('v13', 'anmt_child_vuing_id'),\n# ('v14', 'mtart_vuing_id'),\n# ('v15', 'etc_vuing_id')\n\n# +\n#### Train set에 대해 변수 생성\ndf0 = train_t2.copy()\n\ndf = pd.DataFrame({'id':df0.id.unique()})\nsub = df0[df0.vod_type_cd.isin(relig_vuing_id)]\nsub2 = sub.groupby(['id'])['view_cnt'].sum().reset_index()\ndf2 =df.merge(sub2, on=['id'],how='left')\n\nfor v in vars:\n sub = df0[df0.vod_type_cd.isin(v)]\n sub2 = sub.groupby(['id'])['view_cnt'].sum().reset_index()\n df2=df2.merge(sub2, on=['id'],how='left')\n \ndf2.fillna(0, inplace=True)\ns = ['v'+str(i) for i in range(16)]\ndf2.columns = ['id']+s\n\n\ntrain_t5 = train_t4.merge(df2, on='id',how='left') # 이전 데이터와 Merge\ntrain_t5\n\n# +\n#### Test set에 대해 변수 생성\ndf0 = test_t2.copy()\n\ndf = pd.DataFrame({'id':df0.id.unique()})\nsub = df0[df0.vod_type_cd.isin(relig_vuing_id)]\nsub2 = sub.groupby(['id'])['view_cnt'].sum().reset_index()\ndf2 =df.merge(sub2, on=['id'],how='left')\n\nfor v in vars:\n sub = df0[df0.vod_type_cd.isin(v)]\n sub2 = sub.groupby(['id'])['view_cnt'].sum().reset_index()\n df2=df2.merge(sub2, on=['id'],how='left')\n \ndf2.fillna(0, inplace=True)\ns = ['v'+str(i) for i in range(16)]\ndf2.columns = ['id']+s\n\n\ntest_t5=test_t4.merge(df2, on='id',how='left') # 이전 데이터와 Merge\ntest_t5\n# -\n\n# ### 위 과정을 통해 생성된 데이터 (Table 5) 저장\n\n# +\n# train_t5.to_csv(aidu_framework.config.data_dir + '/ep3_train_t5.csv',index=False)\n# test_t5.to_csv(aidu_framework.config.data_dir + '/ep3_test_t5.csv',index=False)\n# -\n\n# ## 2-4. X, y 데이터 분리 \n\n# Data loading\ntrain = pd.read_csv(aidu_framework.config.data_dir + '/ep3_train_t5.csv')\ntest = pd.read_csv(aidu_framework.config.data_dir + '/ep3_test_t5.csv')\ntrain.shape, test.shape\n\n# +\n# Explain / Target variable 분리 \ntrain_x = train.drop(['id','favor_genre'], axis=1)\ntrain_y = train[['favor_genre']]\nprint('== Raw Train set size:', train_x.shape, train_y.shape)\n\ntest_x = test.drop(['id'], axis=1)\nprint('== Raw Test set size:', test_x.shape)\n# -\n\n# ## 2-5. Data Scaling & Encoding \n\n# +\n### Preprocessing\ntrain_x_cate = train_x[['sex_cd','age_cd']]\ntrain_x_num = train_x.drop(['sex_cd','age_cd'], axis=1)\ntrain_x_dumm = pd.get_dummies(train_x_cate)\n\ntest_x_cate = test_x[['sex_cd','age_cd']]\ntest_x_num = test_x.drop(['sex_cd','age_cd'], axis=1)\ntest_x_dumm = pd.get_dummies(test_x_cate)\n\n# Scaling the Train and Test feature set \nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\ntrain_x_scaled = pd.DataFrame(data=scaler.fit_transform(train_x_num),\n columns=train_x_num.columns)\ntest_x_scaled = pd.DataFrame(data=scaler.transform(test_x_num),\n columns=test_x_num.columns)\n\ntrain_x_r = pd.concat([train_x_scaled, train_x_dumm], axis=1) #Scaling\n# train_x_r = pd.concat([train_x_num, train_x_dumm], axis=1) #Non-scaling\nprint(\"== Processed Train X shape: : \", train_x_r.shape)\n\ntest_x_r = pd.concat([test_x_scaled, test_x_dumm], axis=1) #Scaling\n# test_x_r = pd.concat([test_x_num, test_x_dumm], axis=1) #Non-scaling \nprint(\"== Processed Test X shape: : \", test_x_r.shape)\n\n\nY_train_label = train_y.values.astype(object).ravel()\nfrom sklearn import preprocessing\ne = preprocessing.LabelEncoder()\ne.fit(Y_train_label)\ntrain_y_enc = e.transform(Y_train_label)\nprint(\"== Processed Train Y shape: : \", train_y_enc.shape)\n\ne_name_mapping = dict(zip(e.classes_, e.transform(e.classes_)))\nprint('== Y Lable mapping:',e_name_mapping)\n# -\n\n# ## 2-6. PCA를 이용한 차원 축소\n\n# +\nimport pandas as pd\nfrom sklearn.decomposition import PCA\n\nnum = 100 #PCA dimension\npca = PCA(n_components=num)\npca.fit(train_x_scaled)\n\npca_train = pca.transform(train_x_scaled)\nprint(pca_train.shape)\npca_test = pca.transform(test_x_scaled)\nprint(pca_test.shape)\n\ndf_pca_train = pd.DataFrame(pca_train, columns=['pc'+str(i) for i in range(num)])\ndf_pca_test = pd.DataFrame(pca_test, columns=['pc'+str(i) for i in range(num)])\n\ntrain_x_pca = pd.concat([df_pca_train, train_x_dumm], axis=1)\nprint(\"== PCA Train X shape: : \", train_x_pca.shape)\n\ntrain_x_pca = pd.concat([df_pca_test, test_x_dumm], axis=1) \nprint(\"== PCA Test X shape: : \", train_x_pca.shape)\n# -\n\n# # 3. 모델링\n# - Grid Search & Cross Validation 이용\n\n# ## 3-1. XGBoost\n\n# +\nimport datetime\nimport time\nstart_time = time.time()\nprint(\"--- Start Time: %s ---\" % datetime.datetime.now())\n\nn_fold = 3\nseed = 0\nstratified_shuffle_split = StratifiedShuffleSplit(train_size = 0.7, test_size=0.3, n_splits = n_fold, random_state = seed)\n\n# XGBoost 분류기 생성\nmodel = xgb.XGBClassifier(objective='multi:softprob', num_class=10)\n\n# hyperparameter grid 생성 - 제출용 코드에서는 빠른 실행을 위해 grid를 단순하게 설정 \nparam_grid = {\n 'max_depth': [3], #[3, 5, 7],\n 'learning_rate': [0.1], #[0.01, 0.1, 0.2],\n 'n_estimators': [15], #[15, 50, 100],\n 'gamma': [0.1], #[0.1, 0.2],\n 'subsample': [0.3],\n# 'min_child_weight': [0, 0.5, 1],\n# 'max_delta_step': [0], \n# 'colsample_bytree': [0.6, 0.8, 1],\n# 'colsample_bylevel': [1],\n# 'reg_alpha': [1.1, 1.2, 1.3],\n# 'reg_lambda': [1.1, 1.2, 1.3], \n }\n\n# Create a GridSearchCV object\ngrid_search = GridSearchCV(estimator=model,\n param_grid=param_grid,\n n_jobs=4, #Number of jobs to run in parallel\n cv=stratified_shuffle_split,\n refit=True, #Refit an estimator using the best found parameters on the whole dataset\n return_train_score=True, verbose=True)\n\n# grid search\ngrid_result = grid_search.fit(train_x_r, train_y_enc)\n\nprint(\"--- Running Time: %s seconds ---\" % (time.time() - start_time))\n# -\n\n# summarize results\nprint(\"Best: %f using %s\" % (grid_result.best_score_, grid_result.best_params_))\nmeans = grid_result.cv_results_['mean_test_score']\nstds = grid_result.cv_results_['std_test_score']\nparams = grid_result.cv_results_['params']\nfor mean, stdev, param in zip(means, stds, params):\n print(\"%f (%f) with: %r\" % (mean, stdev, param))\n\n# Importance plot\nfig, ax = plt.subplots(figsize=(10,30))\nxgb.plot_importance(grid_result.best_estimator_, ax=ax)\nax.figure.savefig('xbg_importance.png')\n\n# +\n### Best 모델\nxgb_best = grid_result.best_estimator_\nprint('== Best model:',xgb_best)\n\n# Best 모델을 이용하여 Prediction\ntest_x_r = test_x_r[train_x_r.columns]\ntest_probs = xgb_best.predict_proba(test_x_r)\nprint('== Test prob shape:',test_probs.shape)\n\n# +\n### Prediction 결과 확률 값을 담은 DataFrame 생성 \ngenre = [k for k in e_name_mapping.keys()]\n\ndf_test_probs = pd.DataFrame(test_probs, columns=genre)\ndf_test_probs = pd.concat([test['id'], df_test_probs], axis=1)\ndf_test_probs\n\n# +\n### top3 DataFrame 생성\nresult = pd.DataFrame(columns=['id','top1','top2','top3'])\nresult['id'] = test['id']\ncol = df_test_probs.columns[1:]\n\nfor i,v in df_test_probs.iterrows():\n result.loc[i,['top1','top2','top3']] = col[v.values[1:].argsort()[::-1][:3]]\nresult\n\n# +\n### 저장할 파일명 설정\n\n# 파일 count로 저장\nprob_cnt = len([f for f in os.listdir(aidu_framework.config.data_dir) if f.startswith('prob_xgb')]) # directory 안의 파일 수 count\nrank_cnt = len([f for f in os.listdir(aidu_framework.config.data_dir) if f.startswith('rank_xgb')]) # directory 안의 파일 수 count\nf_pred = '/prob_xgb_' + str(prob_cnt) + '.csv'\nf_rank = '/rank_xgb_' + str(rank_cnt) + '.csv'\n\nprint('== Probability save to',f_pred)\nprint('== Output save to',f_rank)\n\n# # ### class 별 확률 저장\n# df_test_probs.to_csv(aidu_framework.config.data_dir + f_pred,index=False)\n# ### top 1 ~3 저장\n# result.to_csv(aidu_framework.config.data_dir + f_rank, header=False, index=False)\n# -\n\n# ## 3-2. LightGBM\n\n# +\nfrom lightgbm import LGBMClassifier\nimport datetime\nimport time\nfrom numpy import mean\nfrom numpy import std\n\nstart_time = time.time()\n\nn_fold = 3\nseed = 0\n\n# evaluate the model\nmodel = LGBMClassifier(objective='multi:softprob', num_class=10, n_jobs=2)\ncv = StratifiedShuffleSplit(train_size = 0.7, test_size=0.3, n_splits = n_fold, random_state = seed)\n\nprint(\"--- Start Time: %s ---\" % datetime.datetime.now())\nn_scores = cross_val_score(model, train_x_r, train_y_enc, scoring='accuracy', n_jobs=4, cv=cv, verbose=True)\nprint(\"--- Running Time: %s seconds ---\" % (time.time() - start_time))\nprint('Accuracy: %.3f (%.3f)' % (mean(n_scores), std(n_scores)))\n# -\n\n# fit the model on the whole dataset\n# model = LGBMClassifier()\nprint(\"--- Start Time: %s ---\" % datetime.datetime.now())\nmodel_fit = model.fit(train_x_r, train_y_enc, verbose=True)\nprint(\"--- Running Time: %s seconds ---\" % (time.time() - start_time))\n\n# Return the predicted probability for each class for each sample.\ny_predict = model_fit.predict(test_x_r, num_iteration=model.best_iteration_)\n# Return the predicted probability for each class for each sample.\ny_predict_prob = model_fit.predict_proba(test_x_r, num_iteration=model.best_iteration_)\n\ndf_test_probs = pd.DataFrame(y_predict_prob, columns=genre)\ndf_test_probs = pd.concat([test['id'], df_test_probs], axis=1)\ndf_test_probs\n\n# +\n### top 1 ~3 DataFrame 생성\nresult = pd.DataFrame(columns=['id','top1','top2','top3'])\nresult['id'] = test['id']\ncol = df_test_probs.columns[1:]\n\nfor i,v in df_test_probs.iterrows():\n result.loc[i,['top1','top2','top3']] = col[v.values[1:].argsort()[::-1][:3]]\nresult\n\n# +\n### 저장할 파일명 설정\n\n# 파일 count로 저장\nprob_cnt = len([f for f in os.listdir(aidu_framework.config.data_dir) if f.startswith('prob_lgb')]) # directory 안의 파일 수 count\nrank_cnt = len([f for f in os.listdir(aidu_framework.config.data_dir) if f.startswith('rank_lgb')]) # directory 안의 파일 수 count\nf_pred = '/prob_lgb_' + str(prob_cnt) + '.csv'\nf_rank = '/rank_lgb_' + str(rank_cnt) + '.csv'\n\nprint('== Probability save to',f_pred)\nprint('== Output save to',f_rank)\n\n# ### class 별 확률 저장\n# df_test_probs.to_csv(aidu_framework.config.data_dir + f_pred, header=False, index=False)\n# ### top 1 ~3 저장\n# result.to_csv(aidu_framework.config.data_dir + f_rank, header=False, index=False)\n# -\n\n# # 4. 앙상블\n\n# ## 4-1. 모델별 예측 확률의 Weighted average를 통한 Top3 장르 선정\n\n# +\n## 예측확률 데이터 로딩\n\n# 모델1\nresult1 =pd.read_csv(aidu_framework.config.data_dir + '/result1_fin_ez.csv') #AIDU-EZ를 통해 생성한 파일\nresult1 = result1[result1.columns.tolist()[2:12]]\nresult1.columns=['_'.join(k.split('_')[3:]) for k in result1.columns]\n\n# 모델2\nresult2 =pd.read_csv(aidu_framework.config.data_dir + '/ep3_t5_ez_100_1024.csv') #AIDU-EZ를 통해 생성한 파일\nresult2 = result2[result2.columns.tolist()[2:12]]\nresult2.columns=['_'.join(k.split('_')[3:]) for k in result2.columns]\n\n# 모델3\ncategory=['ACTION_SF', 'ANMT', 'CHDR_FAMLY', 'CMDY', 'CRIM_THRL', 'DOCU', 'DRAMA', 'HORR', 'MTART', 'ROMC_MELO']\nresult3 =pd.read_csv(aidu_framework.config.data_dir + '/prob_xgb_3.csv',header=None)\nresult3.columns = ['id'] + category\n\n# 모델4\nresult4 =pd.read_csv(aidu_framework.config.data_dir + '/prob_xgb_6.csv',header=None)\nresult4.columns = ['id'] + category\n\n# 모델5\nresult5 =pd.read_csv(aidu_framework.config.data_dir + '/prob_xgb_8.csv',header=None)\nresult5.columns = ['id'] + category\n\n# +\n# Weighted average\nf_prob = pd.DataFrame(columns=['id']+category)\nf_prob['id']=result3['id']\nw = [.1, .1, .3, .3, .2]\nfor c in category:\n f_prob[c] = w[0]*result1[c] + w[1]*result2[c] + w[2]*result3[c] + w[3]*result4[c] + w[4]*result5[c]\n\n# Top3 저장\nf_rank = pd.DataFrame(columns=['id','top1','top2','top3'])\nf_rank['id']=f_prob['id']\ncol = f_prob.columns[1:] #장르 이름만 저장 \nfor i,v in f_prob.iterrows():\n f_rank.loc[i,['top1','top2','top3']] = col[v.values[1:].argsort()[::-1][:3]]\n# -\n\n# ## 4-2. 최종 결과 저장 \n\n# +\n# f_rank.to_csv(aidu_framework.config.data_dir + '/aiplay1115_result_ep3.csv',index=False,header=False)\n","repo_name":"gzone2000/my_machine_learning","sub_path":"ml5/90-1.참조 노트북 이용하자(미디어취향분류-AI해커톤).ipynb","file_name":"90-1.참조 노트북 이용하자(미디어취향분류-AI해커톤).ipynb","file_ext":"py","file_size_in_byte":28470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"30152952859","text":"# # Problem No 1 on Case Study Salary for ANOVA\n#\n# Salary is hypothesized to depend on educational qualification and occupation. To understand the dependency, the salaries of 40 individuals are collected and each person’s educational qualification and occupation are noted. Educational qualification is at three levels, High school graduate, Bachelor, and Doctorate. Occupation is at four levels, Administrative and clerical, Sales, Professional or specialty, and Executive or managerial. A different number of observations are in each level of education – occupation combination. Conduct hypothesis test to get the inferences.\n#\n#\n# # level of significance $\\alpha$ = 0.05\n\n# +\nimport numpy as np\nimport pandas as pd\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom statsmodels.formula.api import ols # For n-way ANOVA\nfrom statsmodels.stats.anova import _get_covariance,anova_lm # For n-way ANOVA\n# %matplotlib inline\nsns.set(color_codes=True)\nfrom warnings import filterwarnings\nfilterwarnings(\"ignore\")\npd.set_option('display.float_format', lambda x: '%.2f' % x)\nimport scipy.stats as stats\nimport math\n# -\n\ndf=pd.read_csv('SalaryData.csv')\n\ndf.head()\n\ndf.info()\n\ndf.describe(include=\"all\")\n\ndf.Education.value_counts()\n\ndf.Occupation.value_counts()\n\ncorrelation = df.corr()\ncorrelation\n\ndf.corr\n\nplt.figure(figsize = (10,8))\nsns.heatmap(df.corr(), annot=True,fmt='.2f');\n\n# # Q1.1 State the null and the alternate hypothesis for conducting one-way ANOVA for both Education and Occupation individually.\n\n# 1. Postulate the Null and Alternate Hypothesis for Salary to Education\n\n# $H_0$: The Salary is depended on educational qualification.\n#\n# $H_1$: The Salary is not depended on educational qualification.\n#\n\ndf.shape\n\nn=df.shape[0]*df.shape[1] #total no of observations\nk=df.shape[1] #no of groups\n\n#Degree of freedom between groups\ndfb=k-1\nprint('Degree of Freedom between groups',dfb)\n#Degree of freedom within groups\ndfw=n-k\nprint('Degree of Freedom within groups',dfw)\n\n# # Q1.2 Perform one-way ANOVA for Education with respect to the variable ‘Salary’. State whether the null hypothesis is accepted or rejected based on the ANOVA results.\n\n# 2. Perform the analysis of variances test on the dataset\n\nformula = 'Salary~Education'\nmodel = ols(formula, df).fit()\naov_table = anova_lm(model)\nprint(aov_table)\n\n# 3. Infere the test result\n\n# Since the p value is less than the significance level, we can reject the null hupothesis and state that Salary is not depended on educational qualification\n\nsns.pointplot(x='Education', y='Salary', data=df, ci=None)\n\naov_table['mean_sq']\n\n# # Q1.3 Perform one-way ANOVA for variable Occupation with respect to the variable ‘Salary’. State whether the null hypothesis is accepted or rejected based on the ANOVA results.\n\n# Postulate the Null and Alternate Hypothesis for Salary to Occupation.\n\n# $H_0$: The Salary is depended on Occupation.\n#\n# $H_1$: The Salary is not depended on Occupation.\n#\n\nformula = 'Salary~Occupation'\nmodel = ols(formula, df).fit()\naov_table = anova_lm(model)\nprint(aov_table)\n\n# Since the p value is greater than the significance level, we can accept the null hupothesis and state that Salary is depended on Occupation\n\nsns.pointplot(x='Occupation', y='Salary', data=df, ci=None)\n\n# # Q1.4 If the null hypothesis is rejected in either (1.2) or in (1.3), find out which class means are significantly different. Interpret the result.\n\naov_table['mean_sq']\n\n# Since mean_sq difference is more between Educational qualification class this means that Education class means are significantly different.\n#\n#\n#\n#\n#\n\n# # Q1.5) What is the interaction between two treatments? Analyze the effects of one variable on the other (Education and Occupation) with the help of an interaction plot.\n\nsns.pointplot(x='Education', y='Salary', data=df, hue='Occupation') \n\nsns.pointplot(x='Occupation', y='Salary', data=df, hue='Education') \n\n# From the above interaction plots, it seems to be little interaction between the two variables.\n#\n# Adm-clerical and sales persons with bachelors and doctorate degrees earn almost similar salarypackages.\n\n# # 1.6 Perform a two-way ANOVA based on the Education and Occupation (along with their interaction Education*Occupation) with the variable ‘Salary’. State the null and alternative hypotheses and state your results. How will you interpret this result?\n\n# $H_0$: The Salary is depended both on Education and Occupation.\n#\n# $H_1$: The Salary is not depended both on Education and Occupation.\n#\n\nformula = 'Salary ~ C(Education) + C(Occupation)'\nmodel = ols(formula, df).fit()\naov_table = anova_lm(model)\n(aov_table)\n\n# Since the p value is lesser than the significance level, we can accept the null hupothesis and state that Salary is depended both with respect to Education and Occupation\n\nsns.pointplot(x='Occupation', y='Salary', data=df, hue='Education',ci=None);\n\n# # Q1.7 Explain the business implications of performing ANOVA for this particular case study.\n\n# By performing the ANOVA test for Salary case study we can say that Salary is not depended on educational qualification but infact it is little dependent on Occupation.\n#\n# But when considered both the class it says that Salary is moderately depended both with respect to Education and Occupation\n\n# # THE END________________________________________________________\n\n# # Problem No 2 on EDA and PCA\n#\n# The dataset Education - Post 12th Standard.csv contains information on various colleges. We are expected to do a Principal Component Analysis for this case study. \n#\n#\n\n# ## The Data Dictionary for the variables are given as follows :- \n# 1)      Names: Names of various university and colleges\n#\n# 2)      Apps: Number of applications received\n#\n# 3)      Accept: Number of applications accepted\n#\n# 4)      Enroll: Number of new students enrolled\n#\n# 5)      Top10perc: Percentage of new students from top 10% of Higher Secondary class\n#\n# 6)      Top25perc: Percentage of new students from top 25% of Higher Secondary class\n#\n# 7)      F.Undergrad: Number of full-time undergraduate students\n#\n# 8)      P.Undergrad: Number of part-time undergraduate students\n#\n# 9)      Outstate: Number of students for whom the particular college or university is Out-of-state tuition\n#\n# 10)   Room.Board: Cost of Room and board\n#\n# 11)   Books: Estimated book costs for a student\n#\n# 12)   Personal: Estimated personal spending for a student\n#\n# 13)   PhD: Percentage of faculties with Ph.D.’s\n#\n# 14)   Terminal: Percentage of faculties with terminal degree\n#\n# 15)   S.F.Ratio: Student/faculty ratio\n#\n# 16)   perc.alumni: Percentage of alumni who donate\n#\n# 17)   Expend: The Instructional expenditure per student\n#\n# 18)   Grad.Rate: Graduation rate\n#\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n# %matplotlib inline\nfrom sklearn import decomposition\nfrom sklearn.preprocessing import scale\nfrom sklearn.decomposition import PCA\n\ndff =pd.read_csv(\"Education+-+Post+12th+Standard.csv\")\n\ndff.head()\n\ndff.tail()\n\nprint('The dataset has {} rows and {} columns'.format(dff.shape[0],dff.shape[1]))\nprint('\\n')\n\ndff.info()\n\ndff.isnull().sum()\n\ndff.shape\n\ndff.describe()\n\ndff.describe(include='all')\n\n# +\ndups = dff.duplicated()\nprint('Number of duplicate rows = %d' % (dups.sum()))\n\ndff[dups]\n# -\n\n# Observations:\n# Dataset has 18 columns and 777 rows\n# The entire dataset is has 16 integer data type, 1 float and 1 object data type. \n# The dataset provided is for the student who enrol in the university / college after 12th std. \n# Column names Name, Accept, Enroll will be more meaningful if associated with S.F.Ratio, Grad.Rate.\n# No duplicate records\n\ndff.boxplot(figsize=(20,3))\nplt.xticks(rotation=90)\nplt.show()\n\n# Here can see that except for Top25perc column all other column has outliers\n\n# # Q2.1 Perform Exploratory Data Analysis [both univariate and multivariate analysis to be performed]. What insight do you draw from the EDA?\n\n# # Univariate Analysis\n\n# +\nfig, axes = plt.subplots(nrows=4,ncols=2)\nfig.set_size_inches(20,18)\n\nsns.histplot(dff['Apps'], kde=True, ax=axes[0][0])\nsns.boxplot(x='Apps', data=dff, ax=axes[0][1])\n\nsns.histplot(dff['Accept'] , kde=True, ax=axes[1][0])\nsns.boxplot(x='Accept', data=dff , ax=axes[1][1])\n\nsns.histplot(dff['Enroll'] , kde=True, ax=axes[2][0])\nsns.boxplot(x='Enroll', data=dff , ax=axes[2][1])\n\nsns.histplot(dff['Top10perc'] , kde=True, ax=axes[3][0])\nsns.boxplot(x='Top10perc', data=dff ,ax=axes[3][1])\n\nplt.show()\n\n# +\nfig, axes = plt.subplots(nrows=5,ncols=2)\nfig.set_size_inches(20,18)\n\nsns.histplot(dff['Top25perc'] , kde=True, ax=axes[0][0])\nsns.boxplot(x='Top25perc', data=dff, ax=axes[0][1])\n\nsns.histplot(dff['F.Undergrad'] , kde=True, ax=axes[1][0])\nsns.boxplot(x='F.Undergrad', data=dff ,ax=axes[1][1])\n\nsns.histplot(dff['P.Undergrad'] , kde=True, ax=axes[2][0])\nsns.boxplot(x='P.Undergrad', data=dff , ax=axes[2][1])\n\nsns.histplot(dff['Outstate'] , kde=True,ax=axes[3][0])\nsns.boxplot(x='Outstate', data=dff , ax=axes[3][1])\n\nsns.histplot(dff['Room.Board'] , kde=True, ax=axes[4][0])\nsns.boxplot(x='Room.Board', data=dff , ax=axes[4][1])\n\nplt.show()\n\n# +\nfig, axes = plt.subplots(nrows=5,ncols=2)\nfig.set_size_inches(20,18)\n\nsns.histplot(dff['Books'] , kde=True, ax=axes[0][0])\nsns.boxplot(x='Books', data=dff , ax=axes[0][1])\n\nsns.histplot(dff['Personal'] , kde=True, ax=axes[1][0])\nsns.boxplot(x='Personal', data=dff , ax=axes[1][1])\n\nsns.histplot(dff['PhD'] , kde=True, ax=axes[2][0])\nsns.boxplot(x='PhD', data=dff , ax=axes[2][1])\n\nsns.histplot(dff['Terminal'] , kde=True, ax=axes[3][0])\nsns.boxplot(x='Terminal', data=dff , ax=axes[3][1])\n\nsns.histplot(dff['S.F.Ratio'] , kde=True, ax=axes[4][0])\nsns.boxplot(x='S.F.Ratio', data=dff , ax=axes[4][1])\n\nplt.show()\n\n# +\nfig, axes = plt.subplots(nrows=3,ncols=2)\nfig.set_size_inches(20,18)\n\nsns.histplot(dff['perc.alumni'] , kde=True, ax=axes[0][0])\nsns.boxplot(x='perc.alumni', data=dff , ax=axes[0][1])\n\nsns.histplot(dff['Expend'] , kde=True, ax=axes[1][0])\nsns.boxplot(x='Expend', data=dff , ax=axes[1][1])\n\nsns.histplot(dff['Grad.Rate'] , kde=True, ax=axes[2][0])\nsns.boxplot(x='Grad.Rate', data=dff , ax=axes[2][1])\n\nplt.show()\n# -\n\ndff['Names'].value_counts\n\n#Univariate Analysis on Categorical Variable\ndff['Names'].value_counts(normalize=True)\n\nplt.figure(figsize = (12,8))\nsns.countplot(dff['Names'])\nfont1 = {'family':'serif','color':'blue','size':20}\nfont2 = {'family':'serif','color':'darkred','size':15}\nplt.title(\"Varieties in Food Categories\",fontdict = font1)\nplt.xlabel(\"Names\",fontdict = font2)\nplt.ylabel(\"Count\",fontdict = font2)\nplt.xticks(rotation=90)\nplt.show()\ndff['Names'].value_counts()\n\ndff.skew(axis=0, skipna=True)\n\n# # Skweness of Data \n# 1) Skweness = 0 -------- Normally Distributed\n#\n#\n# 2) Skweness > 0 ---------Left Skewed\n#\n#\n# 3) Skweness < 0 ---------Right Skewed.\n#\n#\n# From above we can say that Top25perc and Grad.Rate is almost normally distributed.\n#\n#\n\n#Multivariate analysis\ndff.corr()\n\n#Correlation Heatmap\nplt.figure(figsize=(12,7))\nsns.heatmap(dff.corr(), annot=True, fmt='.2f', cmap='Blues')\nplt.show()\n\n# # Q2.2 Is scaling necessary for PCA in this case? Give justification and perform scaling.\n\n# ## Yes it is necessary to do scaling for PCA in this case.\n#\n# **Often the variables of the data set are of different scales i.e. one variable is in millions and other in only 100. For e.g. in our data set many variables are having values in thousands and in other just two digits. Since the data in these variables are of different scales, it is tough to compare these variables.**\n#\n# **Feature scaling (also known as data normalization) is the method used to standardize the range of features of data. Since, the range of values of data may vary widely, it becomes a necessary step in data preprocessing while using machine learning algorithms.**\n#\n# **In this method, we convert variables with different scales of measurements into a single scale.**\n#\n# **StandardScaler normalizes the data using the formula (x-mean)/standard deviation.**\n#\n# **We will be doing this only for the numerical variables.***Often the variables of the data set are of different scales i.e. one variable is in millions and other in only 100. For e.g. in our data set Income is having values in thousands and age in just two digits. Since the data in these variables are of different scales, it is tough to compare these variables.**\n#\n# **Feature scaling (also known as data normalization) is the method used to standardize the range of features of data. Since, the range of values of data may vary widely, it becomes a necessary step in data preprocessing while using machine learning algorithms.**\n#\n# **In this method, we convert variables with different scales of measurements into a single scale.**\n#\n# **StandardScaler normalizes the data using the formula (x-mean)/standard deviation.**\n#\n# **We will be doing this only for the numerical variables.**\n\n# # Since scalling is done only on numerical values we will remove Names Column\n\ndff1=dff.drop(['Names'], axis =1)\ndff1\n\nfrom scipy.stats import zscore\ndff1_num_scaled=dff1.apply(zscore)\ndff1_num_scaled.head()\n\n# # Q2.3 Comment on the comparison between the covariance and the correlation matrices from this data.[on scaled data]\n\n# Correlation is a scaled version of covariance; note that the two parameters always have the same sign\n# (positive, negative, or 0). When the sign is positive, the variables are said to be positively correlated; when the\n# sign is negative, the variables are said to be negatively correlated; and when the sign is 0, the variables are said\n# to be uncorrelated.\n\n# In simple sense correlation,measures both the strength and direction of the linear relationship between two\n# variables\n# Covariance is a measure used to determine how much two variables change in tandem. It indicates the\n# direction of the linear relationship between variables.\n\ncov_mat=pd.DataFrame.cov(dff1_num_scaled)\ncov_mat\n\ncov_matrix= np.cov(dff1_num_scaled.T)\ncov_matrix\n\ndff1_num_scaled.corr()\n\n# # Q 2.4 Check the dataset for outliers before and after scaling. What insight do you derive here?\n\ndff.boxplot(figsize=(20,3))\nplt.xticks(rotation=90)\nplt.show()\n\ndff1_num_scaled.boxplot(figsize=(20,3))\nplt.xticks(rotation=90)\nplt.show()\n\n# We can see that there are many changes in outliers. Here can see that except for Top25perc column all other column has outliers\n\n# # Q2.5 Extract the eigenvalues and eigenvectors. [Using Sklearn PCA Print Both]\n\n# Eigenvalue and Eigenmatrix are mainly used to capture key information that stored in a large matrix.\n# 1. It provides summary of large matrix.\n# 2. Performing computation on large matrix is slow and require more memory and CPU, eigenvectors and\n# eigenvalues can improve the efficiency in computationally intensive task by reducing dimensions after\n# ensuring of the key information is maintained.\n\n#Apply PCA taking all features\nfrom sklearn.decomposition import PCA\npca = PCA(n_components=17, random_state=123)\npca_transformed = pca.fit_transform(dff1_num_scaled)\n\n#Extract eigen values\npca.explained_variance_\n\n#Extract eigen vectors\npca.components_\n\n# # Q2.6 Perform PCA and export the data of the Principal Component (eigenvectors) into a data frame with the original features\n\n# +\n# Apply PCA for the number of decided components to get the loadings and component output\n\n# Using scikit learn PCA here. It maps data to PCA dimensions in one shot\nfrom sklearn.decomposition import PCA\n# NOTE - we are generating only 8 PCA dimensions (dimensionality reduction from 18 to 7)\npca = PCA(n_components=7, random_state=123)\ndf_pca = pca.fit_transform(dff1_num_scaled)\ndf_pca.transpose() # Component output\n# -\n\n#Check the explained variance for each PC\n#Note: Explained variance = (eigen value of each PC)/(sum of eigen values of all PCs)\npca.explained_variance_ratio_\n\ndf_extracted_loadings = pd.DataFrame(pca.components_.T, \n columns = ['PC1','PC2', 'PC3', 'PC4', 'PC5', 'PC6',\n 'PC7'],\n index = dff1_num_scaled.columns)\n\ndf_extracted_loadings\n\n# Scree plot: A scree plot helps the analyst visualize the relative importance of the factors, a sharp drop in\n# the plot signals that subsequent factors are ignorable\n\n#Create a scree plot\nplt.figure(figsize=(8,5))\nsns.lineplot(y=pca.explained_variance_ratio_ ,x=range(1,8),marker='o')\nplt.xlabel('Number of Components',fontsize=10)\nplt.ylabel('Variance Explained',fontsize=10)\nplt.title('Scree Plot',fontsize=12)\nplt.grid()\nplt.show()\n\n# # Q2.7 Write down the explicit form of the first PC \n\npca.components_\n\n#Choose the PCs basis cumulative explained variance\ndf_selected = df_extracted_loadings[['PC1','PC2', 'PC3', 'PC4', 'PC5']]\n\n#Check the selected PCs\ndf_selected\n\n#Check as to how the original features matter to each PC\n#Note: Here we are only considering the absolute values\nplt.figure(figsize = (12,8))\nfor i in range(len(df_selected.columns)):\n plt.subplot(3,2,i+1)\n abs(df_selected[df_selected.columns[i]]).T.sort_values(ascending = False).plot.bar()\n plt.yticks(np.arange(0,1.2,.2))\n plt.title('Abs. loadings of {}'.format(df_selected.columns[i]))\n plt.tight_layout()\n\n# # Q2.8 Consider the cumulative values of the eigenvalues. How does it help you to decide on the optimum number of principal components? What do the eigenvectors indicate?\n\n# We should define the objective first for doing PCA in the first place. Are we doing it for reducing storage requirements, to reduce dimensionality for a\n# classification algorithm, or for some other reason.\n#\n# If we don't have any strict constraints, then we should plot the cumulative sum of eigenvalues.\n# If we divide each value by the total sum of eigenvalues prior to plotting, then your plot will show the fraction of\n# total variance retained vs. number of eigenvalues. The plot will then provide a good indication of when you hit\n# the point of diminishing returns.\n\n#Check the cumlative explained variance ratio to find a cut off for selecting the number of PCs\nnp.cumsum(pca.explained_variance_ratio_)\n\nvar = np.cumsum(np.round(pca.explained_variance_ratio_,3))*100\nvar\n\n# The Cumulative % gives the percentage of variance accounted for by the n components. For example, the\n# cumulative percentage for the second component is the sum of the percentage of variance for the first and\n# second components. It helps in deciding the number of components by selecting the components which\n# explained the high variance\n# In the above array we see that the first feature explains 32% of the variance within our data set while the\n# first two explain 58.3 and so on. If we employ 7 features we capture ~ 85.2% of the variance within the\n# dataset.\n\n# # Q2.9 Explain the business implication of using the Principal Component Analysis for this case study. How may PCs help in the further analysis? [Hint: Write Interpretations of the Principal Components Obtained]\n\n# 1. PCA is a statistical technique and uses orthogonal transformation to convert a set of observations of\n# possibly correlated variables into a set of values of linearly uncorrelated variables. PCA also is a tool to reduce\n# multidimensional data to lower dimensions while retaining most of the information. Principal Component\n# Analysis (PCA) is a well-established mathematical technique for reducing the dimensionality of data, while\n# keeping as much variation as possible.\n#\n#\n# 2. This PCA can only be done on continuous variables\n#\n#\n# 3. There are about 18 variables in the dataset, by applying PCA we will reduce those to just 7 components\n# which will capture 87.6 % variance in the dataset\n#\n\n# # The End-------------------------------------------------------------------------\n","repo_name":"abrangeruchi/Case-Study-on-Anova-using-Salarydataset-and-EDA-and-PCA-using-educaton-12th-std","sub_path":"Project_Advance_Stat.ipynb","file_name":"Project_Advance_Stat.ipynb","file_ext":"py","file_size_in_byte":19891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"26"} +{"seq_id":"9120666135","text":"# + id=\"LLBabeG3KF_1\" colab_type=\"code\" colab={}\nfrom tensorflow.python.keras import backend as K\nfrom tensorflow.python.keras.models import load_model\nfrom tensorflow.python.keras.preprocessing import image\nimport os\nimport numpy as np\n\n# + id=\"6n5MObSFKMMQ\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34} outputId=\"779639d6-da75-452c-a59e-f6e23bd5155a\" executionInfo={\"status\": \"ok\", \"timestamp\": 1565854287277, \"user_tz\": -480, \"elapsed\": 727, \"user\": {\"displayName\": \"Hao Xiang Qiu\", \"photoUrl\": \"https://lh4.googleusercontent.com/-ZrZtiKkCV58/AAAAAAAAAAI/AAAAAAAAJiU/KDdLHGOryUI/s64/photo.jpg\", \"userId\": \"03402855445974220356\"}}\nfrom google.colab import drive\ndrive.mount('/content/drive')\n\n# + id=\"JLBNO7vCKUvW\" colab_type=\"code\" colab={}\nnet = load_model('/content/drive/My Drive/model-resnet50-final.h5') #載入模型\n\n# + id=\"9BB0x6asKdPS\" colab_type=\"code\" colab={}\nfiles = os.listdir('/content/drive/My Drive/test') #載入資料夾\nfiles.sort()\n\n# + id=\"ZtXsHxrFKwkq\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 1000} outputId=\"3f358d86-bc2e-4a7c-d1c5-a891a1faddef\" executionInfo={\"status\": \"ok\", \"timestamp\": 1565857923280, \"user_tz\": -480, \"elapsed\": 101131, \"user\": {\"displayName\": \"Hao Xiang Qiu\", \"photoUrl\": \"https://lh4.googleusercontent.com/-ZrZtiKkCV58/AAAAAAAAAAI/AAAAAAAAJiU/KDdLHGOryUI/s64/photo.jpg\", \"userId\": \"03402855445974220356\"}}\nimages = [] #空串列\npredits= [] #空串列\nfor file in files:\n img = image.load_img(os.path.join('/content/drive/My Drive/test', file), target_size=(224, 224)) #讀取圖片\n x = image.img_to_array(img) #圖片轉成數組\n x = np.expand_dims(x, axis = 0) #增加维度\n pred = net.predict(x)[0] #進行預測\n images.append(file.strip('.jpg')) #增加至空串列\n \n preds=\"{0:.10f}\".format(pred[0]) #取預測值小數點10位\n predits.append(preds)#增加至空串列\n \n print(file) #列印圖片序列\n print(preds) #列印預測值\n\n# + id=\"WoIaOQIoMl52\" colab_type=\"code\" colab={}\nimport pandas as pd\nDic= {\"id\":images,\"Predicted\":predits}\ndf = pd.DataFrame(Dic)\ndf.sort_index(inplace=True) #对DataFrame以index排序\ndf.to_csv('sample_submission.csv',index=None)\n#df2 = pd.DataFrame({'id':np.arange(1,nb_test+1),'label':df['label']})\n\n","repo_name":"greamown/2nd-ML100Days","sub_path":"homework/kaggle期末考_Predits_cat_dog.ipynb","file_name":"kaggle期末考_Predits_cat_dog.ipynb","file_ext":"py","file_size_in_byte":2281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"26"}