diff --git "a/5740.jsonl" "b/5740.jsonl" new file mode 100644--- /dev/null +++ "b/5740.jsonl" @@ -0,0 +1,70 @@ +{"seq_id":"31065100057","text":"# + id=\"c4_lumVxl9uH\"\nimport numpy as np\nimport pandas as pd \nimport sklearn\n\n# + id=\"RykmQf9mmqwU\"\nfrom sklearn.datasets import load_boston\ndf = load_boston()\n\n# + id=\"IkNlcSwxm8rc\"\ndf.keys()\n\n# + id=\"gG5_8vQSnEPc\"\nprint(df.target)\n\n# + id=\"vhw69urdoLBl\"\nboston = pd.DataFrame(df.data, columns=df.feature_names)\nboston.head()\n\n# + id=\"yFMdEMpJpCPK\"\nboston['MEDV'] = df.target\nboston.head()\n\n# + id=\"mp5UqKrBpWML\"\nboston.isnull()\n\n# + id=\"NxH64IPjpg5D\"\nboston.isnull().sum()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"ZdU0tP-8prPr\" outputId=\"f14f77f8-8ac7-4b50-f8d4-df073b259939\"\nfrom sklearn.model_selection import train_test_split\n\nX = boston.drop('MEDV', axis=1)\nY = boston['MEDV']\n\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.15, random_state=5)\nprint(X_train.shape)\nprint(X_test.shape)\nprint(Y_train.shape)\nprint(Y_test.shape)\n\n# + id=\"05wP8buysjAU\"\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_squared_error\n\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"nhueVXdZtszU\" outputId=\"f64e04f5-d572-4195-909f-2e18fce2ad42\"\n## FITTING MODEL ON THE TRAINING DATASET\n\nlin_model = LinearRegression()\nlin_model.fit(X_train, Y_train)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"BS10WpZvuTLj\" outputId=\"40b3752c-2a24-4782-cd08-a0f1848063da\"\n#on training set\ny_train_predict = lin_model.predict(X_train)\nrmse = (np.sqrt(mean_squared_error(Y_train, y_train_predict)))\n\nprint(\"The model performance for training set\")\nprint('RMSE is {}'.format(rmse))\nprint(\"\\n\")\n\n# on testing set\ny_test_predict = lin_model.predict(X_test)\nrmse = (np.sqrt(mean_squared_error(Y_test,y_test_predict)))\nprint(\"The model performance for testing set\")\nprint('RMSE is {}'.format(rmse))\n","repo_name":"afrozyanp/ShapeAI_Python_Machine_Learning","sub_path":"MIRZA_AFROZ.ipynp.ipynb","file_name":"MIRZA_AFROZ.ipynp.ipynb","file_ext":"py","file_size_in_byte":1753,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"38"} +{"seq_id":"15065945853","text":"# +\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport japanize_matplotlib\nimport seaborn as sns\nimport pandas_profiling\nimport os\nimport pickle\n\npd.set_option(\"display.max_columns\", None)\n# pd.set_option(\"display.max_rows\", 200)\n# -\n\nDATA_DIR = '../input/'\n\ndf_2018 = pd.read_csv(DATA_DIR+'train_2018.csv')\nprint(df_2018.shape)\ndf_2018.head()\n\ndf_2017 = pd.read_csv(DATA_DIR+'train_2017.csv')\nprint(df_2017.shape)\ndf_2017.head()\n\ndf_2016 = pd.read_csv(DATA_DIR+'train_2016.csv')\nprint(df_2016.shape)\ndf_2016.head()\n\n# +\nlabel = 'time_played'\n\ncols_num = [\n 'height',\n 'weight',\n 'nth_year',\n 'is_youth',\n 'j1_total_num_played',\n 'j1_total_scores',\n 'j2_total_num_played',\n 'j2_total_scores',\n 'j3_total_num_played',\n 'j3_total_scores',\n 'na_total_num_played',\n 'na_total_scores',\n 'prev3_num_played',\n 'prev2_num_played',\n 'prev1_num_played',\n 'prev3_scores',\n 'prev2_scores',\n 'prev1_scores',\n 'prev3_time_played',\n 'prev2_time_played',\n 'prev1_time_played'\n]\n\ncols_cat = [\n 'team',\n 'position',\n 'birthdate',\n 'salary',\n 'nationality',\n 'prev3_team',\n 'prev2_team',\n 'prev1_team',\n 'prev3_div',\n 'prev2_div',\n 'prev1_div',\n]\n\nfeatures = cols_num + cols_cat + [label]\n# -\n\ncols_rename = {col: col+\"_prev_year\" for col in features}\ndf_train = pd.merge(df_2017[[\"id\"]+features], df_2016[[\"id\"]+features].rename(columns=cols_rename), on=\"id\", how=\"left\")\ndf_test = pd.merge(df_2018[[\"id\"]+features], df_2017[[\"id\"]+features].rename(columns=cols_rename), on=\"id\", how=\"outer\")\n\nprint(df_train[\"id\"].nunique())\ndf_train.head()\n\nprint(df_test[\"id\"].nunique())\ndf_test.head()\n\nos.makedirs(\"../input/orgn\", exist_ok=True)\ndf_train.to_pickle(\"../input/orgn/train.pkl\")\ndf_test.to_pickle(\"../input/orgn/test.pkl\")\n\n\n\ndf_train[label].isnull().sum()\n\nnum_bins = np.floor(1 + np.log2(len(df_train)))\nnum_bins\n\ndf_train[label]\n\ndf_train.loc[:, \"bins\"] = pd.cut(df_train[label], bins=int(num_bins), labels=False)\n\ncols_num = list(df_train.select_dtypes(include='number').columns)\ncols_num\n\nprint(df_train.dtypes[:10])\nprint(df_train.dtypes[10:20])\nprint(df_train.dtypes[20:20])\nprint(df_train.dtypes[30:40])\nprint(df_train.dtypes[40:50])\nprint(df_train.dtypes[50:])\n\nfor col in cols_num:\n print(df_train[col].mean())\n\n\n","repo_name":"mf1611/soccer_nishika","sub_path":"notebooks/make_data.ipynb","file_name":"make_data.ipynb","file_ext":"py","file_size_in_byte":2363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"38"} +{"seq_id":"36095835836","text":"# + colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"elapsed\": 1609, \"status\": \"ok\", \"timestamp\": 1670457381454, \"user\": {\"displayName\": \"Henry Savich\", \"userId\": \"10317851829012013120\"}, \"user_tz\": 360} id=\"CkfNLr3bwM1d\" outputId=\"ac564285-d59b-49ce-de78-3718b3b0fc35\"\n# check system specs\n\n# gpu_info = !nvidia-smi\ngpu_info = '\\n'.join(gpu_info)\nif gpu_info.find('failed') >= 0:\n print('Not connected to a GPU')\nelse:\n print('Connected to a GPU')\n\nfrom psutil import virtual_memory\nram_gb = virtual_memory().total / 1e9\n\nif ram_gb < 20:\n print('Not using a high-RAM runtime: {:.1f} gigabytes of available RAM'.format(ram_gb))\nelse:\n print('Using a high-RAM runtime: {:.1f} gigabytes of available RAM'.format(ram_gb))\n\n# + id=\"nRhUTne0pj1Z\"\nimport pandas as pd\nimport numpy as np\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"elapsed\": 17577, \"status\": \"ok\", \"timestamp\": 1670457399008, \"user\": {\"displayName\": \"Henry Savich\", \"userId\": \"10317851829012013120\"}, \"user_tz\": 360} id=\"abnMMJxtptv1\" outputId=\"60fe5683-d3b2-4bf0-d69d-285b57bbd788\"\nfrom google.colab import drive\ndrive.mount('/content/gdrive')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"elapsed\": 9, \"status\": \"ok\", \"timestamp\": 1670457399009, \"user\": {\"displayName\": \"Henry Savich\", \"userId\": \"10317851829012013120\"}, \"user_tz\": 360} id=\"MZHDFnTQpxb2\" outputId=\"c65cd94d-6f47-4583-f454-d52d110cc9ec\"\n# note: place shortcut to shared project folder in google drive root directory\n# %cd /content/gdrive/MyDrive/ml2_project\n\n# + id=\"RoEB_guxuHF5\"\n# !pip install sentence_transformers\n\n# + id=\"4gr0Cmwgpj1b\"\n# load models\n\nfrom sentence_transformers import SentenceTransformer\nimport torch\n\n# base_model = SentenceTransformer('all-MiniLM-L12-v2')\n# base_model.save('./all-MiniLM-L12-v2')\nbase_model = SentenceTransformer('./models/all-MiniLM-L12-v2')\nbase_model = base_model.to(torch.device('cuda')) # use GPU\n\nft_final_model = SentenceTransformer('./models/finetune_mnr_final')\nft_final_model = ft_final_model.to(torch.device('cuda')) # use GPU\n\n\n# + [markdown] id=\"UTaJtyPe5lrO\"\n# ### Small Dataset\n# Load small dataset and append embeddings from base model and final fine-tuned model\n\n# + id=\"COEuIZ33pj1c\"\nsds = pd.read_csv('data/small_dataset.csv')\n\n# + id=\"5GzP3isbpj1c\"\nembeddings_base = base_model.encode(sds['lyrics'])\n\n# + id=\"2vh7RWiP62KO\"\nembeddings_ft_final = ft_final_model.encode(sds['lyrics'])\n\n# + id=\"4rizQKlrpj1c\"\nsds['embeddings_base'] = list(embeddings_base)\nsds['embeddings_ft_final'] = list(embeddings_ft_final)\n\n# + id=\"RWoEBLqzxGVt\"\nsds.to_csv('data/small_dataset_w_embeddings.csv')\n\n# + [markdown] id=\"y7LMXs7T5pXa\"\n# ### Large Dataset\n# Load full dataset and append embeddings from base model and final fine-tuned model\n\n# + id=\"g_EM3fXl5oSs\"\ndf = pd.read_csv('data/clean_dataset.csv')\n\n# + id=\"oj4hh8EV5sAv\"\nembeddings_base = base_model.encode(df['lyrics'])\n\n# + id=\"ygGDtD1X66Ku\"\nembeddings_ft_final = ft_final_model.encode(df['lyrics'])\n\n# + id=\"RBZUqYpd5sGR\"\ndf['embeddings_base'] = list(embeddings_base)\ndf['embeddings_ft_final'] = list(embeddings_ft_final)\n\n# + id=\"yC-6asu-5sKa\"\ndf.to_csv('data/clean_dataset_w_embeddings.csv')\n\n# + id=\"J0axynuZ5sQF\"\n\n","repo_name":"santarabantoosoo/semantic_song_search","sub_path":"4_lyrics_embed.ipynb","file_name":"4_lyrics_embed.ipynb","file_ext":"py","file_size_in_byte":3208,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"38"} +{"seq_id":"6788748518","text":"from PIL import Image, ImageFont, ImageDraw, ImageOps\nimport os\nimport numpy as np\nimport datetime\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport photo_processing as pp\n\n# +\nfilepath = 'photos/Failed' \n\nphotos = np.zeros((len(os.listdir(filepath)),4928,6560),dtype=np.float)\nphoto_slices = np.zeros((len(os.listdir(filepath)),450))\ndatetimes = []\n\nfor i in range(len(os.listdir(filepath))): \n filename = os.listdir(filepath)[i]\n file_datetime = datetime.datetime(int(filename[:4]),int(filename[5:7]),int(filename[8:10]),int(filename[11:13]),int(filename[13:15]),int(filename[15:17]))\n datetimes.append(file_datetime)\n \n photos[i] = np.asarray(Image.open(filepath + '/' + os.listdir(filepath)[i]).convert('L'),dtype=np.float)\n photo_slices[i] = pp.slice_photo(photos[i])\n \nbaseline, std = pp.leading_baseline(photo_slices,300,0,100)\nprocessed_slices = [photo_slices[i]-baseline[i] for i in range(len(baseline))]\n\n\nfor i in range(len(photo_slices)):\n start, end = pp.std_dev_pulsefinding(processed_slices[i],std[i],300,60,rising_thresh=3.0,falling_thresh=1.0)\n ice_widths.append(end-start)\n \n plt.plot([start,start],\n [0,30],'r--')\n plt.plot([end,end],[0,30],'r--')\n plt.plot(np.arange(450),processed_slices[i])\n plt.xlabel('Pixel index in slice')\n plt.ylabel('Pixel brightness over baseline')\n plt.show()\n \n fig = plt.figure(figsize=(20,30))\n ax = fig.add_subplot(111)\n ax.imshow(photos[i],cmap='gray',clim=(0,255),aspect='equal')\n mid_slice_x = np.arange(2200+start,2200+end)\n mid_slice_y = mid_slice_x - 1300\n plt.plot(mid_slice_x,mid_slice_y,'r')\n slice_x = np.arange(2150,2600)\n slice_y = slice_x - 1200\n plt.plot(slice_x,slice_y,'r--')\n slice_x = np.arange(2250,2700)\n slice_y = slice_x - 1400\n plt.plot(slice_x,slice_y,'r--')\n\n plt.show()\n# -\n\nplt.plot(datetimes, ice_widths)\nplt.xlabel('Date and time')\nplt.ylabel('Ice ring width (pixels)')\nplt.xticks(rotation = 45)\nplt.show()\n","repo_name":"ryansmith63/CHILLAX_photos","sub_path":"ice_photo_measuring.ipynb","file_name":"ice_photo_measuring.ipynb","file_ext":"py","file_size_in_byte":2005,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"38"} +{"seq_id":"21551226506","text":"#\n\n#\n\n# ![](py.svg.png)\n\n# [github](https://github.com/)\n\n# # loops\n\n# ## while loop 2 for loop\n\n# ### .syntax while condition statements\n\n# +\n# print the number 1 and 20 using while loop\n# -\n\nn = int(input(\"enter the number\"))\ni = 1\nwhile i<=n: #i<10,2<10\n print(i, end=\" \")\n i =i+1 #1 =2, 2+1=3\n\n#input:10\ni=1\nn=int(input(\"no\"))\nsum=0\nwhile i<=n:\n if i%2==0:\n sum=sum+i\n i=i+1\nprint(sum)\n\nfor i in \" ptyhon \":\n print(i)\n\n\n","repo_name":"Laxmanreddy675/CRT-Batch","sub_path":"day2.ipynb","file_name":"day2.ipynb","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"38"} +{"seq_id":"34490180212","text":"# # Photogate explicado paso a paso\n#\n# ## Photogate y MotionDAQ\n#\n# El [*photogate*](https://www.vernier.com/product/photogate/),\n# o fotosensor de barrera,\n# es un sensor que permite medir tiempos de manera muy precisa.\n# Para ello,\n# tiene un emisor de luz infrarroja\n# y un detector de luz.\n# Cuando detecta la luz infrarroja,\n# emite una señal de un dado voltaje.\n# Cuando un objeto atravieza el sensor,\n# bloquea la luz,\n# y el sensor emite otro voltaje.\n# Midiendo el tiempo cuando se produce el cambio de voltaje,\n# podemos saber cuando un objeto pasó por el *photogate*.\n#\n# La señal del *photogate* la podemos digitalizar con el MotionDAQ.\n# Este mide el voltaje que emite el sensor\n# para un conjunto de tiempos discretos.\n# El tiempo $\\Delta t$ entre mediciones se puede controlar,\n# elijiendo la frecuencia de muestreo $f = 1/\\Delta t$.\n# Luego,\n# podemos exportar estas mediciones como un archivo de texto.\n#\n# En este notebook,\n# vamos a ver como podemos cargar\n# y analizar esas mediciones para obtener los tiempos en que se bloqueó o desbloquó el sensor.\n\n# ## Paquetes\n#\n# Importamos los paquetes y funciones que vamos a necesitar:\n#\n# - la función `Path` de `pathlib`,\n# que nos permite manejar las \"rutas\" o ubicaciones de los archivos.\n# En particular,\n# la vamos a usar para encontrar todos los archivos de medición que usemos.\n# - `numpy`, para operar con arrays numéricos\n# - `matplotlib`, para graficar\n# - `pandas`, que solo vamos a usar para leer los archivos.\n# Es muy usado porque proporciona varias comodidades sobre `numpy`,\n# pero es confuso de usar al principio.\n\n# +\nfrom pathlib import Path\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n# -\n\n# ## Buscando los archivos\n\n# Buscamos todos los archivos que terminan con `.txt` en la carpeta actual.\n#\n# :::{note}\n# Pueden decargar unos archivos de muestra de acá:\n# - [1cm.txt](https://github.com/maurosilber/python-tutorial/raw/main/book/laboratorio/photogate/1cm.txt)\n# - [2cm.txt](https://github.com/maurosilber/python-tutorial/raw/main/book/laboratorio/photogate/2cm.txt)\n# :::\n\n# +\ncarpeta = Path() # carpeta actual\narchivos = list(carpeta.glob(\"*.txt\")) # lista de archivos que terminan con .txt\n\narchivos\n# -\n\n# ## Cargando datos de un archivo\n#\n# Si abrimos un archivo en un editor de texto (`notepad`),\n# veriamos lo siguiente:\n\n# !head \"1cm.txt\"\n\n# Es un archivo de texto,\n# donde las primeras dos filas tienen *metadata*:\n#\n# - la hora a la que se tomó la medición, y\n# - número de corrida.\n#\n# Las siguientes filas tienen los datos\n# agrupados en dos columnas,\n# que estan separadas por \"un espacio\".\n# En programación,\n# hay al menos dos tipos de espacios:\n#\n# - `\" \"`, el espacio común que inserta la barra espaciadora, y\n# - `\"\\t\"`, el espacio que inserta la tecla Tab.\n#\n# En este caso,\n# es el segundo.\n#\n# También,\n# los números usan una coma como separador decimal.\n#\n# Todo esto hay que decirselo a Python,\n# para que sepa como interpretar el archivo.\n\n# +\ndf = pd.read_csv(\n archivos[0], # el primer archivo,\n skiprows=3, # que ignore las primeras 3 filas\n delimiter=\"\\t\", # separador Tab\n decimal=\",\", # coma decimal\n)\n\ndf\n# -\n\n# La variable `df` tiene un `DataFrame` de `pandas`.\n# Podemos extraer el `array` de `numpy` interno con `df.values`:\n\n# +\ndata = df.values\n\ndata\n# -\n\n# Este `array` tiene 996 filas y 2 columnas:\n\ndata.shape\n\n# Para más (o menos) comodidad,\n# podemos separar cada una en una variable:\n\nt = data[:, 0] # tiempo [s]\nv = data[:, 1] # voltaje [V]\n\n# ## Graficar los datos\n#\n# Es importante visualizar los datos,\n# para asegurarnos de que no haya habido problemas de medición.\n# Grafiquemos estas dos variables:\n\nplt.figure(figsize=(6, 2))\nplt.xlabel(\"Tiempo [s]\")\nplt.ylabel(\"Voltaje [V]\")\nplt.plot(t, v)\n\n# Hagamos zoom sobre el primer salto,\n# y graficamos los valores discretos de la señal:\n\nplt.figure(figsize=(6, 2))\nplt.xlabel(\"Tiempo [s]\")\nplt.ylabel(\"Voltaje [V]\")\nplt.plot(t, v, marker=\"o\", linestyle=\"--\")\nplt.xlim(0.12, 0.18)\nplt.grid()\n\n# ### Preguntas\n#\n# - ¿En qué tiempo se bloqueó el sensor?\n# - ¿Qué error podemos asignarle a ese tiempo?\n# - ¿Cómo podemos encontar \"automaticamente\" ese tiempo?\n# ¿Qué distingue a esos tiempos de los demás?\n\n# ## Calcular diferencias de voltaje\n#\n# Para encontrar el cambio de voltaje,\n# podemos calcular la diferencia entre un punto $i$ y el siguiente $i+1$.\n# `numpy` incluye una función para esto: `np.diff`.\n\ndif_de_v = np.diff(v)\n\n# Este vector tiene un valor menos el original,\n# ya que no puede calcular la diferencia del último con el siguiente\n# (¡ya no hay siguiente!).\n\nnp.size(v)\n\nnp.size(dif_de_v)\n\n# Para graficarlo,\n# vamos a ignorar el tiempo,\n# y dejar que grafique contra el número de indice del array:\n\nplt.figure(figsize=(6, 2))\nplt.xlabel(\"Indice del array\")\nplt.ylabel(\"Dif. de voltaje [V]\")\nplt.plot(dif_de_v, marker=\".\", linestyle=\"--\")\n\n# Si hacemos zoom al primer salto,\n# y superponemos la señal original,\n# podemos ver que da (practicamente) 0 en todos lados,\n# menos en los cambios de voltaje:\n\nplt.figure(figsize=(6, 2))\nplt.xlabel(\"Indice del array\")\nplt.ylabel(\"Voltaje [V]\")\nplt.plot(v, label=\"Voltaje\", marker=\".\", linestyle=\"--\")\nplt.plot(dif_de_v, label=\"Dif. de voltaje\", marker=\".\", linestyle=\"--\")\nplt.legend()\nplt.xlim(0, 40)\n\n# Pero ojo,\n# no es exactamente 0,\n# ya que el voltaje fluctua levemente:\n\nv[:5]\n\ndif_de_v[:5]\n\n# ## Encontrar valores que cumplen cierta condicion\n#\n# Para encontrar los valores dentro de un `array` que cumplen cierta condicion,\n# se pueden hacer lo siguiente:\n\n# +\ny = np.array([0, 0, 5, 5, 0, 5]) # array de ejemplo\n\ny > 3\n# -\n\n# que devuelve un vector de verdaderos (`True`) y falsos (`False`) para cada elemento.\n#\n# Si quieren obtener las posiciones o indices donde se cumplió la condición,\n# es decir, donde están los `True`,\n# pueden hacer así:\n\n# +\npos = np.nonzero(y > 3)\n\npos\n# -\n\n# Si quisieran extraer los valores de `y` que están en esas posiciones:\n\ny[pos]\n\n# Entonces,\n# en el caso de la señal del fotosesnsor,\n# podemos encontrar los \"saltos\",\n# tanto positivos y negativos,\n# como:\n\n# +\npos = np.nonzero(np.abs(dif_de_v) > 2.5)\n\npos\n# -\n\n# Peor no nos interesa obtener el valor del voltaje en esas posiciones,\n# sino los tiempos en esas posiciones:\n\n# +\ntiempo_saltos = t[pos]\n\ntiempo_saltos\n# -\n\n# ## Encontrar periodos\n\n# Finalmente,\n# si nos interesa encontrar periodos,\n# podemos calcular las diferencias entre los tiempos correspondientes.\n# Esto dependerá del experimento.\n#\n# Por ejemplo,\n# si necesitamos obtener 1 de cada 4 tiempos,\n# podemos tomar una \"rebanada\" (*slice*) del array con la siguiente expresion:\n\ntiempo_saltos[::4]\n\n# En general,\n# la notación es `array[desde:hasta:paso]`.\n# Si omitimos uno,\n# por defecto son:\n#\n# - `desde`: 0\n# - `hasta`: hasta el final\n# - `paso`: 1\n#\n# Por ejemplo:\n#\n# - `array[2:8:3]`\n# - `array[:5]`: hasta el 5to elemento.\n# - `array[10::3]`: desde el 10mo elemento cada 3.\n# - etc.\n\n# Luego,\n# podriamos calcular la diferencia entre valores consecutivos con:\n\nnp.diff(tiempo_saltos[::4])\n\n# ## Más periodos\n\n# Para aprovechar todos los datos,\n# también pueden calcular los periodos cada 4,\n# pero empezando de la segunda medicion (indice 1):\n\nnp.diff(tiempo_saltos[1::4])\n\n# Y desde la tercera y cuarta medicion.\n#\n# Pueden hacer todo esto en un paso con la siguiente expresion:\n\ntiempo_saltos[4:] - tiempo_saltos[:-4]\n\n# Para ver que esta haciendo,\n# generemos un array más simple:\n\nx = np.arange(6)\nx\n\n# Si tomamos desde el segundo hasta el final,\n# obtenemos:\n\nx[2:]\n\n# Y si tomamos desde el principio hasta 2 menos del final,\n# tenemos:\n\nx[:-2]\n\n# Luego,\n# haciendo la diferencia elemento a elemento,\n# es hacer la diferencia cada dos elementos:\n\nx[2:] - x[:-2]\n","repo_name":"maurosilber/python-tutorial","sub_path":"book/laboratorio/photogate/paso_a_paso.ipynb","file_name":"paso_a_paso.ipynb","file_ext":"py","file_size_in_byte":7787,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"38"} +{"seq_id":"12722043568","text":"import pandas as pd\nfrom pandas import DataFrame\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport statsmodels.api as sm\nfrom statsmodels.tsa.stattools import adfuller, kpss\nfrom statsmodels.graphics import tsaplots\nfrom statsmodels.tsa.arima.model import ARIMA\nfrom sklearn.metrics import mean_absolute_error, mean_squared_error\nfrom statsmodels.graphics.tsaplots import plot_acf, plot_pacf\n\nne_df = pd.read_csv(\"ne_train.csv\")\n\nne_df.head()\n\nsouth = pd.read_csv('south_train.csv')\n\n\n# # ARIMA Model: NE\n#\n\n# ### Check data is stationary using ADF and KPSS test\n\ndef adf_test(df):\n adf_result = adfuller(df)\n print('ADF Statistic:', adf_result[0])\n print('p-value:', adf_result[1])\n print('Critical Values:', adf_result[4])\nadf_test(ne_df['covid_19_confirmed_cases'])\n\n\ndef kpss_test(time_series):\n kpss_result = kpss(time_series)\n print('\\nKPSS Statistic:', kpss_result[0])\n print('p-value:', kpss_result[1])\n print('Critical Values:', kpss_result[3])\nkpss_test(ne_df['covid_19_confirmed_cases'])\n\nne_df.plot(x = 'date', y ='covid_19_confirmed_cases', \n title = 'NE Confirmed Cases Time Series', figsize = (15,10))\n\n\n# ### Remove zero from NE df and re-run stationary tests\n# # ADF is non-stationary and KPSS shows non-stationary -> remove zeroes to better improve, attempt differncing and log transformation\n\nne_df_filtered = ne_df[ne_df['covid_19_confirmed_cases'] != 0]\n\nne_df_filtered['cases_diff'] = ne_df_filtered['covid_19_confirmed_cases'].diff()\nne_df_filtered = ne_df_filtered.dropna()\n\n\ndef adf_test(df):\n adf_result = adfuller(df)\n print('ADF Statistic:', adf_result[0])\n print('p-value:', adf_result[1])\n print('Critical Values:', adf_result[4])\nadf_test(ne_df_filtered['cases_diff'])\n\n\ndef kpss_test(time_series):\n kpss_result = kpss(time_series)\n print('\\nKPSS Statistic:', kpss_result[0])\n print('p-value:', kpss_result[1])\n print('Critical Values:', kpss_result[3])\nkpss_test(ne_df_filtered['cases_diff'])\n\nne_df_filtered.plot(x = 'date', y ='cases_diff', \n title = 'NE Confirmed Cases Time Series (Differencing)', figsize = (15,8))\n\nne_df_filtered['cases_log'] = np.log(ne_df_filtered['covid_19_confirmed_cases'])\n\nadf_test(ne_df_filtered['cases_log'])\n\nkpss_test(ne_df_filtered['cases_log'])\n\nne_df_filtered.plot(x = 'date', y ='cases_log', \n title = 'NE Confirmed Cases Time Series (Log Transform)', figsize = (15,8))\n\n# #### ADF and KPSS test show that the data becomes stationary with a log transformation\n\n# ### Autocorrelation Plots\n\nplt.figure(figsize=(15, 10))\nplot_acf(ne_df_filtered['cases_log'], lags=65)\nplt.title('Autocorrelation (ACF) Plot')\nplt.xlabel(\"Lag\")\nplt.show()\n\nplt.figure(figsize=(12, 10))\nplot_pacf(ne_df_filtered['cases_log'], lags=65)\nplt.title('Partial Autocorrelation (PACF) Plot')\nplt.xlabel(\"Lag\")\nplt.show()\n\n# Based on the ACF and PACF plots, I will attempt a model with order (1,1,2) and (1,1,1)\n\n# ### Models\n\nmodel1 = ARIMA(ne_df_filtered['cases_log'], order=(1, 1, 2))\nresults1 = model1.fit()\nresults1.summary()\n\nplt.figure(figsize=(12, 10))\nplt.plot(ne_df_filtered['cases_log'], label='Original')\nplt.plot(results1.fittedvalues, color='red', label='Fitted')\nplt.legend()\nplt.title('ARIMA Model1 Fitting')\nplt.show()\n\nmodel2 = ARIMA(ne_df_filtered['cases_log'], order=(1, 1, 1))\nresults2 = model2.fit()\nresults2.summary()\n\nplt.figure(figsize=(12, 10))\nplt.plot(ne_df_filtered['cases_log'], label='Original')\nplt.plot(results2.fittedvalues, color='red', label='Fitted')\nplt.legend()\nplt.title('ARIMA Model2 Fitting')\nplt.show()\n\n# Model 2 appears to be better fitted to the actual data\n\n# Calculating MAE and residuals\n\nne_pred = results2.fittedvalues\nmean_absolute_error(np.exp(ne_df_filtered['cases_log']), np.exp(ne_pred))\n\n# to prove that model 2 was better fitted, finding mae of model 1 -> mae is higher\nne_pred = results1.fittedvalues\nmean_absolute_error(np.exp(ne_df_filtered['cases_log']), np.exp(ne_pred))\n\n# +\nresiduals = ne_df_filtered['cases_log'] - results2.fittedvalues\n\nplt.figure(figsize=(15, 12))\nplt.plot(residuals)\nplt.title('Residual Plot')\nplt.ylabel('Residuals')\nplt.axhline(0, color='black', linestyle='--', linewidth=1) \nplt.show()\n# -\n\n# # ARIMA Model - South\n\nadf_test(south['covid_19_confirmed_cases'])\n\nkpss_test(ne_df['covid_19_confirmed_cases'])\n\n# #### Tests show that the data is not stationary -> try to transform via log and differencing, also remove zeroes\n\nsouth_filtered = south[south['covid_19_confirmed_cases'] != 0]\nsouth_filtered['cases_diff'] = south_filtered['covid_19_confirmed_cases'].diff()\nsouth_filtered = south_filtered.dropna()\n\nadf_test(south_filtered['cases_diff'])\n\nkpss_test(south_filtered['cases_diff'])\n\nsouth_filtered.plot(x = 'date', y ='cases_diff', \n title = 'South Confirmed Cases Time Series (Differencing)', figsize = (15,8))\n\nsouth_filtered['cases_log'] = np.log(south_filtered['covid_19_confirmed_cases'])\n\nadf_test(south_filtered['cases_log'])\n\nkpss_test(south_filtered['cases_log'])\n\nsouth_filtered.plot(x = 'date', y ='cases_log', \n title = 'South Confirmed Cases Time Series (Log)', figsize = (15,8))\n\n# Log Transformation proved to be better suited for the dataset\n\n# ### Autocorrelation Plots\n\nplt.figure(figsize=(15, 10))\nplot_acf(south_filtered['cases_log'], lags=65)\nplt.title('Autocorrelation (ACF) Plot')\nplt.xlabel(\"Lag\")\nplt.show()\n\nplt.figure(figsize=(12, 10))\nplot_pacf(south_filtered['cases_log'], lags=65)\nplt.title('Partial Autocorrelation (PACF) Plot')\nplt.xlabel(\"Lag\")\nplt.show()\n\n# ### Model\n\nmodel1 = ARIMA(south_filtered['cases_log'], order=(1, 1, 0))\nresults1 = model1.fit()\nresults1.summary()\n\nplt.figure(figsize=(12, 10))\nplt.plot(south_filtered['cases_log'], label='Original')\nplt.plot(results1.fittedvalues, color='red', label='Fitted')\nplt.legend()\nplt.title('ARIMA Model1 Fitting')\nplt.show()\n\nsouth_pred = results1.fittedvalues\nmean_absolute_error(np.exp(south_filtered['cases_log']), np.exp(south_pred))\n\n# +\nresiduals = south_filtered['cases_log'] - results1.fittedvalues\n\nplt.figure(figsize=(15, 12))\nplt.plot(residuals)\nplt.title('Residual Plot')\nplt.ylabel('Residuals')\nplt.axhline(0, color='black', linestyle='--', linewidth=1) \nplt.show()\n# -\n\n\n","repo_name":"zshi719/LTV_DataSci_Capstone_Project","sub_path":"models/ARIMA/lalla_new_arima.ipynb","file_name":"lalla_new_arima.ipynb","file_ext":"py","file_size_in_byte":6217,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"33"} +{"seq_id":"70327820255","text":"import random\nimport pylab\n\n\nclass Location(object):\n \n def __init__(self,x,y):\n self.x, self.y = x, y\n \n def move(self, deltaX, deltaY):\n return Location(self.x + deltaX, self.y + deltaY)\n \n def getX(self):\n return self.x\n \n def getY(self):\n return self.y\n\n def distFrom(self, other):\n ox, oy = other.x, other.y \n xDist, yDist = self.x - ox, self.y - oy\n return (xDist**2 + yDist**2)**0.5 # Euclidean Distance\n \n def __str__(self):\n return '<' + str(self.x) + ', ' + str(self.y) + '>'\n \n\n\nclass Field(object):\n \n def __init__(self):\n self.drunks = {}\n \n def addDrunk(self, drunk, loc):\n if drunk in self.drunks:\n raise ValueError('Duplicate drunk')\n else:\n self.drunks[drunk] = loc\n \n def moveDrunk(self, drunk):\n if drunk not in self.drunks:\n raise ValueError('Drunk not in field')\n xDist, yDist = drunk.takeStep() \n currentLocation = self.drunks[drunk]\n #use move method of Location to get new location\n self.drunks[drunk] = currentLocation.move(xDist, yDist)\n \n def getLoc(self, drunk):\n if drunk not in self.drunks:\n raise ValueError('Drunk not in field')\n return self.drunks[drunk]\n\n\nclass Drunk(object): \n def __init__(self, name = None):\n self.name = name\n def __str__(self):\n if self != None:\n return self.name\n return 'Anonymous' \n \n\n\nclass UsualDrunk(Drunk):\n def takeStep(self):\n stepChoices = [(0,1), (0,-1), (1,0), (-1,0)] # Random walk modelling\n return random.choice(stepChoices)\n\n\n# +\ndef walk(f, d, numSteps): # f = Field() , d = Drunk()\n start = f.getLoc(d)\n for s in range(numSteps):\n f.moveDrunk(d)\n return start.distFrom(f.getLoc(d))\n\ndef simWalks(numSteps, numTrials, dClass): # dClass = Drunk Class\n Homer = dClass()\n origin = Location(0,0)\n distances = []\n for t in range(numTrials):\n f = Field()\n f.addDrunk(Homer, origin)\n distances.append(round(walk(f, Homer, numSteps), 1)) \n return distances\n\ndef drunkTest(walkLenghts, numTrials, dClass):\n for numSteps in walkLenghts:\n distances = simWalks(numSteps, numTrials, dClass)\n print(dClass.__name__, 'random walk of', numSteps, 'steps')\n print(' Mean =', round(sum(distances)/len(distances),4))\n print(' Max=', max(distances), 'Min=', min(distances))\n\n\n# -\n\ndrunkTest((10, 100, 1000, 10000), 100, UsualDrunk)\n\ndrunkTest((0,1), 100, UsualDrunk)\n\n\n# +\nclass NSDrunk(Drunk):\n def takeStep(self):\n stepChoices = [(0, 1), (0, -2), (1, 0), (-1, 0)]\n return random.choice(stepChoices)\n \nclass EWDrunk(Drunk):\n def takeStep(self):\n stepChoices = [(1, 0), (-1, 0)]\n return random.choice(stepChoices)\n\n\n# -\n\ndef simAll(drunkKinds, walkLenghts, numTrials):\n for dClass in drunkKinds:\n drunkTest(walkLenghts, numTrials, dClass)\n\n\nsimAll((UsualDrunk, NSDrunk, EWDrunk), (100, 1000), 10)\n\n\nclass styleIterator(object):\n def __init__(self, styles):\n self.index = 0\n self.styles = styles\n def nextStyle(self):\n result = self.styles[self.index]\n if self.index == len(self.styles) - 1:\n self.index = 0\n else:\n self.index += 1\n return result \n \n\n\ndef simDrunk(numTrials, dClass, walkLenghts):\n meanDistances = []\n for numSteps in walkLenghts:\n print('Starting simulation of', numSteps, 'steps')\n trials = simWalks(numSteps, numTrials, dClass)\n mean = sum(trials)/len(trials)\n meanDistances.append(mean)\n return meanDistances\n\n\ndef simAll1(drunkKinds, walkLenghts, numTrials):\n styleChoice = styleIterator(('m-', 'r:', 'k-.')) # different type of line for the graph\n for dClass in drunkKinds:\n curStyle = styleChoice.nextStyle()\n print('Starting simulation of', dClass.__name__)\n means = simDrunk(numTrials, dClass, walkLenghts)\n pylab.plot(walkLenghts, means, curStyle,\n label = dClass.__name__)\n pylab.title('Mean Distance from Origin ('\n + str(numTrials) + 'trials)')\n pylab.xlabel('Number of Steps')\n pylab.ylabel('Distance from Origin')\n pylab.legend(loc = 'best')\n pylab.semilogx()\n pylab.semilogy()\n\n\nsimAll1((UsualDrunk, NSDrunk, EWDrunk), (10,100,1000,10000), 100)\n\n\ndef getFinalLocs(numSteps, numTrials, dClass):\n locs = []\n d = dClass()\n for t in range(numTrials):\n f = Field()\n f.addDrunk(d, Location(0, 0))\n for s in range(numSteps):\n f.moveDrunk(d)\n locs.append(f.getLoc(d))\n return locs\n\n\ndef plotLocs(drunkKinds, numSteps, numTrials):\n styleChoice = styleIterator(('k+', 'r^', 'mo'))\n for dClass in drunkKinds:\n locs = getFinalLocs(numSteps, numTrials, dClass)\n xVals, yVals = [], []\n for loc in locs:\n xVals.append(loc.getX())\n yVals.append(loc.getY())\n meanX = sum(xVals)/len(xVals)\n meanY = sum(yVals)/len(yVals)\n curStyle = styleChoice.nextStyle()\n pylab.plot(xVals, yVals, curStyle,\n label = dClass.__name__ + 'mean loc. = <'\n + str(meanX) + ', ' + str(meanY) + '>')\n pylab.title('Location at End of Walks ('\n + str(numSteps) + 'steps)')\n pylab.xlabel('Steps East/West of Origin')\n pylab.ylabel('Steps North/South of Origin')\n pylab.legend(loc = 'lower left')\n\n\nplotLocs((UsualDrunk, NSDrunk, EWDrunk), 100, 200)\n","repo_name":"Eliegautie/Mathematical-Finance-with-Python","sub_path":"Random walk simulation.ipynb","file_name":"Random walk simulation.ipynb","file_ext":"py","file_size_in_byte":5664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"33"} +{"seq_id":"20284432590","text":"# Import Necessary Libraries : \n# ---\n\nimport numpy as np\nfrom numpy import array\nimport pandas as pd\nimport matplotlib.pyplot as plt\n# %matplotlib inline\nimport string\nimport os\nfrom PIL import Image\nimport glob\nfrom pickle import dump, load\nfrom time import time\nfrom keras.preprocessing import sequence\nfrom keras.models import Sequential\nfrom keras.layers import LSTM, Embedding, TimeDistributed, Dense, RepeatVector,\\\n Activation, Flatten, Reshape, concatenate, Dropout, BatchNormalization\nfrom keras.optimizers import Adam, RMSprop\nfrom keras.layers.wrappers import Bidirectional\nfrom keras.layers.merge import add\nfrom keras.applications.inception_v3 import InceptionV3\nfrom keras.preprocessing import image\nfrom keras.models import Model\nfrom keras import Input, layers\nfrom keras import optimizers\nfrom keras.applications.inception_v3 import preprocess_input\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.utils import to_categorical\n\n\n# Load The descriptions file into memory :\n# ---\n\n# +\ndef load_doc(filename):\n file = open(filename, 'r')\n text = file.read()\n file.close()\n return text\n\nfilename = \"data/Flickr8k.token.txt\"\ndoc = load_doc(filename)\nprint(doc[:300])\n\n\n# -\n\n# Parse Descriptions :\n# ---\n# Preprocess the Descriptions by parsing the file and returning the mapped dictionary with keys as image name and a list of descriptions as the Value.\n\n# +\ndef load_descriptions(doc):\n mapping = dict() \n for line in doc.split('\\n'):\n tokens = line.split()\n if len(line) < 2:\n continue\n image_id, image_desc = tokens[0], tokens[1:]\n image_id = image_id.split('.')[0]\n image_desc = ' '.join(image_desc)\n if image_id not in mapping:\n mapping[image_id] = list()\n mapping[image_id].append(image_desc)\n return mapping\n\n# parse descriptions\ndescriptions = load_descriptions(doc)\nprint('Loaded: %d ' % len(descriptions))\n# -\n\ndescriptions['3323514651_3efdbd63ed']\n\n\n# Prep Descriptions :\n# ---\n# prepare translation table for removing punctuation, numbers etc. \n\n# +\ndef clean_descriptions(descriptions):\n #construct a mapping table to map string.punctuations to null character\n table = str.maketrans('', '', string.punctuation)\n for key, desc_list in descriptions.items():\n for i in range(len(desc_list)):\n desc = desc_list[i]\n desc = desc.split()\n desc = [word.lower() for word in desc]\n desc = [w.translate(table) for w in desc]\n desc = [word for word in desc if len(word)>1]\n desc = [word for word in desc if word.isalpha()]\n desc_list[i] = ' '.join(desc)\n\n# clean descriptions\nclean_descriptions(descriptions)\n# -\n\ndescriptions['3323514651_3efdbd63ed']\n\n\n# Make Vocab :\n# ---\n# Take unique words occuring in the 8k examples and make a vocab from them. \n# Set only accepts words once. \n\n# +\ndef to_vocabulary(descriptions):\n all_desc = set()\n for key in descriptions.keys():\n [all_desc.update(d.split()) for d in descriptions[key]]\n return all_desc\n\n# summarize vocabulary\nvocabulary = to_vocabulary(descriptions)\nprint('Original Vocabulary Size: %d' % len(vocabulary))\n\n\n# -\n\n# Save the Descriptions Vocab on Disk :\n#\n\n# +\ndef save_descriptions(descriptions, filename):\n lines = list()\n for key, desc_list in descriptions.items():\n for desc in desc_list:\n lines.append(key + ' ' + desc)\n data = '\\n'.join(lines)\n file = open(filename, 'w')\n file.write(data)\n file.close()\n\nsave_descriptions(descriptions, 'desc.txt')\n\n\n# -\n\n# ### Load the Trainset Identifiers :\n#\n\n# +\ndef load_set(filename):\n doc = load_doc(filename)\n dataset = list()\n for line in doc.split('\\n'):\n # skip empty lines\n if len(line) < 1:\n continue\n # get the image identifier\n identifier = line.split('.')[0]\n dataset.append(identifier)\n return set(dataset)\n\n# load training dataset (6K)\nfilename = 'data/Flickr_8k.trainImages.txt'\ntrain = load_set(filename)\nprint('Dataset: %d' % len(train))\n# -\n\n# ### Create List of All Image Names in Dataset : \n\nimages = 'data/Flicker8k_Dataset/' #path to all images\nimg = glob.glob(images + '*.jpg')\n\nimg[0:5]\n\n# ### Create a list of all the training images with their full path names :\n\n# +\n# Below file contains the names of images to be used in train data\ntrain_images_file = 'data/Flickr_8k.trainImages.txt'\n# Read the train image names in a set\ntrain_images = set(open(train_images_file, 'r').read().strip().split('\\n'))\n\n# Create a list of all the training images with their full path names\ntrain_img = []\n\nfor i in img: # img is list of full path names of all images\n if i[len(images):] in train_images: # Check if the image belongs to training set\n train_img.append(i) # Add it to the list of train images\n# -\n\ntrain_img[0:5]\n\n# +\n### Create a list of all the test images with their full path names :\n\n# +\n# Below file contains the names of images to be used in test data\ntest_images_file = 'data/Flickr_8k.testImages.txt'\n# Read the validation image names in a set# Read the test image names in a set\ntest_images = set(open(test_images_file, 'r').read().strip().split('\\n'))\n\n# Create a list of all the test images with their full path names\ntest_img = []\n\nfor i in img: # img is list of full path names of all images\n if i[len(images):] in test_images: # Check if the image belongs to test set\n test_img.append(i) # Add it to the list of test images\n# -\n\ntest_img[0:5]\n\n\n# ### Load descriptions for train set :\n\n# +\n# load clean descriptions into memory\ndef load_clean_descriptions(filename, dataset):\n # load document\n doc = load_doc(filename)\n descriptions = dict()\n for line in doc.split('\\n'):\n # split line by white space\n tokens = line.split()\n # split id from description\n image_id, image_desc = tokens[0], tokens[1:]\n # skip images not in the set\n if image_id in dataset:\n # create list\n if image_id not in descriptions:\n descriptions[image_id] = list()\n # wrap description in tokens\n desc = 'startseq ' + ' '.join(image_desc) + ' endseq'\n # store\n descriptions[image_id].append(desc)\n return descriptions\n\n# descriptions\ntrain_descriptions = load_clean_descriptions('desc.txt', train)\nprint('Descriptions: train=%d' % len(train_descriptions))\n# -\n\nlist(train_descriptions.keys())[:5]\n\ntrain_descriptions['2196050115_e236d91f52']\n\n\n# ### Define Function to Preprocess the Images\n#\n# Requirements for Inception V3 :\n# 1. main size = 299x299\n# 2. numpy array\n# 3. extra dimension added\n# 4. preprocess_input() from Inception Applied\n\ndef preprocess(image_path):\n # Convert all the images to size 299x299 as expected by the inception v3 model\n img = image.load_img(image_path, target_size=(299, 299))\n # Convert PIL image to numpy array of 3-dimensions\n x = image.img_to_array(img)\n # Add one more dimension\n x = np.expand_dims(x, axis=0)\n # preprocess the images using preprocess_input() from inception module\n x = preprocess_input(x)\n return x\n\n\n# ### Load Inception V3 and Create Model Instance\n#\n\n# Load the inception v3 model\nmodel = InceptionV3(weights='imagenet')\n\n# Create a new model, by removing the last layer (output layer) from the inception v3\nmodel_new = Model(model.input, model.layers[-2].output)\n\n\n# ### Function to Encode an Image into a Vector (2048,)\n\ndef encode(image):\n image = preprocess(image) # preprocess the image\n fea_vec = model_new.predict(image) # Get the encoding vector for the image\n fea_vec = np.reshape(fea_vec, fea_vec.shape[1]) # reshape from (1, 2048) to (2048, )\n return fea_vec\n\n\n# Now Encode and Henceforth Save : \n\nstart = time()\nencoding_train = {} # maps image name to image data\nfor img in train_img:\n encoding_train[img[len(images):]] = encode(img)\nprint(\"Time taken in seconds =\", time()-start)\n\nencoding_train['2196050115_e236d91f52.jpg'].shape\n\nimport pickle\n# Save the bottleneck train features to disk\nwith open(\"data/encoded_train_images.pkl\", \"wb\") as encoded_pickle:\n pickle.dump(encoding_train, encoded_pickle) # save the data in encoding_train into encoding_pickle.\n\n# Do the same for Test Images :\n\n# Call the funtion to encode all the test images - Execute this only once\nstart = time()\nencoding_test = {}\nfor img in test_img:\n encoding_test[img[len(images):]] = encode(img)\nprint(\"Time taken in seconds =\", time()-start)\n\n# Save the bottleneck test features to disk\nwith open(\"data/encoded_test_images.pkl\", \"wb\") as encoded_pickle:\n pickle.dump(encoding_test, encoded_pickle)\n\n# ### Load the data we just saved : \n\ntrain_features = load(open(\"data/encoded_train_images.pkl\", \"rb\"))\nprint('Photos: train=%d' % len(train_features))\n\n# ### Create a list of all the training captions :\n\nall_train_captions = []\nfor key, val in train_descriptions.items():\n for cap in val:\n all_train_captions.append(cap)\nlen(all_train_captions)\n\nall_train_captions[:4]\n\n# Consider only words which occur at least 10 times in the corpus and add to vocabulary:\n\n# +\nword_count_threshold = 10\nword_counts = {}\nnsents = 0\nfor sent in all_train_captions:\n nsents += 1\n for w in sent.split(' '):\n word_counts[w] = word_counts.get(w, 0) + 1 #counting number of times word w has occurred \n\nvocab = [w for w in word_counts if word_counts[w] >= word_count_threshold]\nprint('preprocessed words %d -> %d' % (len(word_counts), len(vocab)))\n# -\n\nvocab[0:5]\n\nlist(word_counts.items())[:4]\n\n# ## Form mapping from index to word and word to index :\n\n# +\nixtoword = {}\nwordtoix = {}\n\nix = 1\nfor w in vocab:\n wordtoix[w] = ix\n ixtoword[ix] = w\n ix += 1\n# -\n\nvocab_size = len(ixtoword) + 1 # one for appended 0's\nvocab_size\n\n\n# ### Convert a dictionary of clean descriptions to a list of descriptions :\n#\n# This will come in handy later when we preprocess data for the embedding-LSTM(Decoder) part.\n\n# +\ndef to_lines(descriptions):\n all_desc = list()\n for key in descriptions.keys():\n [all_desc.append(d) for d in descriptions[key]]\n return all_desc\n\n# calculate the length of the description with the most words\ndef max_length(descriptions):\n lines = to_lines(descriptions)\n return max(len(d.split()) for d in lines)\n\n# determine the maximum sequence length\nmax_length = max_length(train_descriptions)\nprint('Description Length: %d' % max_length)\n\n\n# -\n\n# ### Define Generator for use in training : \n# - Takes as input the descriptions dict, photos data(2048), word2index data, etc. \n# - Yields as output a list of 3 lists, with the photo, input sequence and output sequence\n# - number of photos depends on num_photos_per_batch\n\ndef data_generator(descriptions, photos, wordtoix, max_length, num_photos_per_batch):\n X1, X2, y = list(), list(), list()\n n=0\n # loop for ever over images\n while 1:\n for key, desc_list in descriptions.items():\n n+=1\n # retrieve the photo feature\n photo = photos[key+'.jpg']\n for desc in desc_list:\n # encode the sequence\n seq = [wordtoix[word] for word in desc.split(' ') if word in wordtoix]\n # split one sequence into multiple X, y pairs\n for i in range(1, len(seq)):\n # split into input and output pair\n in_seq, out_seq = seq[:i], seq[i]\n # pad input sequence\n in_seq = pad_sequences([in_seq], maxlen=max_length)[0]\n # encode output sequence\n out_seq = to_categorical([out_seq], num_classes=vocab_size)[0]\n # store\n X1.append(photo)\n X2.append(in_seq)\n y.append(out_seq)\n # yield the batch data\n if n==num_photos_per_batch:\n yield [[array(X1), array(X2)], array(y)]\n X1, X2, y = list(), list(), list()\n n=0\n\n\n# ### Load GloVe Vectors : \n# - load glove and read\n# - find number of word vectors\n\n# +\n# Load Glove vectors\nglove_dir = 'data/'\nembeddings_index = {} # empty dictionary\nf = open(os.path.join(glove_dir, 'glove.6B.200d.txt'), encoding=\"utf-8\")\n\nfor line in f:\n values = line.split()\n word = values[0]\n coefs = np.asarray(values[1:], dtype='float32')\n embeddings_index[word] = coefs\nf.close()\nprint('Found %s word vectors.' % len(embeddings_index))\n# -\n\n# ### Embed the descriptions using the vectors in glove :\n\n# +\nembedding_dim = 200\n\n# Get 200-dim dense vector for each of the 10000 words in out vocabulary\nembedding_matrix = np.zeros((vocab_size, embedding_dim))\n\nfor word, i in wordtoix.items():\n #if i < max_words:\n embedding_vector = embeddings_index.get(word)\n if embedding_vector is not None:\n # Words not found in the embedding index will be all zeros\n embedding_matrix[i] = embedding_vector\nembedding_matrix.shape\n# -\n\n# ### Define Model :\n\ninputs1 = Input(shape=(2048,))\nfe1 = Dropout(0.5)(inputs1)\nfe2 = Dense(256, activation='relu')(fe1)\ninputs2 = Input(shape=(max_length,))\nse1 = Embedding(vocab_size, embedding_dim, mask_zero=True)(inputs2)\nse2 = Dropout(0.5)(se1)\nse3 = LSTM(256)(se2)\ndecoder1 = add([fe2, se3])\ndecoder2 = Dense(256, activation='relu')(decoder1)\noutputs = Dense(vocab_size, activation='softmax')(decoder2)\nmodel = Model(inputs=[inputs1, inputs2], outputs=outputs)\n\nmodel.summary()\n\nmodel.layers[2]\n\nmodel.layers[2].set_weights([embedding_matrix])\nmodel.layers[2].trainable = False\n\nmodel.compile(loss='categorical_crossentropy', optimizer='adam')\n\nepochs = 10\nnumber_pics_per_bath = 3\nsteps = len(train_descriptions)//number_pics_per_bath\n\nfor i in range(epochs):\n generator = data_generator(train_descriptions, train_features, wordtoix, max_length, number_pics_per_bath)\n model.fit_generator(generator, epochs=1, steps_per_epoch=steps, verbose=1)\n model.save('./model_weights/model_' + str(i) + '.h5')\n\nfor i in range(epochs):\n generator = data_generator(train_descriptions, train_features, wordtoix, max_length, number_pics_per_bath)\n model.fit_generator(generator, epochs=1, steps_per_epoch=steps, verbose=1)\n model.save('./model_weights/model_' + str(i) + '.h5')\n\nmodel.optimizer.lr = 0.0001\nepochs = 10\nnumber_pics_per_bath = 6\nsteps = len(train_descriptions)//number_pics_per_bath\n\n# +\n\nfor i in range(epochs):\n generator = data_generator(train_descriptions, train_features, wordtoix, max_length, number_pics_per_bath)\n model.fit_generator(generator, epochs=1, steps_per_epoch=steps, verbose=1)\n #model.save('./model_weights/model_' + str(i) + '.h5')\n# -\n\nmodel.save_weights('./model_weights/model_30.h5')\n\nopen('model.json', 'w').write(model.to_json())\nmodel.save_weights('weights.h5')\n\nmodel.load_weights('./model_weights/model_30.h5')\n\nimages = 'data/Flicker8k_Dataset/'\nwith open(\"data/encoded_test_images.pkl\", \"rb\") as encoded_pickle:\n encoding_test = load(encoded_pickle)\n\n\ndef greedySearch(photo):\n in_text = 'startseq'\n for i in range(max_length):\n sequence = [wordtoix[w] for w in in_text.split() if w in wordtoix]\n sequence = pad_sequences([sequence], maxlen=max_length)\n yhat = model.predict([photo,sequence], verbose=0)\n yhat = np.argmax(yhat)\n word = ixtoword[yhat]\n in_text += ' ' + word\n if word == 'endseq':\n break\n final = in_text.split()\n final = final[1:-1]\n final = ' '.join(final)\n return final\n\n\nz=0\n\n# +\n\nz +=1\npic = list(encoding_test.keys())[z]\nimage = encoding_test[pic].reshape((1,2048))\nx=plt.imread(images+pic)\nplt.imshow(x)\nplt.show()\nprint(\"Greedy:\",greedySearch(image))\n\n# +\nfrom keras.models import model_from_json\n\nmodel2 = model_from_json(open('model.json').read())\nmodel2.load_weights('weights.h5')\n\n\n# +\ndef greedySearch2(photo):\n in_text = 'startseq'\n for i in range(max_length):\n sequence = [wordtoix[w] for w in in_text.split() if w in wordtoix]\n sequence = pad_sequences([sequence], maxlen=max_length)\n yhat = model2.predict([photo,sequence], verbose=0)\n yhat = np.argmax(yhat)\n word = ixtoword[yhat]\n in_text += ' ' + word\n if word == 'endseq':\n break\n final = in_text.split()\n final = final[1:-1]\n final = ' '.join(final)\n return final\n\n\nz +=1\npic = list(encoding_test.keys())[z]\nimage = encoding_test[pic].reshape((1,2048))\nx=plt.imread(images+pic)\nplt.imshow(x)\nplt.show()\nprint(\"Greedy:\",greedySearch2(image))\n# -\n\n\n","repo_name":"AbhilashPal/ImageToPoetry","sub_path":"ImageCaptioning.ipynb","file_name":"ImageCaptioning.ipynb","file_ext":"py","file_size_in_byte":16652,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"33"} +{"seq_id":"23351484793","text":"from DistantSpeech.beamformer.utils import load_audio\nfrom scipy.signal import convolve as conv\nfrom matplotlib import pyplot as plt\nfrom tqdm import tqdm\nimport numpy as np\nfrom DistantSpeech.adaptivefilter.BaseFilter import BaseFilter, awgn\nfrom DistantSpeech.adaptivefilter.FastFreqLms import FastFreqLms\nfrom DistantSpeech.beamformer.utils import load_audio as audioread\nfrom DistantSpeech.beamformer.utils import save_audio as audiowrite\n\n# +\n# load source single and rir\nsrc = load_audio('/home/wangwei/work/DistantSpeech/samples/audio_samples/cleanspeech_aishell3.wav')\nsrc = np.random.rand(len(src))-0.5# * np.sqrt(npower)\nprint(src.shape)\nrir = load_audio('/home/wangwei/work/DistantSpeech/DistantSpeech/adaptivefilter/rir.wav')\nrir = rir[200:]\n\nfilter_len = 256\n\nrir = rir[:filter_len, np.newaxis]\nplt.figure()\nplt.plot(rir)\nplt.title('impulse response')\nplt.show()\n\n# +\n\n\ndata_clean = conv(src, rir[:, 0])\ndata = data_clean[:len(src)]\n\nprint(src.shape)\nprint(data.shape)\n\nw = np.zeros((filter_len, 1))\n\nflms = FastFreqLms(filter_len=filter_len)\nflms.w[:] = rir\n\nvalid_len = len(src)-flms.filter_len # discard last frame\n\n\nest_err_flms = np.zeros(valid_len)\n\noutput = np.zeros(data.shape)\n\nfor n in tqdm(range((valid_len))):\n if np.mod(n, flms.filter_len) == 0:\n input_vector = src[n: n + flms.filter_len]\n d_vector = data[n : n + flms.filter_len]\n err, w_flms = flms.update(input_vector, d_vector, update=False)\n\n output[n : n + flms.filter_len] = err[:, 0]\n\nplt.figure(figsize=(14,8))\nplt.plot(data - output)\nplt.show()\n","repo_name":"wangwei2009/DistantSpeech","sub_path":"example/Overlap_save.ipynb","file_name":"Overlap_save.ipynb","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-jupyter-script","pt":"38"} +{"seq_id":"1578780725","text":"# +\nimport numpy as np\nimport os\nfrom tqdm import tqdm_notebook\nimport pandas as pd\nfrom skimage.transform import rescale, resize\n\n\nfrom fastai.imports import *\nfrom fastai.transforms import *\nfrom fastai.conv_learner import *\nfrom fastai.model import *\nfrom fastai.dataset import *\nfrom fastai.sgdr import *\nfrom fastai.plots import *\nfrom fastai.conv_learner import *\nfrom fastai.dataset import *\nimport tensorflow as tf\n\n\n# -\n\n# # My first fastai run on image segmentation task\n\n# In this notebook I run my first fastai model. I participate in a competition https://www.kaggle.com/c/tgs-salt-identification-challenge\n#\n# The idea here is to identofy the segment of an image with the salt. Also, for every image the depth of the signals is provided.
\n# In the current solution I don't use the depth, but it is a definetely an important feature. To be done in future. \n#\n# Useful notebooks: \n# \n# https://www.kaggle.com/phoenigs/u-net-dropout-augmentation-stratification\n#\n# https://www.kaggle.com/bguberfain/unet-with-depth\n#\n# I'm using the U-net architecture, where the encoder part is done with the pretrained model ResNet34. \n\ndef show_img(im, figsize=None, ax=None, alpha=None):\n if not ax: fig,ax = plt.subplots(figsize=figsize)\n ax.imshow(im, alpha=alpha)\n ax.set_axis_off()\n return ax\n\n\nsz = 128\nbs = 64 #batch size\nnw = 16\n\n# +\nPATH = Path('data/')\nTRAIN_PATH = PATH/'images'\n\nMASKS_FN = Path('train.csv')\n\nTRAIN_DN = 'train_images'\nMASKS_DN = 'train_masks'\nTEST_PATH = 'test_images'\n# -\n\nmasks_csv = pd.read_csv(PATH/MASKS_FN)\n\nmasks_csv.head()\n\n\nclass MatchedFilesDataset(FilesDataset):\n def __init__(self, fnames, y, transform, path):\n self.y=y\n assert(len(fnames)==len(y))\n super().__init__(fnames, transform, path)\n def get_y(self, i): return open_image(os.path.join(self.path, self.y[i]))\n def get_c(self): return 0\n\n\nx_names = np.array([str(Path(TRAIN_DN)/o) + '.png' for o in masks_csv['id']])\ny_names = np.array([str(Path(MASKS_DN)/o) + '.png' for o in masks_csv['id']])\n\ntest_path_full = f'{TRAIN_PATH}/{TEST_PATH}'\n\nx_test_names = np.array([f'{str(TEST_PATH)}/{o}' for o in os.listdir(test_path_full)])\n\nval_idxs = list(range(1008))\n((val_x,trn_x),(val_y,trn_y)) = split_by_idx(val_idxs, x_names, y_names)\n\naug_tfms = [RandomRotate(4, tfm_y=TfmType.CLASS),\n RandomFlip(tfm_y=TfmType.CLASS),\n RandomLighting(0.05, 0.05, tfm_y=TfmType.CLASS)]\n\ntrn_x\n\n# +\ntfms = tfms_from_model(resnet34, sz, crop_type=CropType.NO, tfm_y=TfmType.CLASS, aug_tfms=aug_tfms)\n\ndatasets = ImageData.get_ds(MatchedFilesDataset, (trn_x,trn_y), (val_x,val_y), tfms, test=(x_test_names, x_test_names), path=TRAIN_PATH)\nmd = ImageData(PATH, datasets, bs, num_workers=4, classes=None)\ndenorm = md.trn_ds.denorm\n# -\n\nx,y = next(iter(md.trn_dl))\n\n# +\n# example of one batch \n\nx.shape, y.shape\n# -\n\nshow_img(x[1, 0])\n\nf = resnet34\ncut, lr_cut = model_meta[f]\n\n\ndef mean_iou(targs, pred):\n prec = []\n for t in np.arange(0.5, 1.0, 0.05):\n y_pred_ = (pred>t).float()\n score, up_opt = tf.metrics.mean_iou(y_true, y_pred_, 2)\n prec.append(score)\n return K.mean(K.stack(prec), axis=0)\n\n\n# +\ndef get_base():\n layers = cut_model(f(True), cut)\n return nn.Sequential(*layers)\n\ndef dice(pred, targs):\n pred = (pred>0).float()\n return 2. * (pred*targs).sum() / (pred+targs).sum()\n\nclass StdUpsample(nn.Module):\n def __init__(self, nin, nout):\n super().__init__()\n self.conv = nn.ConvTranspose2d(nin, nout, 2, stride=2)\n self.bn = nn.BatchNorm2d(nout)\n \n def forward(self, x): return self.bn(F.relu(self.conv(x)))\n\n\n# -\n\nclass Upsample34(nn.Module):\n def __init__(self, rn):\n super().__init__()\n self.rn = rn\n self.features = nn.Sequential(\n rn, nn.ReLU(),\n StdUpsample(512,256),\n StdUpsample(256,256),\n StdUpsample(256,256),\n StdUpsample(256,256),\n nn.ConvTranspose2d(256, 1, 2, stride=2))\n \n def forward(self,x): return self.features(x)[:,0]\n\n\nclass UpsampleModel():\n def __init__(self,model,name='upsample'):\n self.model,self.name = model,name\n\n def get_layer_groups(self, precompute):\n lgs = list(split_by_idxs(children(self.model.rn), [lr_cut]))\n return lgs + [children(self.model.features)[1:]]\n\n\nm_base = get_base()\n\n\nm = to_gpu(Upsample34(m_base))\nmodels = UpsampleModel(m)\n\nlearn = ConvLearner(md, models)\nlearn.opt_fn = optim.Adam\nlearn.crit = nn.BCEWithLogitsLoss()\nlearn.metrics = [accuracy_thresh(0.5),dice]\n\nlearn.freeze_to(1)\n\nlearn.lr_find()\nlearn.sched.plot()\n\nlr=4e-2\nwd=1e-7\nlrs = np.array([lr/100,lr/10,lr])/2\n\nlearn.fit(lr,1, wds=wd, cycle_len=4,use_clr=(20,8))\n\nlearn.save('tmp')\n\nlearn.load('tmp')\n\n\nlearn.unfreeze()\nlearn.bn_freeze(True)\n\nlearn.fit(lrs, 1, cycle_len=2,use_clr=(20,8))\n\nlearn.save('128')\n\nx,y = next(iter(md.val_dl))\npy = to_np(learn.model(V(x)))\n\nshow_img(py[20]>0);\n\nshow_img(y[20]);\n\n# +\n# Additional to the original test/validation images, apply image augmentation to them\n# (just like for training images) and calculate the mean of predictions. The intent\n# is to increase the accuracy of predictions by examining the images using multiple\n# perspectives.\n\npreds, y = learn.TTA(is_test=True)\n# -\n\npreds_test = preds[0,:,:,:]\n\npreds_val = learn.predict(is_test=False)\n\npreds_val.shape\n\nshow_img(preds[4,2,:,:] > 1)\n\n\n# +\n# src: https://www.kaggle.com/aglotero/another-iou-metric\ndef iou_metric(y_true_in, y_pred_in, print_table=False):\n labels = y_true_in\n y_pred = y_pred_in\n \n true_objects = 2\n pred_objects = 2\n\n intersection = np.histogram2d(labels.flatten(), y_pred.flatten(), bins=(true_objects, pred_objects))[0]\n\n # Compute areas (needed for finding the union between all objects)\n area_true = np.histogram(labels, bins = true_objects)[0]\n area_pred = np.histogram(y_pred, bins = pred_objects)[0]\n area_true = np.expand_dims(area_true, -1)\n area_pred = np.expand_dims(area_pred, 0)\n\n # Compute union\n union = area_true + area_pred - intersection\n\n # Exclude background from the analysis\n intersection = intersection[1:,1:]\n union = union[1:,1:]\n union[union == 0] = 1e-9\n\n # Compute the intersection over union\n iou = intersection / union\n\n # Precision helper function\n def precision_at(threshold, iou):\n matches = iou > threshold\n true_positives = np.sum(matches, axis=1) == 1 # Correct objects\n false_positives = np.sum(matches, axis=0) == 0 # Missed objects\n false_negatives = np.sum(matches, axis=1) == 0 # Extra objects\n tp, fp, fn = np.sum(true_positives), np.sum(false_positives), np.sum(false_negatives)\n return tp, fp, fn\n\n # Loop over IoU thresholds\n prec = []\n if print_table:\n print(\"Thresh\\tTP\\tFP\\tFN\\tPrec.\")\n for t in np.arange(0.5, 1.0, 0.05):\n tp, fp, fn = precision_at(t, iou)\n if (tp + fp + fn) > 0:\n p = tp / (tp + fp + fn)\n else:\n p = 0\n if print_table:\n print(\"{:1.3f}\\t{}\\t{}\\t{}\\t{:1.3f}\".format(t, tp, fp, fn, p))\n prec.append(p)\n \n if print_table:\n print(\"AP\\t-\\t-\\t-\\t{:1.3f}\".format(np.mean(prec)))\n return np.mean(prec)\n\ndef iou_metric_batch(y_true_in, y_pred_in):\n batch_size = y_true_in.shape[0]\n metric = []\n for batch in range(batch_size):\n value = iou_metric(y_true_in[batch], y_pred_in[batch])\n metric.append(value)\n return np.mean(metric)\n# -\n\n\n\ndef process_arr(x_img):\n return resize(x_img, (128, 128, 1), mode='constant', preserve_range=True)\n\n\nval_true = np.array([process_arr(learn.data.val_ds.get_y(i)) for i in range(learn.data.val_dl.dataset.get_n())])\n\nval_true = val_true[:,:,:,0]\n\nval_true.shape\n\npreds_val.shape\n\nthresholds = np.linspace(0, 1, 50)\nious = np.array([iou_metric_batch(val_true, np.int32(preds_val > threshold)) for threshold in tqdm_notebook(thresholds)])\n\nthreshold_best_index = np.argmax(ious[9:-10]) + 9\niou_best = ious[threshold_best_index]\nthreshold_best = thresholds[threshold_best_index]\n\nplt.plot(thresholds, ious)\nplt.plot(threshold_best, iou_best, \"xr\", label=\"Best threshold\")\nplt.xlabel(\"Threshold\")\nplt.ylabel(\"IoU\")\nplt.title(\"Threshold vs IoU ({}, {})\".format(threshold_best, iou_best))\nplt.legend()\n\niou_best\n\n\n# Source https://www.kaggle.com/bguberfain/unet-with-depth\ndef RLenc(img, order='F', format=True):\n \"\"\"\n img is binary mask image, shape (r,c)\n order is down-then-right, i.e. Fortran\n format determines if the order needs to be preformatted (according to submission rules) or not\n\n returns run length as an array or string (if format is True)\n \"\"\"\n bytes = img.reshape(img.shape[0] * img.shape[1], order=order)\n runs = [] ## list of run lengths\n r = 0 ## the current run length\n pos = 1 ## count starts from 1 per WK\n for c in bytes:\n if (c == 0):\n if r != 0:\n runs.append((pos, r))\n pos += r\n r = 0\n pos += 1\n else:\n r += 1\n\n # if last run is unsaved (i.e. data ends with 1)\n if r != 0:\n runs.append((pos, r))\n pos += r\n r = 0\n\n if format:\n z = ''\n\n for rr in runs:\n z += '{} {} '.format(rr[0], rr[1])\n return z[:-1]\n else:\n return runs\n\n\npreds_test.shape\n\nlen(preds_test)\n\npreds_test[0,:,:]\n\n\ndef downsample(img):\n return resize(img, (101, 101), mode='constant', preserve_range=True)\n\n\nfnames = [fname[5:-4] for fname in learn.data.test_ds.fnames]\n\npred_dict = {name: RLenc(np.round(downsample(preds_test[i, :, :]) > threshold_best)) for name, i in zip(fnames, range(len(preds_test)))}\n\npred_dict.get('dc066ad24e')\n\nsub = pd.DataFrame.from_dict(pred_dict,orient='index')\nsub.index.names = ['id']\nsub.columns = ['rle_mask']\nsub.to_csv('fastai_submission.csv')\n\n\n","repo_name":"galinaalperovich/kaggle-salt","sub_path":"salt.ipynb","file_name":"salt.ipynb","file_ext":"py","file_size_in_byte":9898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"38"} +{"seq_id":"28741970259","text":"import pandas as pd\ndataset = pd.read_csv('dataset_halfSecondWindow.csv')\n\ndataset.columns\n\ndataset = dataset.iloc[:, 5:]\n\ndataset\n\ndataset.isnull().sum()/dataset.shape[0]\n\nfor name,col in zip(dataset.columns,dataset.isnull().sum()/dataset.shape[0]):\n if col>0.7:\n dataset.drop(name,axis=1, inplace=True)\n\ndataset.shape\n\nfor col in dataset.columns.to_list():\n for comp_col in dataset.columns.to_list():\n if col != comp_col and ((dataset[col]==dataset[comp_col]).sum()+dataset[col].isnull().sum())==dataset.shape[0]:\n dataset.drop(col,axis=1, inplace=True)\n break\n\ndataset.shape\n\ndataset.groupby('user').count()\n\ntrain, test = dataset[~dataset['user'].isin(['U5','U2','U11','U9'])],dataset[dataset['user'].isin(['U5','U2','U11','U9'])]\n\ntrain.shape\n\ntest.shape\n\ntrain['user'].unique()\n\ntest['user'].unique()\n\ntrain_out = train\n\ntrain_out.fillna(train_out.mean(), inplace=True)\n\ntest.fillna(train_out.mean(), inplace=True)\n\nx_train, y_train = train_out.drop(['user','target'], axis=1), train_out['target']\nx_test, y_test = test.drop(['user','target'], axis=1), test['target']\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\nx_train = scaler.fit_transform(x_train)\nx_test = scaler.transform(x_test)\n\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn import metrics\nclf = RandomForestClassifier(random_state=0)\nclf.fit(x_train, y_train)\ny_pred = clf.predict(x_test)\nacc = metrics.accuracy_score(y_test, y_pred) * 100\nprint(acc)\n\ny_pred_train = clf.predict(x_train)\nacc = metrics.accuracy_score(y_train, y_pred_train) * 100\nprint(acc)\n\n\n","repo_name":"SohanAlam/Personal_exercises","sub_path":"Build Week 2(Machine Learning)/Day3/BW2.ipynb","file_name":"BW2.ipynb","file_ext":"py","file_size_in_byte":1616,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"38"} +{"seq_id":"8766148682","text":"# Class Examples for Project 1\n\nimport pandas as pd\nimport altair as alt\n\n\n#url = \"https://github.com/byuidatascience/data4names/raw/master/data-raw/names_year/names_year.csv\"\nnames = pd.read_csv(\"names_year.csv\")\n\n# How many babies are named ‘Oliver’ in the state of Utah for all years?\n\nnames.query('name == \"Oliver\"').UT.sum()\n\n# What was the earliest year that the name ‘Felisha’ was used?\n\nnames.query(\"name == 'Felisha'\")\n\n# How many unique names does the names dataset contain?\n\nlen(names.name.unique())\n\n\n# What is the range of years in the names dataset?\n\nprint(min(names.year))\nprint(max(names.year))\n\n# Project 1, Day 3 Class Examples\n\n# +\nnames[(names['name'] == \"Gavin\") | (names['name'] == 'Kyle')]\n#or#\n#names.query('name == \"Gavin\"')\n\nnames[names['name'].isin(['Gavin', 'Kyle'])]\n\n# +\nlist_of_names = ['Gavin' , 'Nate' , 'Brigham']\n\ncompare_names = (names.query('name is in @list_of_names')\n .groupby('name')\n .mean()\n .filter(['AK', 'Total'])\n .sort_values('AK' , ascending = False))\n\ncompare_names \n","repo_name":"gavinforstrom/DATA-SCIENCE","sub_path":"project1/w01class.ipynb","file_name":"w01class.ipynb","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"38"} +{"seq_id":"8313115116","text":"# + id=\"tlcurckNJGSO\"\nimport pandas as pd\nimport numpy as np\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom sklearn.feature_extraction.text import CountVectorizer\n\n# + id=\"FmEvCMTwXDXB\"\ndf = pd.read_csv(\n \"/home/aca/Documents/S6_Lab/Projects/libraryDataAnalysis/pattern_mining/unq_bks.csv\", index_col=0)\n\n# -\n\n# Searching books in dataset to find exact matches. \ndef search_exact(data = None, auth=\"\", pub=\"\", title=\"\"):\n\n if (data is None): \n print(\"No dataframe selected\")\n return \n \n # New dataframe for storing the search result\n res = pd.DataFrame()\n\n # Finding non empty arguments\n fields = []\n if (title != \"\"):\n fields.append({\"title\": title})\n if (pub != \"\"):\n fields.append({\"publisher\": pub})\n if (auth != \"\"):\n fields.append({\"author\": auth})\n\n # Number of non empty arguments\n _sz = len(fields)\n\n if _sz == 0:\n print(\"You need to specify atleast one field\")\n return\n\n # Iterate through non empty arguments. Combine them using AND logic. \n _key = list(fields[0].keys())[0] \n \n res = data.loc[data[_key] == fields[0][_key]]\n\n if _sz > 1:\n for i in fields[1:]:\n _key = list(i.keys())[0]\n res = res.loc[res[_key] == i[_key]]\n\n return res \n\n\n\n# +\n# Verification of search_exact. Status: Finished \nres_exact = search_exact(\n data=df, \n title=\"OPERATING SYSTEM CONCEPTS\", \n auth=\"SILBERCHATZ & GALVIN\", \n pub=\"WILEY INDIA\"\n )\n\nif(res_exact.shape[0] == 0):\n print(\"No exact matches found. Check your spelling\")\nelse:\n print(res_exact)\n\n\n# +\n# function to combine features\ndef combine_features(data=None, valid_args=None):\n\n if (data is None or valid_args is None):\n print(\"No dataframe selected/No arguments passed to combine\")\n return\n \n \n _keys = list(valid_args.keys())\n\n # If you're passing scalar values, you have to pass an index\n # https://stackoverflow.com/a/17840195/12616968\n _row = pd.DataFrame(valid_args, index=[0])\n\n data = pd.concat([data, _row], axis=0, ignore_index=True)\n\n features = []\n\n sz = data.shape[0]\n\n try:\n for i in range(sz):\n fea = \"\"\n for j in _keys:\n fea += data[j][i] + \" \"\n features.append(fea)\n except:\n print(i)\n finally:\n data[\"combined\"] = features\n return data\n\n \n\n\n# Search similar books based on cosine similarity.\ndef search_similar(data=None, auth=\"\", pub=\"\", title=\"\"):\n\n if (data is None):\n print(\"No data frame selected\")\n return\n\n valid_args = {}\n\n\n if (title != \"\"):\n valid_args[\"title\"] = title\n if (pub != \"\"):\n valid_args[\"publisher\"] = pub\n if (auth != \"\"):\n valid_args[\"author\"] = auth\n\n _temp = combine_features(data=df[list(valid_args.keys())], valid_args=valid_args)\n\n cm = CountVectorizer().fit_transform(_temp[\"combined\"])\n\n # get cosine similarity mtx\n cs = cosine_similarity(cm)\n # print\n # print(type(cs))\n\n index = cs.shape[0]-1 # index of the added row\n\n a = list(enumerate((cs[index])))\n \n # Sort scores in descending order. More score means higher similarity\n sorted_scores = sorted(a, key=lambda x: x[1], reverse=True)\n\n return sorted_scores[1:]\n \n \n\n\n# +\nres_similar = search_similar(\n data=df, \n title=\"10 MINUTE GUIDE TO MICROSOFT EXCEL 2000\",\n auth=\"FULTON,JENNIFER\",\n pub=\"PHI\"\n )\n\nres_similar\n\n# +\n# Printing similar results\nj = 0\ncount = 15\n\nfor i in res_similar:\n\n try:\n bk_title = df[df.index == i[0]]['title'].values[0]\n bk_author = df[df.index == i[0]]['author'].values[0]\n bk_pub = df[df.index == i[0]]['publisher'].values[0]\n except IndexError:\n # Index Error happens because we have added an additional row that wasn't \n # originally in dataframe. In that case we skip and continue with next index.\n continue\n\n print(f\"\"\"\n Number: {j+1}\n Title: {bk_title} \n Author: {bk_author} \n Publisher: {bk_pub} \n Score: {i[1]}\n --------------------------------\n \"\"\")\n j += 1\n if (j >= count):\n break\n\n# -\n\n\n","repo_name":"aca00/libraryDataAnalysis","sub_path":"model/similarityBasedOnUserQuery.ipynb","file_name":"similarityBasedOnUserQuery.ipynb","file_ext":"py","file_size_in_byte":4173,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"38"} +{"seq_id":"16282525258","text":"# # Analyzing and visualizing\n#\n# ## Molecular structure\n#\n# Molecular structures can be inspected with use of the `py3Dmol` module. We initialize a view and include a stick representation of the water molecule. The view is interactive, so you can rotate, translate, zoom in and out. An illustration of the van der Waals surface is added to give an idea of the \"molecular size\", or the electron cloud.\n\n# +\nimport py3Dmol as p3d\n\nh2o_xyz = \"\"\"3\n \nO 0.000000000000 0.000000000000 0.000000000000 \nH 0.740848095288 0.582094932012 0.000000000000 \nH -0.740848095288 0.582094932012 0.000000000000\n\"\"\"\n\nv = p3d.view(width=300, height=300)\nv.addModel(h2o_xyz, \"xyz\")\nv.setStyle({\"stick\": {}})\nv.addSurface(p3d.VDW, {\"opacity\": 0.7, \"color\": \"green\"})\nv.show()\n# -\n\n# (section-orbitals)=\n# ## Molecular orbitals\n#\n# The molecular orbitals (MOs) can be viewer using the `OrbitalViewer` function. First, run an SCF to obtain the MO coefficients\n\n# + tags=[\"remove-output\"]\nimport veloxchem as vlx\n\nmolecule = vlx.Molecule.from_xyz_string(h2o_xyz)\nbasis = vlx.MolecularBasis.read(molecule, \"cc-pVDZ\")\nscf_drv = vlx.ScfRestrictedDriver()\nscf_results = scf_drv.compute(molecule, basis)\n# -\n\n# Next, initiate a `viewer` object, provide information it with the molecular structure, basis set, and SCF, and plot:\n\nviewer = vlx.OrbitalViewer()\nviewer.plot(molecule, basis, scf_drv.mol_orbs)\n\n# This results in seven molecular orbitals (selected by drop-down menu at the lower left), as the use of a minimal basis set (STO-3G) yields one basis function per hydrogen (1s), and five basis functions for oxygen (1s, 2s, and three 2p). Note that you cannot plot different MOs on the book, but it will work in a notebook.\n#\n#\n# Additionally, the values of orbitals at given coordinates are readily available. Below is an example in terms of finding the values of the $1s$-orbital ($\\alpha$-spin) along the $z$-axis. \n\n# + tags=[\"remove-cell\"]\nimport py3Dmol as p3d\n\n\n\n\n# +\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nvis_drv = vlx.VisualizationDriver()\nmol_orbs = scf_drv.mol_orbs\n\nn = 100\ncoords = np.zeros((n, 3))\ncoords[:, 2] = np.linspace(0, 1.5, n)\n\nmo_1s = 0\nmo_1s_values = vis_drv.get_mo(coords, molecule, basis, mol_orbs, mo_1s, \"alpha\")\n\n# +\nfig = plt.figure(figsize=(8, 3))\n\nplt.plot(coords[:, 2], mo_1s_values, label = r\"oxygen $1s$-orbital\")\n\nplt.grid(True)\n\nplt.legend()\n\nplt.title(r\"H$_2$O molecule\")\nplt.xlabel(\"Distance from oxyxen nucleus (Bohr)\")\nplt.ylabel(\"Orbital values (a.u.)\")\n\nplt.show()\n# -\n\n# ## One-particle density\n#\n# The one-particle density for an $N$-electron system is defined as\n#\n# $$\n# n(\\mathbf{r}) = N \\int \n# \\Psi^\\dagger(\\mathbf{r}, \\mathbf{r}_2, \\ldots,\\mathbf{r}_N)\n# \\Psi(\\mathbf{r}, \\mathbf{r}_2, \\ldots,\\mathbf{r}_N)\n# \\, d^3\\mathbf{r}_2 \\cdots d^3\\mathbf{r}_N\n# $$\n#\n# and it refers to the probability density of finding any one electron at position $\\mathbf{r}$ in space regardless of the distribution of others. It fulfills\n#\n# $$\n# \\int n(\\mathbf{r}) \\, d^3\\mathbf{r} = N\n# $$\n#\n# For a Hartree–Fock state, one-particle densities are available as illustrated in the example script below.\n\n# +\nvis_drv = vlx.VisualizationDriver()\n\none_part_den = vis_drv.get_density(coords, molecule, basis, scf_drv.density, \"alpha\")\n\n# +\nfig = plt.figure(figsize=(8, 3))\nax = plt.axes(xlim=(0, 0.5), ylim=(0, 140))\n\nplt.plot(coords[:, 2], one_part_den)\n\nplt.grid(True)\n\nplt.title(r\"H$_2$O molecule\")\nplt.xlabel(\"Distance from oxyxen nucleus (Bohr)\")\nplt.ylabel(\"One-particle density (a.u.)\")\n\nplt.show()\n# -\n\n# As indicated by the string argument \"alpha\", the $\\alpha$- and $\\beta$-spin densities can be determined individually, referring to the relation\n#\n# $$\n# n(\\mathbf{r}) = n^\\alpha(\\mathbf{r}) + n^\\beta(\\mathbf{r})\n# $$\n#\n# For a closed shell system, the two spin densities are equal and thus equal to half the total one-particle density.\n\nhelp(vis_drv.get_density)\n\n# ## Two-particle density\n#\n# The two-particle density for an $N$-electron system is defined as\n#\n# $$\n# n(\\mathbf{r}_1, \\mathbf{r}_2) = N(N-1)\\int \n# \\Psi^\\dagger(\\mathbf{r}_1, \\mathbf{r}_2, \\ldots,\\mathbf{r}_N)\n# \\Psi(\\mathbf{r}_1, \\mathbf{r}_2, \\ldots,\\mathbf{r}_N)\n# \\, d^3\\mathbf{r}_3 \\cdots d^3\\mathbf{r}_N\n# $$\n#\n# and it refers to the probability density of finding one electron at position $\\mathbf{r}_1$ and another at position $\\mathbf{r}_2$ in space regardless of the distribution of others.\n#\n# For a Hartree–Fock state, two particle densities are available as illustrated in the example script below.\n\n# +\ncoord = [[0.0, 0.0, 0.0]]\n\ntwo_part_den_aa = vis_drv.get_two_particle_density(\n coord, coord, molecule, basis, scf_drv.density, \"alpha\", \"alpha\"\n)\ntwo_part_den_ab = vis_drv.get_two_particle_density(\n coord, coord, molecule, basis, scf_drv.density, \"alpha\", \"beta\"\n)\n\nprint(f\"Two-particle density (same spin): {two_part_den_aa[0]:10.4f} a.u.\")\nprint(f\"Two-particle density (opposite spin): {two_part_den_ab[0]:10.4f} a.u.\")\n# -\n\n# As indicated by the string arguments \"alpha\" and \"beta\", the spin densities can be determined individually, referring to the relation\n#\n# $$\n# n(\\mathbf{r}_1, \\mathbf{r}_2) = n^{\\alpha\\alpha}(\\mathbf{r}_1, \\mathbf{r}_2) + \n# n^{\\alpha\\beta}(\\mathbf{r}_1, \\mathbf{r}_2) + n^{\\beta\\alpha}(\\mathbf{r}_1, \\mathbf{r}_2) + \n# n^{\\beta\\beta}(\\mathbf{r}_1, \\mathbf{r}_2)\n# $$\n#\n# For a closed shell system, we have\n#\n# \\begin{align*}\n# n^{\\alpha\\alpha}(\\mathbf{r}_1, \\mathbf{r}_2) & = n^{\\beta\\beta}(\\mathbf{r}_1, \\mathbf{r}_2) \\\\\n# n^{\\alpha\\beta}(\\mathbf{r}_1, \\mathbf{r}_2) & = n^{\\beta\\alpha}(\\mathbf{r}_1, \\mathbf{r}_2) \n# \\end{align*}\n\nhelp(vis_drv.get_two_particle_density)\n","repo_name":"kthpanor/cb2070","sub_path":"docs/analyze.ipynb","file_name":"analyze.ipynb","file_ext":"py","file_size_in_byte":5896,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"38"} +{"seq_id":"72249861550","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom sklearn.metrics import mean_absolute_error, mean_squared_error,mean_absolute_percentage_error\nfrom scipy.spatial.distance import cosine\n\n# +\nviews = pd.read_csv('movies_views.csv' ,low_memory=False)\nratings = pd.read_csv('movies_ratings.csv',low_memory=False)\nmovies = pd.read_csv('movies_movie.csv',low_memory=False)\n\nmovies.drop(['rating','portrait','landscape'],inplace=True, axis=1)\nratings.drop('rorb_id',inplace=True, axis=1)\nratings.rename(columns = {'ron':'m_id'}, inplace = True)\n# -\n\nmovies.head()\n\nratings.head()\n\nviews.head()\n\n# +\n\nratings.rename(columns = {'rating':'centered_rating'}, inplace = True)\nratings.head()\n# -\n\nmsc = pd.merge(movies,views,on='m_id')\nmsc['average_rating'] = msc['sum'] / msc['count']\nmsc\n\npopularity_threshold = 25\nrating_popular_movie= msc.query('count >= @popularity_threshold')\nrating_popular_movie\n\ndf = pd.merge(rating_popular_movie,ratings,on='m_id')\ndf.drop('release_year', inplace=True, axis=1)\ndf\n\nuser_movie_matrix = df.pivot(index='rby', columns='m_id', values='centered_rating')\nuser_movie_train_matrix=None\nuser_movie_matrix\n\n\ndef compute_cosine_similarity(user1, user2):\n common_items = user_movie_matrix.loc[user1].dropna().index.intersection(user_movie_train_matrix.loc[user2].dropna().index)\n if len(common_items) == 0:\n return 0\n else:\n user1_ratings = user_movie_train_matrix.loc[user1][common_items]\n user2_ratings = user_movie_train_matrix.loc[user2][common_items]\n return 1 - cosine(user1_ratings, user2_ratings)\n\n\ndef find_k_nearest_neighbors(user, k):\n similarities = []\n for other_user in user_movie_train_matrix.index:\n if other_user != user:\n similarity = compute_cosine_similarity(user, other_user)\n similarities.append((other_user, similarity))\n similarities.sort(key=lambda x: x[1], reverse=True)\n return similarities[:k]\n\n\ndef user_based_recommendation(user, k, rm):\n if user not in user_movie_matrix.index:\n return \"No recommendations available for this user\"\n user_ratings = user_movie_matrix.loc[user].dropna()\n if len(user_ratings) == 0:\n return \"This user has not rated any movies\"\n global user_movie_train_matrix\n user_movie_train_matrix = user_movie_matrix.copy()\n train_rated_movies = user_movie_train_matrix.loc[user].dropna()\n num = int(0.2 * len(train_rated_movies))\n np.random.seed(42)\n movies_to_remove = np.random.choice(train_rated_movies.index, size=num, replace=False)\n \n user_movie_train_matrix.loc[user, movies_to_remove] = np.nan\n \n test_id = movies_to_remove.tolist()\n user_df = df[(df['rby'] == user) & (df['m_id'].isin(test_id))]\n actual_r = user_df[[\"m_id\", \"centered_rating\"]].reset_index(drop=True)\n \n neighbors = find_k_nearest_neighbors(user, k)\n neighbor_ratings = []\n neighbor_similarity_sum =[]\n for neighbor in neighbors:\n neighbor_user_id = neighbor[0]\n neighbor_similarity = neighbor[1]\n neighbor_ratings.append(user_movie_train_matrix.loc[neighbor_user_id].fillna(0) * neighbor_similarity)\n neighbor_similarity_sum.append(user_movie_train_matrix.loc[neighbor_user_id].notnull() * abs(neighbor_similarity))\n \n neighbor_ratings_df = pd.concat(neighbor_ratings, axis=1).sum(axis=1)\n\n neighbor_sum_df = pd.concat(neighbor_similarity_sum, axis=1).sum(axis=1)\n\n \n zz = pd.DataFrame({'m_id': neighbor_ratings_df.index, 'rating_s': neighbor_ratings_df.values})\n xx = pd.DataFrame({'m_id': neighbor_sum_df.index, 'similarity_sum': neighbor_sum_df.values})\n xz = pd.merge(zz,xx,on='m_id')\n \n xz['rating'] = round(xz['rating_s']/xz['similarity_sum'])\n xz.drop(['similarity_sum','rating_s'],inplace=True, axis=1)\n\n xz=xz.dropna()\n \n estimated_r=xz.copy()\n\n merged_ratings = pd.merge(actual_r, estimated_r, on='m_id', how='inner')\n \n if merged_ratings.shape[0]>0:\n mae = mean_absolute_error(merged_ratings['centered_rating'], merged_ratings['rating'])\n mape = mean_absolute_percentage_error(merged_ratings['centered_rating'], merged_ratings['rating'])\n else:\n mae=\"not available\"\n mape=\"not available\"\n\n user_ratings = user_movie_train_matrix.loc[user].dropna()\n \n unrated_movies = user_movie_matrix.columns.difference(user_ratings.index).tolist()\n\n if len(unrated_movies) == 0:\n return \"This user has rated all movies\"\n if neighbor_ratings_df[unrated_movies].empty:\n return \"There are no unrated movies left to recommend\"\n recommended_movie = xz[xz['m_id'].isin(unrated_movies)].sort_values('rating',ascending=False)['m_id'].tolist()\n \n recommended_movie=recommended_movie[:rm]\n tp=len(list(set(recommended_movie).intersection(test_id)))\n\n print(\"no. of nearest neighbour :\",len(neighbors))\n print(\"No. of recommended movies :\",len(recommended_movie))\n print(\"TP :\",tp)\n print(\"no. of Movies watched in test :\",len(test_id))\n print(\"Precison :\",tp/len(recommended_movie))\n print(\"recall :\",tp/len(test_id))\n print(\"MAE :\",mae)\n print(\"MAPE :\",mape)\n recommended_movie=recommended_movie[:5]\n movie_id_to_name = dict(zip(movies['m_id'], df['m_name']))\n movie_names = [movie_id_to_name[m_id] for m_id in recommended_movie]\n print(\"User-Neighborhood-Based Recommendation:\")\n return movie_names\n\nprint(user_based_recommendation(123, 15,60))\n","repo_name":"Vamp-Niklaus/Movie-Recommendation-System","sub_path":"Code.ipynb","file_name":"Code.ipynb","file_ext":"py","file_size_in_byte":5473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"38"} +{"seq_id":"39538024482","text":"# + [markdown] colab_type=\"text\" id=\"-WIZXFxI8OGP\"\n# # Trabajo1 - Presentado por Esteban Garcia Solis\n\n# + colab={} colab_type=\"code\" id=\"-FLcZFqcroqA\"\nimport math\nimport numpy as np\n\nimport torch\nfrom torch.distributions import constraints\nfrom torch.distributions.distribution import Distribution\nfrom torch.distributions.utils import _standard_normal, lazy_property\n\nimport torch.distributions as distrib\n\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\n\n\n# + [markdown] colab_type=\"text\" id=\"49ZlvzxlvDWX\"\n# 1) Escriba la función generarPuntosPlano, la cual genere $m=20$ puntos en $\\vec{x}_{i}\\in\\mathbb{R}^{3}$ aleatorios los cuales pertenezcan a un plano con función $f\\left(x,y\\right)=0.2x+y+\\epsilon, f:\\mathbb{R}^{2}\\rightarrow\\mathbb{R}$, con $\\epsilon$ una variable aleatoria de $\\mu=0$ y $\\sigma=0.05$ Almacenelos en una matriz de modo que: $$X=\\begin{bmatrix}| & | & |\\\\\\vec{x}_{1} & \\ldots & \\vec{x}_{m}\\\\| & | & |\\end{bmatrix}$$\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 370} colab_type=\"code\" id=\"36FMmR37wbTx\" outputId=\"908d9f20-ba8f-4f2d-9432-7257aa689cf5\"\ndef generarPuntosPlano(samples = 20):\n\n #create random X1 and X2 values\n x1_x2 = torch.rand(samples, 2)\n\n #create randodm error mu = 0 sigma = 0.5\n e = torch.reshape(torch.randn(samples) * 0.5, (samples, 1))\n\n #factors for plane equation x3= e + 0.2 x1 + x2\n factors = torch.tensor([[1.0], [0.2], [1.0]])\n\n #e, x1, x2 matrix\n e_x1_x2 = torch.cat((e, x1_x2), 1)\n\n #Calculate x3\n x3 = e_x1_x2.mm(factors)\n\n #Samples matrix (x1, x2, x3 removed e)\n X = torch.cat((e_x1_x2[:,1:3], x3), 1)\n\n return X\n\nX = generarPuntosPlano(20)\n\nprint(\"X: \", X.shape, \"\\n\", X)\n\n\n# + [markdown] colab_type=\"text\" id=\"mC5xHcUgwwze\"\n# 1.a) Grafique los puntos con la función scatter3.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 248} colab_type=\"code\" id=\"8urGV9hjwqBc\" outputId=\"23759b38-5407-4610-8077-8e3b736430a6\"\ndef plot3d(samples, show = True):\n \n #Plot\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n \n #labels\n ax.set_xlabel('x1')\n ax.set_ylabel('x2')\n ax.set_zlabel('x3')\n\n ax.scatter(X[:, 0].numpy(), X[:, 1].numpy(), X[:, 2].numpy(), c='r', marker='.')\n\n if show:\n plt.show()\n \n return ax\n\nax = plot3d(X, show = True)\n\n\n# + [markdown] colab_type=\"text\" id=\"XUgoyisxxzrd\"\n# 2) Cree una función $calcularEigenvectoresYValores(X, k'=2)$ la cual calcule los auto-vectores y auto-valores de tal matriz de covarianza $\\Sigma$.\n#\n# 2.a) ¿Cuáles deberían ser las dimensiones de la matriz de covarianza $\\Sigma$?\n# \n# **$$Sigma\\in\\mathbb{R}^{3\\times 3}$$**\n#\n# 2.b) Calcule la matriz de covarianza $\\Sigma$ usando la función implementada en el trabajo práctico anterior.\n#\n# 2.c) La función debe tomar los dos auto-vectores de $\\Sigma$ con mayores auto-valores $\\vec{v}_{1}$ y $\\vec{v}_{2}$ para crear un nuevo subespacio $E=\\textrm{espacioGenerado}\\left\\{ \\vec{v}_{1},\\vec{v}_{2}\\right\\}$ , y cree la matriz de la base con tales autovectores:$$V=\\begin{bmatrix}| & |\\\\\\vec{v}_{1} & \\vec{v}_{2}\\\\| & |\\end{bmatrix}.$$\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 353} colab_type=\"code\" id=\"FaQ6um2RruE-\" outputId=\"06228950-8349-4521-f6cd-5c5c973edf8e\"\ndef calcularEigenvectoresYValores(X, k = 2, best = True):\n \n #use numpy cov function to calculate the covariance matrix\n Sigma = torch.tensor(np.cov(X.transpose(0, 1).numpy()))\n \n #one eigen value per row, and its corresponding eigenvector per column\n EigenValues, EigenVectors = torch.eig(Sigma ,eigenvectors=True)\n \n #sort eigenValues \n dummy,order = EigenValues[:,0].sort(descending = best)\n \n #get best k eigenVectors\n V = EigenVectors[:,order[:k]]\n \n print(\"Sigma: \\n\", Sigma.shape, \"\\n\", Sigma)\n print(\"\\nEigenValues: \\n\", EigenValues[:,0])\n print(\"\\nEigenVectors: \\n\", EigenVectors.shape, \"\\n\", EigenVectors)\n print(\"\\nV: \\n\", V.shape, \"\\n\", V)\n \n return V\n\nV = calcularEigenvectoresYValores(X, k = 2, best = True)\n\n\n# + [markdown] colab_type=\"text\" id=\"q5I-Is2gzmLR\"\n# 2.d) Grafique los puntos obtenidos en la matriz X usando la función scatter3, y grafique en la misma figura los 2 auto-vectores que forman el espacio generador, con origen en la media de los datos o centroide $\\mu$. Comente los resultados.\n#\n# **Los eigenvectors en el grafico muestran la direcion del nuevo espacio**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 248} colab_type=\"code\" id=\"S7fFxiOz2Tf_\" outputId=\"2f11d7e1-b58b-434b-deda-9ae3362f3bad\"\ndef plotVectors(V, mu, ax, show = True):\n \n k = list(V.size())[1]\n \n for i in range(k): \n x1 = [mu[0].numpy(), V[0,i].numpy()]\n x2 = [mu[1].numpy(), V[1,i].numpy()]\n x3 = [mu[2].numpy(), V[2,i].numpy()]\n \n ax.plot(x1, x2, x3)\n\n if show:\n plt.show()\n \n return ax\n\n\nmu = torch.mean(X, 0)\nax = plot3d(X, show = False)\nax = plotVectors(V, mu, ax, show = True)\n\n\n# + [markdown] colab_type=\"text\" id=\"2zpIxfRM3Uzz\"\n# 3) Verifique si tales auto-vectores son orto-normales, si es así, ¿porqué sucede esto?\n#\n# **Son orto-normales porque la matriz de covarianza $\\Sigma$ es simetrica**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 67} colab_type=\"code\" id=\"ktWizMsB4UKw\" outputId=\"09c199ab-7672-4d6a-b3c0-11992cda46bf\"\ndef orthoNormalCheck(V): \n #verify that the norm of each eigenvector is one, since eigen vectors are orthonormals\n print(\"orthonormal check\")\n \n k = list(V.size())[1]\n \n for i in range(k): \n print(torch.norm(V[:, i], 2))\n \northoNormalCheck(V)\n\n\n# + [markdown] colab_type=\"text\" id=\"n6Mf53m33p2-\"\n# 4) Reduzca la dimensionalidad de los datos de modo que se pase de un espacio en $\\mathbb{R}^{3}$ a un espacio en $\\mathbb{R}^{2}$ usando 2 los auto-vectores con mayores auto-valores, en la función reducirDimensionalidadDataset(dataset, baseVectors), sin usar estructuras de repetición tipo for. \n#\n# 4.a) Calcule la muestra promedio $\\vec{\\mu}\\in\\mathbb{R}^{3}$ para los datos en X, y calcule una nueva matriz $U\\in\\mathbb{R}^{3\\times m}$ en la que cada vector en el espacio tenga su origen en $\\vec{\\mu}$, haciendo que cada columna i esté dada por $\\vec{u}_{i}=\\vec{x}_{i}-\\vec{\\mu}$.\n#\n# 4.b) Para cada muestra $\\vec{u}_{i}$ calcule la magnitud de la proyección en cada eje del nuevo espacio vectorial $E_{1}=\\textrm{espacioGenerado}\\left\\{ \\vec{v}_{1},\\vec{v}_{2}\\right\\}$ , creando una muestra con dimensión reducida $$\\vec{x}_{i}^{r}=\\begin{bmatrix}x_{i,1}^{r}\\\\x_{i,2}^{r}\\end{bmatrix} donde: \\begin{array}{c}x_{i,1}^{r}=\\vec{u}_{i}\\cdot\\vec{v}_{1}\\\\x_{i,2}^{r}=\\vec{u}_{i}\\cdot\\vec{v}_{2}\\end{array}$$\n#\n# 4.c) Agrupe los resultados en la matriz $X^{r}=\\begin{bmatrix}| & | & |\\\\\\vec{x}_{1}^{r} & \\ldots & \\vec{x}_{m}^{r}\\\\| & | & |\n# \\end{bmatrix}$ y grafiquelos usando la función scatter2. Comente los resultados, ¿Realmente hubo una reducción de la dimensionalidad, y se preservaron los ejes de mayor varianza?\n#\n# **Si hay una reducción de $\\mathbb{R}^{3}$ a $\\mathbb{R}^{2}$, los ejes se selecionaron de acuerdo a la magnitud de los eigen-values por lo que se debe preservar la proyeccion a los eigen-vectors que representan la mayor variación.**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 269} colab_type=\"code\" id=\"j8T2X2EmztjC\" outputId=\"0de8049b-963d-4643-8c07-4ee2079d3975\"\ndef reducirDimensionalidadDataset(X, V):\n \n mu = torch.mean(X, 0)\n U = X - mu\n\n X_gamma = torch.mm(U, V.float())\n\n return X_gamma\n\nX_gamma = reducirDimensionalidadDataset(X, V)\n\nif list(V.size())[1] == 2:\n plt.scatter(X_gamma[:, 0], X_gamma[:, 1], color = \"black\", marker = \".\")\n plt.show()\n\n\n# + [markdown] colab_type=\"text\" id=\"WkwqImKk7Ay_\"\n# 5) Calcule el error al usar los dos autovectores con mayores autovalores: $$V\\in\\mathbb{R}^{3\\times2}V=\\begin{bmatrix}| & |\\\\\n# \\vec{v}_{1} & \\vec{v}_{2}\\\\| & |\\end{bmatrix}.$$\n#\n# Calculelo generando una matriz con los vectores proyectados $P\\in\\mathbb{R}^{3\\times m}$, la pseudoinversa $V^{+}\\in\\mathbb{R}^{2\\times3}$, y el conjunto de muestras con la media sustraída \n#\n# $U\\in\\mathbb{R}^{3\\times m}P=V\\,\\left(V^{T}V\\right)^{-1}V^{T}U=V\\,V^{+}U$, midiendo el error con el RMSE de la matriz de datos proyectados $P$, respecto a los datos con la media extraida $U$. \n#\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34} colab_type=\"code\" id=\"1RLVES274pGh\" outputId=\"93615d73-b298-4423-e666-745158c93c7f\"\ndef calcularError(V, X):\n \n mu = torch.mean(X, 0)\n U = (X - mu).transpose(0,1).float()\n V = V.float()\n \n V_pInv = torch.tensor(np.linalg.pinv(V))\n \n P = V.mm(V_pInv).mm(U)\n \n #print(\"P: \", P)\n \n errorsPerSample = torch.norm(P - U, 2, 0)\n error = torch.norm(errorsPerSample, 2, 0) \n \n print(\"error: \", error)\n \ncalcularError(V, X)\n\n\n# + [markdown] colab_type=\"text\" id=\"clTDRt-AEvI2\"\n# 5.a) Compare el error con usar sólo el mejor auto-vector $\\vec{v}_{1}$. Comente si disminuye o aumenta el error.\n#\n# **Al usar solamente el mejor autovector el error aumenta.**\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 34} colab_type=\"code\" id=\"cfuBI-WcTNt0\" outputId=\"de066b34-8b12-443f-f52f-e8338e97a1e7\"\ncalcularError(V[:,0:1], X)\n\n","repo_name":"Essbante/Aprendizaje_automatico","sub_path":"Esteban Garcia Trabajo1.ipynb","file_name":"Esteban Garcia Trabajo1.ipynb","file_ext":"py","file_size_in_byte":9135,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"38"} +{"seq_id":"7202096700","text":"# + [markdown] id=\"ad2vGHBh9TEK\"\n# # Laser-Embeddings Approach\n# By: Haasitha Pidaparthi\n#\n# Reference: \n# - https://github.com/facebookresearch/LASER\n# - https://engineering.fb.com/2019/01/22/ai-research/laser-multilingual-sentence-embeddings/\n# - https://github.com/yannvgn/laserembeddings/tree/ceb3818c998099d315a935210d3962640922fa8b\n# - https://pypi.org/project/laserembeddings/\n# - https://www.kaggle.com/kiatweitan/contradictory-oh-my-dear-watson-laser-embedding\n# - https://www.kaggle.com/camnugent/faa-laser-days-of-the-week-hypothesis-test/comments#214360\n#\n# ## 1. Import libraries and datasets\n\n# + _uuid=\"8f2839f25d086af736a60e9eeb907d3b93b6e0e5\" _cell_guid=\"b1076dfc-b9ad-4769-8c92-a6c4dae69d19\" id=\"9l2iJPwN6x9d\"\n# !pip install laserembeddings\n\n# + id=\"-9hmqS-I6x9e\"\nimport pandas as pd\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n# modeling\nimport laserembeddings\nfrom laserembeddings import Laser\nimport tensorflow as tf\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom sklearn.preprocessing import OneHotEncoder\n\nfrom fastcache import clru_cache\nfrom typing import List, Union\n\n# + id=\"HndQJK366x9e\"\ndf_train = pd.read_csv('../input/contradictory-my-dear-watson/train.csv', index_col=0).fillna('')\ndf_test = pd.read_csv('../input/contradictory-my-dear-watson/test.csv', index_col=0).fillna('')\ndf_train\n\n# + [markdown] id=\"2H9AziHX6x9e\"\n# ## 2. LASER Embeddings\n#\n\n# + id=\"2PY6gI8r6x9f\" language=\"bash\"\n# mkdir -p models/laser/\n# for FILE in bilstm.93langs.2018-12-26.pt 93langs.fcodes 93langs.fvocab; do\n# wget -cq https://dl.fbaipublicfiles.com/laser/models/$FILE -O models/laser/$FILE\n# done\n\n# + id=\"RDOziNvD6x9f\"\nconfig = {\n \"laser\": {\n \"base_dir\": \"./models/laser\",\n \"bpe_codes\": \"./models/laser/93langs.fcodes\",\n \"bpe_vocab\": \"./models/laser/93langs.fvocab\",\n \"encoder\": \"./models/laser/bilstm.93langs.2018-12-26.pt\",\n }\n}\n\n@clru_cache(None)\ndef get_laser_model():\n laser_model = Laser(\n bpe_codes = config['laser']['bpe_codes'],\n bpe_vocab = config['laser']['bpe_vocab'],\n encoder = config['laser']['encoder'],\n tokenizer_options = None,\n embedding_options = None\n )\n return laser_model\n\n# Template for encoding text\ndef laser_encode(text: Union[str, List[str]], lang='en', normalize=True) -> np.ndarray:\n laser_model = get_laser_model()\n \n if isinstance(text, str):\n sentences = [ text ]\n else:\n sentences = list(text)\n\n embedding = laser_model.embed_sentences(sentences, lang=lang)\n if normalize:\n embedding = embedding / np.sqrt(np.sum(embedding**2, axis=1)).reshape(-1,1)\n \n return embedding\n\n\n# + id=\"k9NVhzr76x9g\"\ndef encode_X(df):\n premise = laser_encode(df['premise'], lang=df['lang_abv'])\n hypothesis = laser_encode(df['hypothesis'], lang=df['lang_abv'])\n cosine = np.array([\n cosine_similarity( premise[n].reshape(1,-1), hypothesis[n].reshape(1,-1) )\n for n in range(len(df))\n ]).reshape(-1,1)\n X = np.array([\n np.concatenate([ premise[n], hypothesis[n], cosine[n] ])\n for n in range(len(df))\n ])\n return X\n \ndef encode_Y(df):\n encoder = OneHotEncoder().fit([ [0], [1], [2] ])\n return encoder.transform( df['label'].to_numpy().reshape(-1,1) ).toarray()\n\ndef decode_Y(one_hot_encoded):\n decoded = tf.argmax(one_hot_encoded, axis=1)\n return decoded.numpy().astype(np.int32)\n\n\n# + id=\"c-WVk5fc6x9g\"\n# %%time\nX_train = encode_X(df_train)\nY_train = encode_Y(df_train)\n\n# + [markdown] id=\"PKCDHZr16x9h\"\n# ## 3. Neural Network\n\n# + id=\"n2vvlsKj6x9h\"\n# Parameters\ntest_size = 0.2\nepochs = 100\nbatch_size = 32\nverbose = 2\n\n# + id=\"0GdRHjHC6x9i\"\n# split data into training and testing: 80 to 20\nX_train, X_test, Y_train, Y_test = train_test_split(X_train, Y_train, test_size=test_size, randon_state=42)\n\n# + id=\"FpqB7W_C6x9h\"\nmodel = tf.keras.Sequential([\n tf.keras.Input(shape=(X_train.shape[1],)),\n tf.keras.layers.Dense(512, activation=tf.keras.layers.LeakyReLU(alpha=0.1)),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dropout(0.25),\n tf.keras.layers.Dense(128, activation=tf.keras.layers.LeakyReLU(alpha=0.1)),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dropout(0.25),\n tf.keras.layers.Dense(32, activation=tf.keras.layers.LeakyReLU(alpha=0.1)),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dropout(0.25),\n tf.keras.layers.Dense(8, activation=tf.keras.layers.LeakyReLU(alpha=0.1)),\n tf.keras.layers.BatchNormalization(),\n tf.keras.layers.Dropout(0.25),\n tf.keras.layers.Dense(Y_train.shape[1], activation=tf.keras.activations.sigmoid),\n ])\nmodel.summary()\n\n# + id=\"ElVQ03ly6x9h\"\nmodel.compile(\n loss = tf.keras.losses.CategoricalCrossentropy(from_logits=True),\n optimizer = tf.keras.optimizers.Adam(learning_rate=1e-5),\n metrics = [ tf.keras.metrics.CategoricalAccuracy() ],\n )\n\n# + jupyter={\"outputs_hidden\": true} id=\"TRHWgDS76x9i\"\n# %%time\nhistory = model.fit(\n X_train, Y_train, \n batch_size = batch_size, \n epochs = epochs, \n validation_split = test_size,\n callbacks = [\n tf.keras.callbacks.EarlyStopping(\n monitor = 'val_loss', \n mode = 'min', \n verbose = 0, \n patience = 100\n ),\n tf.keras.callbacks.ModelCheckpoint(\n 'model.h5', \n monitor = 'val_categorical_accuracy', \n mode = 'max', \n verbose = 0, \n save_best_only = True\n )\n ],\n verbose = verbose\n )\n\n# + id=\"hEeutryY6x9i\"\nprint()\nprint('Train Accuracy')\nmodel.evaluate(X_train, Y_train)\n\nprint('Test Accuracy')\nmodel.evaluate(X_test, Y_test)\n\n# + [markdown] id=\"4wT8FADl6x9i\"\n# ## 4. Visualize Model Training\n\n# + id=\"kkWND78M6x9i\"\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('Model Loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'val'], loc='upper left')\nplt.show()\n\n# + [markdown] id=\"ROTyFjv-6x9j\"\n# ## 5. Submission\n\n# + id=\"zfwyYAz06x9j\"\n# %%time \nX_test = encode_X( df_test)\nY_test = decode_Y( model.predict(X_test) )\n\n# + id=\"5S8g9IRS6x9j\"\ndf_submission = pd.read_csv('../input/contradictory-my-dear-watson/sample_submission.csv', index_col=0).fillna('')\ndf_submission['prediction'] = Y_test\ndf_submission.to_csv('submission.csv')\n# !head submission.csv\n","repo_name":"solarbro/cmpe258-team-project","sub_path":"laser_embeddings.ipynb","file_name":"laser_embeddings.ipynb","file_ext":"py","file_size_in_byte":6774,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"38"} +{"seq_id":"11917419127","text":"# +\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport seaborn as sns\nfrom sklearn.datasets import fetch_openml\n\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.base import BaseEstimator\nfrom sklearn.model_selection import cross_val_score, cross_val_predict\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.svm import SVC\n\nfrom sklearn.metrics import (confusion_matrix, classification_report, precision_score, \n recall_score, f1_score, precision_recall_curve, roc_curve)\n\n\nmpl.rc('axes', labelsize=14)\nmpl.rc('xtick', labelsize=12)\nmpl.rc('ytick', labelsize=12)\n# -\n\nmnist = fetch_openml('mnist_784', version=1)\n\nmnist.keys()\n\nX, y = mnist['data'], mnist['target']\n\n# Show a few digits\nfor i in range(1,11):\n digit = X[i]\n digit_image = digit.reshape(28,28)\n\n plt.imshow(digit_image, cmap='binary')\n plt.axis('off')\n plt.show()\n print(y[i])\n\n# +\n# Cast label as an int\ny = y.astype(np.uint8)\n\n# Create train and test sets\nX_train, X_test, y_train, y_test = X[:60000], X[:60000], y[:60000], y[:60000]\n\n# Try to identify only one digit - turn this into binanry classificaiton problem\ny_train_5 = (y_train==5)\ny_test_5 = (y_test==5)\n\nsome_digit= X[0] # This digit is a five\n\n# try Stochastic GD because it cna handle large datasets\nclf_sgd = SGDClassifier().fit(X_train, y_train_5)\ny_pred = clf_sgd.predict([some_digit])\ny_pred \n# -\n\n# Evaluate Performance\ncross_val_score(clf_sgd, X_train, y_train_5, cv=5, scoring='accuracy')\n\n\n# +\n# Now try a less smart model to predict everything that is not a 5.\nclass Never5Classifier(BaseEstimator):\n def fit(self, X, y=None):\n return self\n def predict(self, X):\n return np.zeros((len(X),1),dtype=bool)\n\nclf_never_5 = Never5Classifier()\ncross_val_score(clf_never_5, X_train, y_train_5, cv=5, scoring='accuracy')\n# 90% is right because 10% of the images are 5's but this doesnt' tell us much anyways\n# -\n\ny_train_pred = cross_val_predict(clf_sgd, X_train, y_train_5, cv=5)\n\n# Examine Performance\nprint(classification_report(y_train_5, y_train_pred))\nprint(confusion_matrix(y_train_5, y_train_pred))\n\n# Consistent with what is above\nprint(precision_score(y_train_5, y_train_pred))\nprint(recall_score(y_train_5, y_train_pred))\nprint(f1_score(y_train_5, y_train_pred))\n\n# Precision/Recall Tradeoff\n# Check the threshold value used in determining the cutoff\ny_scores = clf_sgd.decision_function([some_digit])\ny_scores\n\n# Example of threshold\nthreshold = 3411 \ny_some_digit_pred = (y_scores > threshold)\ny_some_digit_pred\n\n# To decide which threshold to use use cv prediction with decision function for the method\ny_scores = cross_val_predict(clf_sgd, X_train, y_train_5, cv=5, method='decision_function')\ny_scores\n\n# +\n# Plot precions vs recall curves for all possible thresholds\nprecisions, recalls, thresholds = precision_recall_curve(y_train_5, y_scores)\n\ndef plot_precision_recall_vs_threshold(precisions, recalls, thresholds):\n \"\"\" Plots precision vs recall for all thresholds\"\"\"\n plt.figure(figsize=(12,8))\n plt.plot(thresholds, precisions[:-1], \"b--\", label='Precision')\n plt.plot(thresholds, recalls[:-1],'g-',label='Recall')\n plt.legend()\n plt.title('Precsion vs Recall')\n plt.xlabel('Threshold')\n plt.show()\n \nplot_precision_recall_vs_threshold(precisions, recalls, thresholds)\n\n\n# +\ndef plot_precision_vs_recall(precisions, recalls):\n \"\"\" Plot Precision vs. Recall \"\"\"\n plt.figure(figsize=(8,6))\n plt.plot(recalls, precisions, 'b--', linewidth=2)\n plt.xlabel('Recall', fontsize=16)\n plt.ylabel('Precisions', fontsize=16)\n plt.axis([0,1,0,1])\n plt.title('Recall vs. Precision', fontsize=20)\n\nplot_precision_vs_recall(precisions, recalls)\n \n# -\n\n# Pick the threshold value that gives 90% precision\nthreshold_90_precision = thresholds[np.argmax(precisions>=0.90)]\nprint(f\"Threshold to use for 90% precision: \" + np.str(threshold_90_precision))\n\n# +\ny_train_pred_90 = (y_scores >= threshold_90_precision)\n\n# Check Precision and Recall\nprecision_score(y_train_5, y_train_pred_90)\nrecall_score(y_train_5, y_train_pred_90)\n# -\n\n# ## ROC Curve\n\n# +\n#Plot the ROC Curve\nfpr, tpr, thresholds = roc_curve(y_train_5, y_scores)\n\ndef plot_roc_curve(fpr, tpr, label=None):\n \"\"\" Plot the ROC curve. \"\"\"\n plt.figure(figsize=(8,6))\n plt.plot(fpr,tpr, linewidth=3)\n plt.ylabel('False Positive Rate')\n plt.xlabel('True Positive Rate')\n plt.title('ROC Curve')\n plt.show()\n\nplot_roc_curve(fpr,tpr)\n# -\n\n# Train a Random Forest Classifier against the data\nclf_forest = RandomForestClassifier()\ny_probas_forest = cross_val_predict(clf_forest,X_train, y_train_5, cv=3, method='predict_proba')\n\n# Positive Class probability\ny_scores_forest = y_probas_forest[:,1]\ny_scores_forest\n\n# +\nfpr_forest, tpr_forest, thresholds_forest = roc_curve(y_train_5, y_scores_forest)\n\nplt.plot(fpr, tpr,'b:', label='SGD')\nplt.plot(fpr_forest,tpr_forest, 'r--', linewidth=1, label='Random Forest')\nplt.legend()\n\n# +\n# Random Forest has larger AUC - Better Model\n# -\n\n# ### SGD Model on entire dataset\n\n# Check the number of times each digit appears in the training data\npd.DataFrame(y_train).value_counts()\n\n# Scale the data to see if can get an improvement in accuracy\nscaler = StandardScaler()\nX_train_scaled = scaler.fit_transform(X_train)\ncross_val_score(clf_sgd, X_train_scaled, y_train, cv=3, scoring='accuracy', n_jobs=-1, verbose=1)\n\ny_pred = cross_val_predict(clf_sgd, X_train_scaled, y_train, cv=3, verbose=1, n_jobs=-1)\n\nplt.figure(figsize=(14,8))\nconf_mat_color = sns.diverging_palette(10, 150, as_cmap=True)\nsns.heatmap(confusion_matrix(y_test, y_pred), annot=True, fmt='g', cmap=conf_mat_color)\n\n# +\n# Plot the accuracy\ncm = confusion_matrix(y_test, y_pred)\nrow_sums = cm.sum(axis=1, keepdims=True)\nnorm_cm = (cm / row_sums) *100\n\nplt.figure(figsize=(14,8))\nsns.heatmap(norm_cm,annot=True, fmt='g', cmap=conf_mat_color)\n# -\n\n\n","repo_name":"nrichdev21/machine_learning","sub_path":"classification/.ipynb_checkpoints/MULITICLASS CLASSIFICATION - MNIST-checkpoint.ipynb","file_name":"MULITICLASS CLASSIFICATION - MNIST-checkpoint.ipynb","file_ext":"py","file_size_in_byte":6008,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"38"} +{"seq_id":"16168859146","text":"# + id=\"jD0C1KNtjHx2\"\nimport pandas as pd\n\n# + id=\"07nvW_eJkeAD\"\nfall = [19685, 19053, 19180, 19379, 19135, 18465, 17505, 17516]\nwinter = [18824, 17962, 18621, 18604, 18647, 17865, 17170, 17109]\nspring = [17116, 17601, 17814, 17849, 17187, 16581, 16522]\nsummer = [1593, 1671, 1238, 1087, 917, 813, 736, 746]\n\nfallDates = ['October 2021', 'October 2020', 'October 2019', 'October 2018', 'October 2017', 'October 2016', 'October 2015', 'October 2014']\nwinterDates = ['January 2022', 'January 2021', 'January 2020', 'January 2019', 'January 2018', 'January 2017', 'January 2016', 'January 2015']\nspringDates = ['April 2021', 'April 2020', 'April 2019', 'April 2018', 'April 2017', 'April 2016', 'April 2015']\nsummerDates = ['July 2021', 'July 2020', 'July 2019', 'July 2018', 'July 2017', 'July 2016', 'July 2015', 'July 2014']\n\n# + id=\"iwDl8emeCS-c\"\nfallData = pd.DataFrame(\n {'month': fallDates,\n 'price': fall,\n 'quarter': 'fall'\n })\nwinterData = pd.DataFrame(\n {'month': winterDates,\n 'price': winter,\n 'quarter': 'winter',\n })\nspringData = pd.DataFrame(\n {'month': springDates,\n 'price': spring,\n 'quarter': 'spring'\n })\nsummerData = pd.DataFrame(\n {'month': summerDates,\n 'price': summer,\n 'quarter': 'summer'\n })\n\n# + id=\"toDMI5ldCe2W\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"daeca7c1-1d0c-4878-85aa-0a59050f523f\"\nframes = [fallData, winterData, springData, summerData]\nresult = pd.concat(frames)\ndf = result.reset_index(drop=True)\nlen(df)\n\n# + id=\"5Oqu695DFNOw\"\ndf['month'] = pd.to_datetime(df['month']).dt.to_period('M')\n\n# + id=\"94H0DHFjFZrS\"\n\n\n# + id=\"JekqCyB-Dr5W\"\ndf = df.set_index('month').resample('M').interpolate()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"1qXaZNuSF3Ml\" outputId=\"141c827d-c8f6-42fe-d11e-6efa65bf7f43\"\nlen(df)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"bCnFCYSCGC2p\" outputId=\"8f55ce63-a8c1-4b27-d589-40d70be13198\"\ndf = df.drop('quarter', 1)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"8DzjYVxdGpCI\" outputId=\"299801a1-b781-48b8-f312-ad6deb590f49\"\ndf.tail\n\n# + id=\"ed2ziPf5GwrI\"\ndf.to_csv('monthly_enrollment_data')\n\n# + id=\"hkkF2ya4HQJ0\"\n# For median household income\nmedian = [64257, 64841, 75929, 76633, 84213, 85770, 93015, 100179]\nyear = ['2014', '2015', '2016', '2017', '2018', '2019', '2020', '2021']\n\n# + id=\"upMtv6qPJceb\"\ndf = pd.DataFrame(\n {'year': year,\n 'income': median,\n })\n\n# + id=\"zoMrMkJwJmtH\"\ndf['year'] = pd.to_datetime(df['year']).dt.to_period('Y')\n\n# + id=\"TD0ZSXGBJqUw\"\ndf = df.set_index('year').resample('M').interpolate()\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"LBKTvzxGJy29\" outputId=\"d36bc49b-7447-43eb-88fa-92cf79950894\"\ndf.size\n\n# + id=\"9blyu89MJ1zt\"\ndf.to_csv('monthly_median_household_income_data')\n\n# + id=\"PjYjCoBAJ5AW\"\ndf = pd.read_csv('export.csv')\ndf.label = pd.to_datetime(df.label, format='%Y')\n\n# + id=\"kSJqEvs_biHD\"\n# df = df.set_index('label').resample('M').interpolate()\n(df.set_index('label').resample('M').bfill().reset_index()).to_csv('data.csv')\n# df.tail\n\n# + id=\"I-P-c9vncKJU\"\ndf.to_csv('monthly_population.csv')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"U2_bdq8lcSMB\" outputId=\"f55b1d8e-bc94-4bb4-c959-137226ff9567\"\ndf.size\n\n# + id=\"tOmU_6KOcW1-\"\ndf.to_csv('monthly_median_household_income_data')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 375} id=\"wF4TRZ7WckFx\" outputId=\"51ab3c0d-2657-4c4a-f29c-64b69f7fd1dc\"\nfrom google.colab import files\nfiles.download(\"sample.csv\")\n\n# + id=\"slXRfQHYcv2F\"\nimport pandas as pd\nlist1 = ['December 2021','December 2020','December 2019','December 2018','December 2017','December 2016','December 2015','December 2014']\nlist2 = [64503,62956,64522,64725,64860,64452,64119,63197]\n\n\ndf1 = pd.DataFrame (list1, columns = ['date'])\ndf2 = pd.DataFrame (list2, columns = ['population'])\ndf1 = pd.to_datetime(df1.date).dt.to_period('M')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 300} id=\"LIp7aGMzwwUr\" outputId=\"b3c223e3-8a33-4197-c621-f390e6c68faf\"\ndf = pd.DataFrame(\n {'date': df1,\n 'population': list2,\n })\ndf\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 455} id=\"fHUCjahbwCge\" outputId=\"8442e1a9-0ae2-411c-c2b5-abebad9a5581\"\ndf.set_index('date').resample('M').interpolate()\n\n# + id=\"WB_aQCMFwEGd\"\ndf = df.set_index('date').resample('M').interpolate()\ndf.to_csv('monthly_population.csv')\n\n# + id=\"Oj63YjO5wl45\"\nimport pandas as pd\n\ndf = pd.read_csv('data.csv')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"5SUuc_fwy5sJ\" outputId=\"81de8c7d-a040-4117-9187-259b35ebf5fb\"\ndf.columns\n\n# + id=\"mp4Irgv7y7PE\"\ndf.month = pd.to_datetime(df.month).dt.to_period('M')\n# df = df.set_index('month')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 308} id=\"CF27S2B9zFW9\" outputId=\"61961a8f-a130-4fad-dadc-9b0ceb94e815\"\n# months = [g for n, g in df.index.groupby(pd.Grouper(key='Index',freq='M'))]\n# df.month[0].dt.month\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"LGyw4HGezJ08\" outputId=\"b3291fb9-46a9-443b-ee5e-e747649e118e\"\ndf.month[0].month\n\n# + id=\"uHXuMeN40B2E\"\njan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec = [],[],[],[],[],[],[],[],[],[],[],[],\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"yeQX2txu1VrV\" outputId=\"7674c67c-74ae-4a8e-8f50-5b5fb1b02374\"\nfor i in df.index:\n print(i)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"o7UNONK-1xED\" outputId=\"fec588a6-50a5-4b39-f0ba-611afd0750c1\"\ndf.iloc[0]\n\n# + id=\"SIqJ4HbS2Rvp\"\n(df[(df['month'].dt.month == 1)]).to_csv(\"jan.csv\")\n(df[(df['month'].dt.month == 2)]).to_csv(\"feb.csv\")\n(df[(df['month'].dt.month == 3)]).to_csv(\"mar.csv\")\n(df[(df['month'].dt.month == 4)]).to_csv(\"apr.csv\")\n(df[(df['month'].dt.month == 5)]).to_csv(\"may.csv\")\n(df[(df['month'].dt.month == 6)]).to_csv(\"jun.csv\")\n(df[(df['month'].dt.month == 7)]).to_csv(\"jul.csv\")\n(df[(df['month'].dt.month == 8)]).to_csv(\"aug.csv\")\n(df[(df['month'].dt.month == 9)]).to_csv(\"sep.csv\")\n(df[(df['month'].dt.month == 10)]).to_csv(\"oct.csv\")\n(df[(df['month'].dt.month == 11)]).to_csv(\"nov.csv\")\n(df[(df['month'].dt.month == 12)]).to_csv(\"dec.csv\")\n\n# + id=\"e0qhGdDs24UD\"\n\n","repo_name":"ysun155/Math140-PROJECT","sub_path":"140_data_interpolation.ipynb","file_name":"140_data_interpolation.ipynb","file_ext":"py","file_size_in_byte":6137,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"38"} +{"seq_id":"32055808119","text":"# # Jsonformer\n#\n# [Jsonformer](https://github.com/1rgs/jsonformer) 是一个包装本地`HuggingFace pipeline`模型以对JSON Schema的子集进行结构化解码的库。\n#\n# 它的工作原理是填充结构标记,然后从模型中抽取内容标记。\n#\n# **警告 - 此模块仍处于试验阶段**\n\n# !pip install --upgrade jsonformer > /dev/null\n\n# ### HuggingFace 基线\n#\n# 首先,让我们通过检查没有结构化解码的模型输出来建立定性基线。\n\nimport logging\nlogging.basicConfig(level=logging.ERROR)\n\n# +\nfrom typing import Optional\nfrom langchain.tools import tool\nimport os\nimport json\nimport requests\n\nHF_TOKEN = os.environ.get(\"HUGGINGFACE_API_KEY\")\n\n@tool\ndef ask_star_coder(query: str, \n temperature: float = 1.0,\n max_new_tokens: float = 250):\n \"\"\"Query the BigCode StarCoder model about coding questions.\"\"\"\n url = \"https://api-inference.huggingface.co/models/bigcode/starcoder\"\n headers = {\n \"Authorization\": f\"Bearer {HF_TOKEN}\",\n \"content-type\": \"application/json\"\n }\n payload = {\n \"inputs\": f\"{query}\\n\\nAnswer:\",\n \"temperature\": temperature,\n \"max_new_tokens\": int(max_new_tokens),\n }\n response = requests.post(url, headers=headers, data=json.dumps(payload))\n response.raise_for_status()\n return json.loads(response.content.decode(\"utf-8\"))\n\n\n\n# -\n\nprompt = \"\"\"You must respond using JSON format, with a single action and single action input.\nYou may 'ask_star_coder' for help on coding problems.\n\n{arg_schema}\n\nEXAMPLES\n----\nHuman: \"So what's all this about a GIL?\"\nAI Assistant:{{\n \"action\": \"ask_star_coder\",\n \"action_input\": {{\"query\": \"What is a GIL?\", \"temperature\": 0.0, \"max_new_tokens\": 100}}\"\n}}\nObservation: \"The GIL is python's Global Interpreter Lock\"\nHuman: \"Could you please write a calculator program in LISP?\"\nAI Assistant:{{\n \"action\": \"ask_star_coder\",\n \"action_input\": {{\"query\": \"Write a calculator program in LISP\", \"temperature\": 0.0, \"max_new_tokens\": 250}}\n}}\nObservation: \"(defun add (x y) (+ x y))\\n(defun sub (x y) (- x y ))\"\nHuman: \"What's the difference between an SVM and an LLM?\"\nAI Assistant:{{\n \"action\": \"ask_star_coder\",\n \"action_input\": {{\"query\": \"What's the difference between SGD and an SVM?\", \"temperature\": 1.0, \"max_new_tokens\": 250}}\n}}\nObservation: \"SGD stands for stochastic gradient descent, while an SVM is a Support Vector Machine.\"\n\nBEGIN! Answer the Human's question as best as you are able.\n------\nHuman: 'What's the difference between an iterator and an iterable?'\nAI Assistant:\"\"\".format(arg_schema=ask_star_coder.args)\n\n# +\nfrom transformers import pipeline\nfrom langchain.llms import HuggingFacePipeline\n\nhf_model = pipeline(\"text-generation\", model=\"cerebras/Cerebras-GPT-590M\", max_new_tokens=200)\n\noriginal_model = HuggingFacePipeline(pipeline=hf_model)\n\ngenerated = original_model.predict(prompt, stop=[\"Observation:\", \"Human:\"])\nprint(generated)\n# -\n\n# ***这并不是很令人印象深刻,是吗?它根本没有遵循JSON格式!让我们尝试使用结构化解码器。***\n\n# ## JSONFormer LLM Wrapper\n#\n# 让我们再试一次,现在将Action输入的JSON Schema提供给模型。\n\ndecoder_schema = {\n \"title\": \"Decoding Schema\",\n \"type\": \"object\",\n \"properties\": {\n \"action\": {\"type\": \"string\", \"default\": ask_star_coder.name},\n \"action_input\": {\n \"type\": \"object\",\n \"properties\": ask_star_coder.args,\n }\n }\n} \n\nfrom langchain.experimental.llms import JsonFormer\njson_former = JsonFormer(json_schema=decoder_schema, pipeline=hf_model)\n\nresults = json_former.predict(prompt, stop=[\"Observation:\", \"Human:\"])\nprint(results)\n\n# **看,没有解析错误了!**\n\n\n","repo_name":"liteli1987gmail/python_langchain-CN","sub_path":"docs/modules/models/llms/integrations/jsonformer_experimental.ipynb","file_name":"jsonformer_experimental.ipynb","file_ext":"py","file_size_in_byte":3750,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-jupyter-script","pt":"34"} +{"seq_id":"12376779524","text":"# 1. import libraries\nimport requests # to download html code\nfrom bs4 import BeautifulSoup # to navigate through the html code\nimport pandas as pd\nimport numpy as np\nimport re\n\n# 2. find url and store it in a variable\nurl = \"https://www.billboard.com/charts/hot-100/\"\n\n# 3. download html with a get request. Use the function request.get() and store the output in response\nresponse = requests.get(url)\n# 200 status code means OK! response.status_code\nprint(response.status_code)\n\n# 4.1. parse html (create the 'soup')\nsoup = BeautifulSoup(response.text, 'html.parser')\n# 4.2. check that the html code looks like it should\n#print(soup.prettify())\n\ntext_0 = soup.select(\"a.c-title__link\")[0].get_text()\n\ntext_0\n\ntext_1= soup.select(\"h3#title-of-a-story.c-title.a-no-trucate.a-font-primary-bold-s\")[0].get_text(strip=True)\n\nsoup.select(\"h3#title-of-a-story.c-title.a-no-trucate.a-font-primary-bold-s\")[0]\n\ntext_1\n\ntext_2= soup.select(\"h3#title-of-a-story.c-title.a-no-trucate.a-font-primary-bold-s\")[1].get_text(strip=True)\n\ntext_2\n\n#

\n#\n# \t\n# \t\n# \t\t\n# \t\t\t\t\tFlowers\t\t\n# \t\n#

\n\n# \n# \t\n# \tMiley Cyrus\n# \n\nname_1= soup.select(\"span.a-no-trucate.c-label\")[0].get_text(strip=True)\n\nname_1\n\n\n","repo_name":"nullsieben/Song_Recommender","sub_path":"hot_100.ipynb","file_name":"hot_100.ipynb","file_ext":"py","file_size_in_byte":1727,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"34"} +{"seq_id":"33681272857","text":"# + [markdown] id=\"kvxmuQMl9rhq\"\n# **Problem 2**\n\n# + id=\"U8Yn55bK9q_H\"\n# import the CSV file from GitHub:\nCSV_URL = 'https://raw.githubusercontent.com/oriyonay/RandomPublicThings/master/hw5_question2.csv'\ndf = pd.read_csv(CSV_URL, header=None)\n\n# + id=\"D9xRH4Ac_c8r\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"a44141dc-0635-4ab3-8aa2-a4513f551b43\"\n# does the data contain any missing values?\nprint('Missing values: %d' % df.isnull().sum().sum())\n\n# + [markdown] id=\"vcsNc2uT_pe1\"\n# No missing values in the data. Great!\n\n# + id=\"mMg7082c_enV\"\n# separate the features and labels:\nfeatures = df.loc[:, df.columns != 9]\noutcome = df[9]\n\n# + [markdown] id=\"lb3x0VA2AZdb\"\n# Since the data is entirely discrete, there is no need to further preprocess it.\n\n# + id=\"SMmI6NCHAJUi\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"db83f89b-acdd-460e-9684-3c74ec473511\"\n# 2a) Compute the number (and percentage) of samples belonging to the benign and malignant classes:\nprint('Number of benign (2) and malignant (4) samples:')\nprint(outcome.value_counts(normalize=False))\n\nprint('\\nPercentage of benign (2) and malignant (4) samples:')\nprint(outcome.value_counts(normalize=True) * 100)\n\n# + [markdown] id=\"wGqV1KUgBmPs\"\n# From the data above, we can observe that the malignant class is underrepresented in the dataset. \n\n# + id=\"ARpa7KlbA2ql\"\n# Split the data into train and test sets, ensuring both variables are proportionally represented\nX_train, X_test, y_train, y_test = train_test_split(features, outcome, test_size=0.33, stratify=outcome)\n\n\n# + [markdown] id=\"6hqKXFbYEw7L\"\n# It is important to note that since the training data is *disproportionately represented*, it is best to use a method such as AUROC to plot accuracy rather than a simple accuracy function.\n\n# + id=\"TVEu_7OsD_zT\"\n# 2b) Create and train two decision trees using the training samples:\n\n# defining a function that cross-validates two decision tree classifiers \n# (using entropy and gini index as splitting criterion):\ndef cross_validate_models(max_depth, num_of_folds=10):\n auc_dict = {'dtc_entropy': 0, 'dtc_gini': 0}\n\n skf = StratifiedKFold(n_splits=num_of_folds, shuffle=True)\n for train_index, test_index in skf.split(features, outcome):\n # Splitting the data:\n train_inputs = features.iloc[train_index]\n train_outputs = outcome[train_index]\n test_inputs = features.iloc[test_index]\n test_outputs = outcome[test_index]\n\n # Train the models on the data:\n dtc_entropy = DecisionTreeClassifier(criterion = 'entropy', max_depth=max_depth)\n dtc_gini = DecisionTreeClassifier(criterion = 'gini', max_depth=max_depth)\n dtc_entropy.fit(X_train, y_train)\n dtc_gini.fit(X_train, y_train)\n\n # use these models to predict values:\n dtc_entropy_pred = dtc_entropy.predict(test_inputs)\n dtc_gini_pred = dtc_gini.predict(test_inputs)\n\n # calculate ROC scores for these models:\n dtc_entropy_roc = roc_auc_score(test_outputs, dtc_entropy_pred)\n dtc_gini_roc = roc_auc_score(test_outputs, dtc_gini_pred)\n\n # add the contribution to the average AUROC score:\n auc_dict['dtc_entropy'] += dtc_entropy_roc / num_of_folds\n auc_dict['dtc_gini'] += dtc_gini_roc / num_of_folds\n\n # return the auc scores:\n return auc_dict\n\n\n# + id=\"Xb4r7CF-GTxQ\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 279} outputId=\"0fba71d6-7a5d-415e-817c-7a35c4995e77\"\n# plotting the 10-fold cross-validated accuracy on the training and testing data:\nnum_features = len(features.columns)\nmax_depths = list(range(1, num_features))\n\n# keep track of the ROC scores for both models:\ndtc_entropy_rocs = []\ndtc_gini_rocs = []\n\nfor depth in max_depths:\n # train the model with the given max depth:\n auc_dict_ = cross_validate_models(max_depth=depth)\n\n # store the ROC scores:\n dtc_entropy_rocs.append(auc_dict_['dtc_entropy'])\n dtc_gini_rocs.append(auc_dict_['dtc_gini'])\n\n# plot the accuracies as a function of max depth:\nplt.plot(max_depths, dtc_entropy_rocs, label='Decision Tree (Entropy) ROC')\nplt.plot(max_depths, dtc_gini_rocs, label='Decision Tree (Gini Index) ROC')\nplt.xlabel('Maximum tree depth')\nplt.ylabel('AUROC')\nplt.legend()\nplt.show()\n\n# + [markdown] id=\"OffTHbaGOfwW\"\n# By running this multiple times, I can discern no concrete difference between the two decision trees. The peak accuracy seems to be at a maximum tree depth of around 5-6, where neither trees seem to be underfitting nor overfitting to the data.\n\n# + id=\"tl4l2I1BMbbf\"\n# 2c) Feature importances using Random Forests:\nnum_of_folds = 10\n\n# to keep track of the AUROC of the random forest:\nrf_auc = 0\n\n# to keep track of the feature importances:\nfeature_importances = []\n\nskf = StratifiedKFold(n_splits=num_of_folds, shuffle=True)\nfor train_index, test_index in skf.split(features, outcome):\n # Splitting the data:\n train_inputs = features.iloc[train_index]\n train_outputs = outcome[train_index]\n test_inputs = features.iloc[test_index]\n test_outputs = outcome[test_index]\n\n # Train the random forest on the data:\n rf = RandomForestClassifier()\n rf.fit(X_train, y_train)\n\n # use the model to predict values:\n rf_pred = rf.predict(test_inputs)\n\n # store feature importances:\n feature_importances.append(rf.feature_importances_)\n\n # calculate ROC score for this model:\n rf_roc = roc_auc_score(test_outputs, rf_pred)\n\n # add the contribution to the average AUROC score:\n rf_auc += rf_roc / num_of_folds\n\n# + id=\"3p8ICnGwl9QK\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"68e52acf-e1fb-4ffd-ee96-ddea40eb47a5\"\n# print the AUROC score of the random forest classifier:\nprint('AUROC Score for Random Forest Classifier: %f' % rf_auc)\n\n# + [markdown] id=\"7b0wOq7QmLtZ\"\n# From this AUROC score, we can see that the random forest classifier tends to perform a bit better than the singular decision trees.\n\n# + id=\"8KFgoOCvb1Ck\"\n# sort importances from each fold, from most to least important:\nindices = [arr[::-1] for arr in np.argsort(feature_importances)]\n\n# calculate the avreage index location for each (average position in the rank order):\navg_indices = [0] * num_features # init array\nfor rank_arr in indices:\n for i in range(num_features):\n avg_indices[rank_arr[i]] += (i / len(indices))\n\n# use these average indices to calculate the average rank order by their average position in the rank order:\navg_rank_order = np.argsort(avg_indices)\n\n# + id=\"FJca7JVOd4up\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"2228044b-fcde-4a2f-ee60-6424999a4a76\"\nprint('Average rank order: ', avg_rank_order)\n\n# + id=\"GFQ-UqJxiF_A\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"611d70da-b405-4e70-f7a4-5ed9bde7b59a\"\n# for visualization purposes, prepare to plot the average feature importances (using the gini index):\navg_feature_importances = []\nfor rank in avg_rank_order:\n avg_feature_importance = np.mean([arr[rank] for arr in feature_importances])\n avg_feature_importances.append(avg_feature_importance)\n\navg_feature_importances\n\n# + [markdown] id=\"eWsry5Xii40y\"\n# As an interesting sidenote: this approach does not guarantee that the average feature importances will necessarily be sorted in decreasing order, since it cares about the *average relative rank of the feature importances* rather than the *ranks of the average feature importances*.\n#\n# That being said, this is not crucial, as the importances will likely remain mostly in order anyway, and will give us a more robust estimation of feature importances.\n\n# + id=\"5rKoS3RYibsQ\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 295} outputId=\"4233f8e8-8958-4d4d-ec04-53269718177a\"\n# plot the average feature importances (using the gini index):\nplt.bar(range(num_features), avg_feature_importances)\nplt.xticks(range(num_features), avg_rank_order)\nplt.title('Average Feature Importances (using Gini index)')\nplt.xlabel('Feature Index')\nplt.ylabel('Feature Importance (Gini)')\nplt.show()\n\n# + [markdown] id=\"ewbFqrOcmhig\"\n# In order to determine what should be included in the final list of features, let us first display the cumulative sum of the feature importances, in increasing order (similar to what we would do in determining when to cut off features for PCA).\n\n# + id=\"wLsNPJGdkGUO\" colab={\"base_uri\": \"https://localhost:8080/\"} outputId=\"a381c1c0-a695-4669-a6b3-37db4ad6cdaa\"\nprint('Cumulative sum of feature importances: ')\nprint(np.cumsum(avg_feature_importances))\n\n# + [markdown] id=\"wslip1YCm6-K\"\n# From this list, it is clear that in order to get a sufficiently high accuracy rate, almost all features need to be considered. I would suggest that the last feature (index 8, corresponding to *normal nucleoli*) is not necessary in the final model. It does not seem to provide much of an added benefit to the model and may very well lead to overfitting/modeling of random noise. The model contains a small enough set of features that it would still be okay to keep this feature, though it is probably not too important.\n","repo_name":"oriyonay/CSCE421","sub_path":"CSCE_421_Homework_5.ipynb","file_name":"CSCE_421_Homework_5.ipynb","file_ext":"py","file_size_in_byte":8926,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"34"} +{"seq_id":"8234978453","text":"# # Overview\n#\n# Get image index and process them to a data structure for torch\n\n# ## Libraries and Data Import\n\n# +\nimport os\nimport pandas as pd\nfrom PIL import Image\nimport torchvision as tv\nimport torchvision.transforms.functional as TF\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# %matplotlib inline\n# -\n\nindex_df = pd.read_csv(\"../../data/image_index.csv\", index_col=0)\nindex_df.head()\n\n\n# ## Check for image size distribution\n#\n# This will determine the cropping and sizing process\n\ndef img_to_tensor_shape(path):\n return list(tv.io.read_image(path).shape)\n\n\nindex_df[\"image_tensor\"] = index_df.img.apply(img_to_tensor_shape)\n\nindex_df[\"channels\"] = index_df.image_tensor.apply(lambda x: x[0])\nindex_df[\"height\"] = index_df.image_tensor.apply(lambda x: x[1])\nindex_df[\"width\"] = index_df.image_tensor.apply(lambda x: x[2])\n\n\ndef name_data_set(num):\n if num == 0:\n return \"test\"\n elif num == 1:\n return \"train\"\n else:\n return \"validation\"\n\n\nindex_df[\"data_set_name\"] = index_df.data_set.apply(name_data_set)\n\nindex_df.head()\n\nindex_df.groupby([\"data_set\", \"channels\"])[[\"height\", \"width\"]].describe()\n\n# - Test(data_set == 0) only contains greyscale images\n# - Min Height: 344\n# - Max Height: 688\n# - Train(data_set == 1) contains color and greyscale images\n# - Validate(data_set == 2) only contains greyscale images\n\nindex_df.groupby(\"data_set_name\")[[\"height\", \"width\"]].mean()\n\nsns.jointplot(data=index_df, x=\"width\", y=\"height\", hue=\"data_set_name\", kind=\"hist\")\nplt.suptitle(\"Image Size Distribution in Data Sets\", size=14, y=0.98)\nplt.tight_layout()\nplt.savefig(\"../../images/image_pix_dist.png\")\nplt.show()\n","repo_name":"danvalen1/Pneumonia-ID","sub_path":"notebooks/YHJ/image_data_eda.ipynb","file_name":"image_data_eda.ipynb","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"34"} +{"seq_id":"23530014390","text":"# !pip install openpyxl\n\n# +\nimport os\nimport pandas as pd\nimport numpy as np\nfrom numpy import mean, std, absolute\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor\nimport scipy as sp\nfrom sklearn.model_selection import KFold\nfrom sklearn.metrics import mean_squared_error as mse\nfrom sklearn.metrics import r2_score as r2\nfrom sklearn.preprocessing import normalize\nimport shap\n\n\nplt.style.use('ggplot')\nshap.initjs()\n# -\n\n# ## Load Data\n\n# +\ndata = pd.read_excel('Data/Gasification Data.xlsx', index_col=0, header=0)\ndata = data.iloc[1:223,:14] \ndisplay(list(data.columns.values))\n\n# Drop null balues and store dataframe in dataframe 2\ndata=data.dropna()\nprint(data)\n\n#Check Null values again after removing\nprint(data.isnull().values.any())\nprint(data.isna().values.any())\n\nX = data.iloc[:, :9]\ny = data.iloc[:, 9:]\n\ninput_columns = list(X.columns.values)\ninput_columns = [i.split(' [', 1)[0] for i in input_columns]\noutput_columns = list(y.columns.values)\noutput_columns = [i.split(' [', 1)[0] for i in output_columns]\nprint(input_columns, output_columns)\n\nXvals = X.values\nyvals = y.values\nprint(Xvals.shape, yvals.shape)\n\nXnorm = np.zeros_like(Xvals)\nynorm = np.zeros_like(yvals)\nfor idx in range(len(input_columns)):\n Xnorm[:, idx] = (Xvals[:,idx]-min(Xvals[:,idx]))/(max(Xvals[:,idx])-min(Xvals[:,idx]))\nfor odx in range(len(output_columns)):\n ynorm[:, odx] = (yvals[:,odx]-min(yvals[:,odx]))/(max(yvals[:,odx])-min(yvals[:,odx]))\n\nprint(np.max(Xnorm), np.max(ynorm))\nprint(np.min(Xnorm), np.min(ynorm))\n# -\n\nprint(Xnorm)\n\n# ## Classify the data using ensemble regressor\n\n# +\nseed = 42\nX_train, X_test, y_train, y_test = train_test_split(Xnorm, ynorm, test_size=.3, random_state=seed)\n\n# For Gradient Boost\nprediction = np.zeros_like(y_test)\ngbm = {}\nfor idx in range(y.shape[1]):\n gbm[idx] = GradientBoostingRegressor(n_estimators=1000, learning_rate=.1, random_state=seed, loss='huber')\n gbm[idx].fit(X_train, y_train[:, idx])\n prediction[:, idx]=gbm[idx].predict(X_test)\nerror = np.sqrt(mse(y_test, prediction, multioutput='raw_values'))\nr2value = r2(y_test, prediction, multioutput='raw_values')\nprint(error, r2value)\n# -\n\n# ## Plot Results\n\n# ### 1. Correlation analysis between the input features and continuous outputs \n\nresult_folder = 'Results/'\nif not os.path.exists(result_folder):\n os.mkdir(result_folder)\n\n## Correlation analysis for best feature\nplt.figure(figsize=(50, 50))\nrow = len(input_columns)\ncolumn = len(output_columns)\nfor idx, inp in enumerate(input_columns):\n for odx, out in enumerate(output_columns):\n plt.subplot(row, column, 5*idx+odx+1)\n plt.scatter(Xnorm[:, idx], ynorm[:, odx], s=50, color='black')\n slope, intercept, r, p, stderr = sp.stats.linregress(Xnorm[:, idx].astype(float), \n ynorm[:, odx].astype(float))\n line = f'y={intercept:.2f}+{slope:.2f}x, r={r:.2f}'\n plt.plot(Xnorm[:, idx], intercept + slope * Xnorm[:, idx], label=line, color='red')\n plt.xlabel(\"Input Feature: \\n%s\" % inp, fontsize=16)\n plt.ylabel(\"Output Feature: \\n%s\" % out, fontsize=16)\n plt.legend(loc='upper left')\nplt.savefig(result_folder + 'Correlation_analysis.pdf')\nplt.clf()\n\n# ### 2. True vs Estimated plots for each test samples\n\n# +\nplt.figure(figsize=(15, 30))\nfor odx, out in enumerate(output_columns):\n plt.subplot(5, 1, odx +1)\n plt.plot(np.asarray(y_test)[:, odx], label='True value', color='blue')\n plt.plot(np.asarray(prediction)[:, odx], color='red', \n label='Predicted value \\n (RMSE = %.4f, R2=%.3f)' % (error[odx], (r2value[odx])))\n plt.xlabel(\"Features\", fontsize=16)\n plt.ylabel(\"Values\", fontsize=16)\n plt.rc('xtick',labelsize=14)\n plt.rc('ytick',labelsize=14)\n plt.title(\"Output: %s\" % out, fontsize=16)\n plt.legend(fontsize=16)\n\nplt.savefig(result_folder + 'MIMO_Prediction.pdf')\n# plt.show()\n# -\n\n# ### 2. Plot the true and estimated output\n\n## Correlation analysis between true and predicted values\nplt.figure(figsize=(18, 5)) # \ncolumn = len(output_columns)\nfor odx, out in enumerate(output_columns):\n plt.subplot(1, column, odx+1)\n plt.scatter(y_test[:, odx], prediction[:, odx], s=50, color='blue')\n \n slope, intercept, r, p, stderr = sp.stats.linregress(y_test[:, odx].astype(float), \n prediction[:, odx].astype(float)) \n plt.plot(y_test[:, odx], intercept + slope * y_test[:, odx], color='red')\n plt.title(\"%s: $R^2$-value=%.2f\" % (out, r**2))\n plt.xlim(0, 1)\n plt.ylim(0, 1)\n plt.xlabel(\"True Value\", fontsize=16)\n plt.ylabel(\"Predicted Value\", fontsize=16)\nplt.savefig(result_folder + 'R2_true_vs_predicted.pdf')\nplt.clf()\n\n# ## Global Interpretability\n\nfor idx in range(y.shape[1]):\n shap_values = shap.TreeExplainer(gbm[idx]).shap_values(X_train)\n shap.summary_plot(shap_values, X_train, plot_type=\"bar\")\n\n# ### 1. Summary plot\n\ncolumn = len(output_columns)\nplt.figure(figsize=(8,10))\nfor odx, out in enumerate(output_columns):\n shap_values = shap.TreeExplainer(gbm[odx]).shap_values(X_test)\n shap.summary_plot(shap_values, X_test, feature_names=input_columns, show=True)\n plt.title(\"%s\" % out)\n plt.xlim(-0.25, 0.25)\n plt.tight_layout()\n plt.savefig(result_folder + 'global_interpretation_summary_plot_%s.pdf' % out)\n plt.clf()\n\n# ### 2. Dependence Plot\n\ncolumn = len(output_columns)\nplt.figure(figsize=(8,5))\nfor odx, out in enumerate(output_columns):\n shap_values = shap.TreeExplainer(gbm[idx]).shap_values(X_test)\n shap.dependence_plot(odx, shap_values, X_test, feature_names=input_columns, show=False)\n plt.title(\"%s\" % out)\n# plt.xlim(-0.25, 0.25)\n plt.tight_layout()\n plt.savefig(result_folder + 'global_interpretation_dependence_plot_%s.pdf' % out)\n plt.clf()\n\n# ## Individual SHAP Value Plot -- Local Interpretability\n\n# +\nlocal_copy = X_test.copy()\nlocal_output = np.round(gbm[1].predict(local_copy), 2)\n\nrandom_picks = np.arange(1, 57, 10)\nlocal_inputs = local_copy[random_picks]\nS = local_output[random_picks]\nprint(len(local_inputs), len(S))\n\n\n# -\n\ndef shap_plot(index, j):\n explainerModel = shap.TreeExplainer(gbm[index])\n shap_values_Model = explainerModel.shap_values(local_inputs)\n p = shap.force_plot(explainerModel.expected_value, shap_values_Model[j], local_inputs[j], feature_names=input_columns,\n matplotlib=True, show=False)\n return p\n\n\nplt.figure()\ninstance=[0, 2, 4, 5]\nfor j in instance:\n for odx, out in enumerate(output_columns):\n shap_plot(odx, j)\n plt.savefig(result_folder + 'local_interpretation_dependence_plot_%s_instance_%d.pdf' % (out, j))\n\n# ## Decision Plots\n\ncolumn = len(output_columns)\n# plt.figure(figsize=(5,5))\nfor odx, out in enumerate(output_columns):\n explainer = shap.TreeExplainer(gbm[idx])\n expected_value = explainer.expected_value\n shap_values = explainer.shap_values(X_test)\n shap.decision_plot(expected_value, shap_values, feature_names=input_columns, show=False)\n plt.title(\"%s\" % out)\n# plt.xlim(-0.25, 0.25)\n plt.tight_layout()\n plt.savefig(result_folder + 'global_interpretation_decision_plot_%s.pdf' % out)\n plt.clf()\n","repo_name":"sagihaider/XAI-Gasification-Modelling","sub_path":"Gasification_model_XAI.ipynb","file_name":"Gasification_model_XAI.ipynb","file_ext":"py","file_size_in_byte":7361,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"34"} +{"seq_id":"1152568820","text":"# +\nimport pandas as pd\nimport requests\nimport json\n\n\nclass BMEApiHandler:\n\n def __init__(self):\n self.url_base = 'https://miax-gateway-jog4ew3z3q-ew.a.run.app'\n self.competi = 'mia_11'\n self.user_key = ''\n\n def get_ticker_master(self):\n url = f'{self.url_base}/data/ticker_master'\n params = {'competi': self.competi,\n 'market': 'IBEX',\n 'key': self.user_key}\n response = requests.get(url, params)\n tk_master = response.json()\n maestro_df = pd.DataFrame(tk_master['master'])\n return maestro_df\n\n def get_close_data(self, tck) -> pd.Series:\n url = f'{self.url_base}/data/time_series'\n params = {\n 'market': 'IBEX',\n 'key': self.user_key,\n 'ticker': tck\n }\n response = requests.get(url, params)\n tk_data = response.json()\n series_data = pd.read_json(tk_data, typ='series')\n return series_data\n\n def send_alloc(self, algo_tag, str_date, allocation):\n url = f'{self.url_base}/participants/allocation'\n url_auth = f'{url}?key={self.user_key}'\n print(url_auth)\n params = {\n 'competi': self.competi,\n 'algo_tag': algo_tag,\n 'market': 'IBEX',\n 'date': str_date,\n 'allocation': allocation\n }\n #print(json.dumps(params))\n response = requests.post(url_auth, data=json.dumps(params))\n print(response.json())\n\n def get_algos(self):\n url = f'{self.url_base}/participants/algorithms'\n params = {'competi': self.competi,\n 'key': self.user_key}\n response = requests.get(url, params)\n algos = response.json()\n if algos:\n algos_df = pd.DataFrame(algos)\n return algos_df\n\n def allocs_to_frame(self, json_allocations):\n alloc_list = []\n for json_alloc in json_allocations:\n #print(json_alloc)\n allocs = pd.DataFrame(json_alloc['allocations'])\n allocs.set_index('ticker', inplace=True)\n alloc_serie = allocs['alloc']\n alloc_serie.name = json_alloc['date'] \n alloc_list.append(alloc_serie)\n all_alloc_df = pd.concat(alloc_list, axis=1).T\n return all_alloc_df\n\n def get_allocations(self, algo_tag):\n url = f'{self.url_base}/participants/algo_allocations'\n params = {\n 'key': self.user_key,\n 'competi': self.competi,\n 'algo_tag': algo_tag,\n 'market': 'IBEX',\n }\n response = requests.get(url, params)\n df_allocs = self.allocs_to_frame(response.json())\n return df_allocs\n\n\n def delete_allocs(self, algo_tag):\n url = f'{self.url_base}/participants/delete_allocations'\n url_auth = f'{url}?key={self.user_key}'\n params = {\n 'competi': self.competi,\n 'algo_tag': algo_tag,\n 'market': 'IBEX',\n }\n response = requests.post(url_auth, data=json.dumps(params))\n print(response.text)\n\n\n def backtest_algo(self, algo_tag):\n url = f'{self.url_base}/participants/exec_algo'\n url_auth = f'{url}?key={self.user_key}'\n params = {\n 'competi': self.competi,\n 'algo_tag': algo_tag,\n 'market': 'IBEX',\n }\n response = requests.post(url_auth, data=json.dumps(params))\n if response.status_code == 200:\n exec_data = response.json()\n status = exec_data.get('status')\n res_data = exec_data.get('content')\n if res_data:\n performace = pd.Series(res_data['result'])\n trades = pd.DataFrame(res_data['trades'])\n return performace, trades\n else:\n exec_data = dict()\n print(response.text)\n\n def algo_exec_results(self, algo_tag):\n url = f'{self.url_base}/participants/algo_exec_results'\n params = {\n 'key': user_key,\n 'competi': competi,\n 'algo_tag': algo_tag,\n 'market': market,\n } \n response = requests.get(url, params)\n exec_data = response.json()\n print(exec_data.get('status'))\n res_data = exec_data.get('content')\n if res_data:\n performace = pd.Series(res_data['result'])\n trades = pd.DataFrame(res_data['trades'])\n return performace, trades\n\n \n# -\n\napi_handler = BMEApiHandler()\n\n# +\nfrom datetime import datetime\n\nclass EqWeightedAlgo:\n def __init__(self, algo_tag, rbal_days):\n self.algo_tag = algo_tag\n self.rbal_days = rbal_days\n self.api_handler = BMEApiHandler()\n self.df_close = None\n\n def get_data(self):\n # Descarga de todos los datos de cierre\n data_close_dict = {}\n ticker_master = api_handler.get_ticker_master()\n for idx, row in ticker_master.iterrows():\n tck = row.ticker\n print(tck)\n close_data = api_handler.get_close_data(tck)\n data_close_dict[tck] = close_data\n self.df_close = pd.DataFrame(data_close_dict)\n\n def run_simulation(self): \n # inserccion de las allocations\n for fecha, data in self.df_close[::self.rbal_days].iterrows():\n print(fecha)\n in_index = data.dropna().index\n alloc = 1 / len(in_index)\n allocation = [\n {'ticker': ticker, 'alloc': alloc}\n for ticker in in_index\n ]\n str_date = fecha.strftime('%Y-%m-%d')\n self.api_handler.send_alloc(\n algo_tag=self.algo_tag,\n str_date=str_date, \n allocation=allocation)\n performace, trades = self.api_handler.backtest_algo(self.algo_tag)\n self.api_handler.delete_allocs(algo_tag)\n return performace, trades\n\n def run_day(self):\n maestro = self.api_handler.get_ticker_master()\n tck_today = maestro[maestro.end_date == ''].ticker\n alloc = 1/tck_today.shape[0]\n allocations_to_sent = [\n {'ticker': tck, 'alloc': alloc}\n for tck in tck_today\n ]\n today = datetime.now()\n date = today.strftime('%Y-%m-%d')\n self.api_handler.send_alloc(self.algo_tag, date, allocations_to_sent)\n# -\n\n\n\nalgo = EqWeightedAlgo(algo_tag='test_user_1_miax11_algo1', rbal_days=200)\n\nalgo.get_data()\n\nperformace, trades = algo.run_simulation()\n\n\nperformace \n\n\n","repo_name":"fernandodelacalle/miax-product","sub_path":"API_Practica/ejercicios/ejercicio_algos_sol.ipynb","file_name":"ejercicio_algos_sol.ipynb","file_ext":"py","file_size_in_byte":6527,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"34"} +{"seq_id":"13475106434","text":"from bs4 import BeautifulSoup\nimport requests\nimport time\nimport glob\nimport re\nimport pandas as pd\n\n# # scraping NDAR for likely data sharing targets\n# In this notebook, we go through the 'collections' and 'studies' on NDAR and download any non-blank html pages. We then go through those pages and pull out any DOIs listed on those pages.\n\nmissing_ids = []\nprint_statuses = list(range(4200, 5000, 100))\nfor i in range(4203, 5000):\n if i in print_statuses:\n print(i)\n root_link = 'https://nda.nih.gov/edit_collection.html?id='\n lnk = root_link + str(i)\n r = requests.get(lnk)\n if len(r.history)==0:\n with open('output/ndar_collections/collection_'+str(i)+'.html', 'wb') as f:\n f.write(r.content)\n else:\n missing_ids.append(i)\n time.sleep(.25)\n\nmissing_ids = []\nprint_statuses = list(range(200, 800, 50))\nfor i in range(200, 800):\n if i in print_statuses:\n print(i)\n root_link = 'https://nda.nih.gov/study.html?id='\n lnk = root_link + str(i)\n r = requests.get(lnk)\n if len(r.history)==0:\n with open('output/ndar_studies/study_'+str(i)+'.html', 'wb') as f:\n f.write(r.content)\n else:\n missing_ids.append(i)\n time.sleep(.2)\n\nstudy_id = []\ndoi = []\nstudies = glob.glob('output/ndar_studies/*')\nfor study in studies:\n soup = BeautifulSoup(open(study), 'html.parser')\n study_id.append(re.findall('study_([0-9]+)', study))\n try:\n doi.append(soup.find_all('a', href=re.compile('dx.doi.org'))[0]['href'])\n except:\n doi.append('none')\n\nstudy_info = pd.DataFrame({'doi':doi, 'study_id':[s[0] for s in study_id]})\nstudy_info.head()\nstudy_info = study_info[study_info.doi!='none']\nstudy_info['doi2'] = study_info.doi.apply(lambda x: x[18:])\nuser_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'\nheaders = {'User-Agent': user_agent}\nresponse_list = []\nfor number, i in enumerate(study_info.doi2.tolist()):\n root_link = 'http://api.crossref.org/works/'\n lnk = root_link + str(i)\n r = requests.get(lnk,headers=headers)\n response_list.append(r)\n print(number)\n\nfor i in response_list:\n if i.text != 'Resource not found.':\n print(i.text)\n\ndf_pmcid = pd.read_csv('data/PMC-ids.csv')\n\nstudy_info.head()\n\n\n\n# +\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"riddlet/data_share_reuse","sub_path":"5_scrape_ndar.ipynb","file_name":"5_scrape_ndar.ipynb","file_ext":"py","file_size_in_byte":2339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"34"} +{"seq_id":"38589621625","text":"# https://www.acmicpc.net/problem/16287\n\n# +\n# parcel\n\nimport sys\n\nw, n = map(int, input().split())\nseq = list(map(int, input().split()))\n\ndp = [0] * (w+1)\n\nfor i in range(n):\n for j in range(i+1, n):\n if seq[i] + seq[j] > w:\n continue\n \n if dp[w - seq[i] - seq[j]]:\n print('YES')\n sys.exit()\n \n for j in range(i): \n if seq[i] + seq[j] < w:\n dp[seq[i] + seq[j]] = 1\n \nprint('NO')\n# -\n\n# https://www.acmicpc.net/problem/18186\n\n# +\n# 라면 사기(Large)\n# 첫 도전 실패\n\nn, b, c = map(int, input().split())\nseq = list(map(int, input().split()))\n\nif b <= c:\n print(sum(seq) * b)\n \nelse:\n answer = 0\n \n for i in range(n):\n if seq[i] > 0:\n count = 0\n j = 1\n while j < 3 and i + j < n:\n if seq[i] > seq[i + j]:\n break\n \n count += 1\n j += 1\n \n for k in range(1, count+1): \n seq[i + k] -= seq[i]\n \n answer += seq[i] * (b + count * c)\n \n seq[i] = 0\n \n print(answer)\n \n\n# +\nn, b, c = map(int, input().split())\nseq = list(map(int, input().split())) + [0] * 5\n\nif b <= c:\n print(sum(seq) * b)\n \nelse:\n answer = 0\n \n for i in range(n):\n if seq[i+1] > seq[i+2]:\n value = min(seq[i], seq[i+1] - seq[i+2])\n \n seq[i] -= value\n seq[i+1] -= value\n answer += value * (b + c)\n \n value = min(seq[i], seq[i+1], seq[i+2])\n \n seq[i] -= value\n seq[i+1] -= value\n seq[i+2] -= value\n answer += value * (b + 2 * c)\n \n else:\n value = min(seq[i], seq[i+1], seq[i+2])\n \n seq[i] -= value\n seq[i+1] -= value\n seq[i+2] -= value\n answer += value * (b + 2 * c)\n \n value = min(seq[i], seq[i+1])\n \n seq[i] -= value\n seq[i+1] -= value\n answer += value * (b + c)\n \n answer += b * seq[i]\n seq[i] = 0\n \n print(answer)\n \n# -\n\n# https://www.acmicpc.net/problem/18185\n\n# +\n# 라면 사기 (Small)\n\nn = int(input())\nseq = list(map(int, input().split())) + [0] * 2\n\n\nanswer = 0\nb = 3\nc = 2\n \nfor i in range(n):\n if seq[i+1] > seq[i+2]:\n value = min(seq[i], seq[i+1] - seq[i+2])\n \n seq[i] -= value\n seq[i+1] -= value\n answer += value * (b + c)\n \n value = min(seq[i], seq[i+1], seq[i+2])\n \n seq[i] -= value\n seq[i+1] -= value\n seq[i+2] -= value\n answer += value * (b + 2 * c)\n \n else:\n value = min(seq[i], seq[i+1], seq[i+2])\n \n seq[i] -= value\n seq[i+1] -= value\n seq[i+2] -= value\n answer += value * (b + 2 * c)\n \n value = min(seq[i], seq[i+1])\n \n seq[i] -= value\n seq[i+1] -= value\n answer += value * (b + c)\n \n answer += b * seq[i]\n seq[i] = 0\n \nprint(answer)\n# -\n\n# https://www.acmicpc.net/problem/5545\n\n# +\n# 최고의 피자\n\nn = int(input())\na, b = map(int, input().split())\nc = int(input())\nd = []\n\nfor i in range(n):\n d.append(int(input()))\n \nd.sort(reverse = True)\nanswer = c / a\n\nfor i in range(1, n+1):\n value = c + sum(d[:i])\n price = a + b * i\n \n if answer < value / price:\n answer = value / price\n \n else:\n break\n \nprint(int(answer))\n# -\n\n# https://www.acmicpc.net/problem/1379\n\n# +\n# 강의실 2\n\nimport heapq\n\n\nn = int(input())\n\nlst = []\nfor i in range(n):\n num, s, e = map(int, input().split())\n lst.append((s, e, num))\n \nlst.sort()\n\nheap = []\nheapq.heappush(heap, (lst[0][1], 1)) # 두 번째 요소에 강의실 번호 저장\n\nnum = [0] * n\nnum[lst[0][2]-1] = 1\n\nfor i in range(1, n):\n if heap[0][0] > lst[i][0]:\n heapq.heappush(heap, (lst[i][1], len(heap) + 1))\n num[lst[i][2]-1] = len(heap)\n \n else:\n num[lst[i][2]-1] = heap[0][1]\n heapq.heappop(heap)\n heapq.heappush(heap, (lst[i][1], num[lst[i][2]-1]))\n \n \nprint(len(heap))\nfor i in num:\n print(i)\n# -\n\n# https://www.acmicpc.net/contest/problem/755/2\n\n# +\n# 2번 - 가희와 탑\n\nn, a, b = map(int, input().split())\n\ndef sol(n, a, b):\n if a + b > n + 1:\n return [-1]\n \n if a > b:\n lstb = list(range(b-1, 0, -1))\n lsta = [1] * (n - (b-1) - a) + list(range(1, a+1))\n \n else:\n if a == 1:\n lsta = [b]\n lstb = [1] * (n - (b-1) - 1) + list(range(b-1, 0, -1))\n \n else:\n lstb = list(range(b, 0, -1))\n lsta = [1] * (n - b - (a-1)) + list(range(1, a))\n \n lst = lsta + lstb\n return lst\n \n \nprint(*sol(n, a, b))\n \n# -\n\n# https://www.acmicpc.net/problem/23974\n\n# +\n# 짝수 게임\n\nn, k = map(int, input().split())\n\nif not n % 2:\n if k % 6 == 1:\n print('HS')\n else:\n print('YG')\n \nelse:\n if k % 6 == 5 or not k % 6:\n print('HS')\n else:\n print('YG')\n\n# -\n\n# https://www.acmicpc.net/problem/1946\n\n# +\n# 신입 사원\n\n\nt = int(input())\nfor _ in range(t):\n n = int(input())\n \n lst = []\n for i in range(n):\n a, b = map(int, input().split())\n lst.append((a, b))\n \n \n lst.sort(key = lambda x : (x[0], x[1]))\n \n idx = lst[0][1]\n count = n\n \n for i in range(1, n):\n if lst[i][1] > idx:\n count -= 1\n \n elif lst[i][1] < idx:\n idx = lst[i][1]\n \n \n print(count)\n \n\n# +\nn = int(input())\nli = list(map(int, input().split()))\n\nif n == 1:\n if li[0] == 0:\n li[0] = 1\n print(*li)\nelse:\n ip = True\n for i in range(n - 1):\n if li[i] != 0 and li[i] == li[i + 1]:\n ip = False\n break\n\n if not ip:\n print(-1)\n else:\n st = set(range(1, 4))\n\n if li[0] == 0:\n if li[1] == 1:\n li[0] = 2\n else:\n li[0] = 1\n\n for i in range(n - 1):\n if li[i]:\n continue\n\n else:\n cand = st - {li[i - 1], li[i + 1]}\n li[i] = cand.pop()\n\n if li[n - 1] == 0:\n if li[n - 2] == 1:\n li[n - 1] = 2\n else:\n li[n - 1] = 1\n \n print(*li)\n\n# +\nimport sys\n\nn = int(input())\nlst = list(map(int, input().split()))\n\nif n == 1:\n if lst[0] == 0:\n lst[0] = 1\n \n print(*lst)\n sys.exit()\n \n\ncheck = 1\nfor i in range(n - 1):\n if lst[i] and lst[i] == lst[i + 1]:\n check = 0\n break\n\nif not check:\n print(-1)\n sys.exit()\n \n\nif lst[0] == 0:\n if lst[1] == 1:\n lst[0] = 2\n else:\n lst[0] = 1\n \npsb = set(range(1, 4))\n \nfor i in range(n - 1):\n if lst[i]:\n continue\n\n else:\n box = psb - {lst[i - 1], lst[i + 1]}\n lst[i] = box.pop()\n\nif not lst[n - 1]:\n if lst[n - 2] == 1:\n lst[n - 1] = 2\n \n else:\n lst[n - 1] = 1\n \n \nprint(*lst) \n\n# -\n\n# https://www.acmicpc.net/problem/1343\n\n# +\ns = input()\n\ndef sol():\n temp = s.split('.')\n \n #print(temp)\n \n for i in range(len(temp)):\n if temp[i] == '':\n continue\n \n len_ = len(temp[i])\n \n if len_ % 2:\n return -1\n \n if len_ == 2:\n temp[i] = 'BB'\n \n elif not len_ % 4:\n temp[i] = 'A' * len_\n \n elif len_ % 4 and not len_ % 2:\n temp[i] = 'A' * (len_-2) + 'BB'\n \n #print(temp)\n return '.'.join(temp)\n \n\nprint(sol())\n \n# -\n\n# https://www.acmicpc.net/problem/2285\n\n# +\n##### 우체국\n\nn = int(input())\n\nlst = []\nhab = 0\nfor i in range(n):\n x, a = map(int, input().split())\n lst.append((x, a))\n hab += a\n \n\nlst.sort()\n\ncount = 0\nfor i, j in lst:\n count += j\n \n if count >= hab / 2:\n print(i)\n break\n \n# -\n\n# https://www.acmicpc.net/problem/4796\n\n# +\n# 캠핑\n\ncount = 1\nwhile True:\n l, p, v = map(int, input().split())\n \n if not l and not p and not v:\n break\n \n answer = (v // p) * l\n answer += min(v % p, l)\n print(f\"Case {count}: {answer}\")\n count += 1\n \n# -\n\n# https://www.acmicpc.net/problem/15922\n\n# +\n# 아우으 우아으이야!!\n\nn = int(input())\n\ncrd = []\nfor i in range(n):\n x, y = map(int, input().split())\n crd.append((x, y))\n \nstart = crd[0][0]\nend = crd[0][1]\nhab = 0\n\nfor i, j in crd:\n if end < i:\n hab += temp\n temp = 0\n start = i\n end = j\n \n else:\n if end < j:\n end = j\n \n temp = end - start\n \n\nprint(hab if not temp else hab + temp)\n\n# -\n\n# https://www.acmicpc.net/problem/1417\n\n# +\nimport heapq\nimport sys\n\nn = int(input())\nlst = [-int(input()) for _ in range(n)]\n\nif n == 1:\n print(1)\n sys.exit()\n\nstd = lst[0]\ntarget = lst[1:]\n\nheapq.heapify(target)\ncount = 0\nwhile True:\n x = heapq.heappop(target)\n \n if std < x:\n break\n \n std += -1\n heapq.heappush(target, x+1)\n count += 1\n \nprint(count)\n \n# -\n\n# https://www.acmicpc.net/problem/13560\n\n# +\n# 축구 게임\n\nimport sys\n\nn = int(input())\nlst = list(map(int, input().split()))\n\nlst.sort()\n\nbar = 0\nhab = 0\nfor i in range(n):\n hab += lst[i]\n bar = i * (i+1) / 2\n \n if hab < bar:\n print(-1)\n sys.exit()\n \nprint(-1 if hab != n * (n-1) / 2 else 1)\n\n# -\n\n# https://www.acmicpc.net/problem/1201\n\n# +\n# NMK\n\nn, m, k = map(int, input().split())\n\n\nif n < m + k - 1 or m * k < n:\n print(-1)\n \nelse:\n lst = list(range(k, 0, -1))\n \n n -= k\n m -= 1\n \n while m:\n temp = list(range(k+n // m, k, -1))\n lst.extend(temp)\n \n k += n // m\n n -= n // m\n m -= 1\n \n print(*lst)\n \n\n# +\nn, m, k = map(int, input().split())\n\n\nif n < m + k - 1 or m * k < n:\n print(-1)\n \nelse:\n lst = list(range(k, 0, -1))\n \n n -= k\n m -= 1\n \n for i in range(m-1, -1, -1):\n temp = list(range(k+n // m, k, -1))\n lst.extend(temp)\n \n k += n // m\n n -= n // m\n \n print(*lst)\n \n# -\n\n# https://www.acmicpc.net/problem/2873\n\n# +\n# 롤러코스터\n\n\n# -\n\n# https://www.acmicpc.net/problem/13137\n\n# +\n# Exchange Problem\n\nn = int(input())\ncoin = list(map(int, input().split()))\n\n\ndef check(x):\n value = 0\n \n for i in range(n-1, -1, -1):\n if coin[i] <= x:\n value += x // coin[i]\n x -= x // coin[i] * coin[i]\n \n return value\n \n\ndef sol():\n if coin[0] != 1:\n return \"No\"\n \n end = coin[-1]\n dp = [int(1e9)] * 3 * end\n dp[0] = 0\n \n for i in range(n):\n for j in range(2 * end):\n #print(i, j)\n if coin[i] <= j and dp[j-coin[i]] + 1 < dp[j]:\n dp[j] = dp[j-coin[i]] + 1\n \n for i in range(2 * end):\n if dp[i] < check(i):\n return \"No\"\n \n return \"Yes\"\n \n \nprint(sol())\n\n# -\n\n# https://www.acmicpc.net/problem/22748\n\n# +\n# Greedy, Greedy.\n\n\ndef check(x):\n value = 0\n \n for i in range(n-1, -1, -1):\n if coin[i] <= x:\n value += x // coin[i]\n x -= x // coin[i] * coin[i]\n \n return value\n \n\ndef sol():\n if coin[0] != 1:\n return \"Cannot pay some amount\"\n \n end = coin[-1]\n dp = [int(1e9)] * 3 * end\n dp[0] = 0\n \n for i in range(n):\n for j in range(2 * end):\n #print(i, j)\n if coin[i] <= j and dp[j-coin[i]] + 1 < dp[j]:\n dp[j] = dp[j-coin[i]] + 1\n \n for i in range(2 * end):\n if dp[i] < check(i):\n return \"Cannot use greedy algorithm\"\n \n return \"OK\"\n \n \ncount = 1\nwhile True:\n temp = list(map(int, input().split()))\n\n n = temp[0]\n if not n:\n break\n coin = temp[1:]\n \n print(f\"Case #{count}: {sol()}\")\n count += 1\n\n\n# -\n\n# https://www.acmicpc.net/problem/15423\n\n# +\n# Canonical Coin Systems\n\n\nn = int(input())\ncoin = list(map(int, input().split()))\n\n\ndef check(x):\n value = 0\n \n for i in range(n-1, -1, -1):\n if coin[i] <= x:\n value += x // coin[i]\n x -= x // coin[i] * coin[i]\n \n return value\n \n\ndef sol():\n if coin[0] != 1:\n return \"non-canonical\"\n \n end = coin[-1]\n dp = [int(1e9)] * 3 * end\n dp[0] = 0\n \n for i in range(n):\n for j in range(2 * end):\n #print(i, j)\n if coin[i] <= j and dp[j-coin[i]] + 1 < dp[j]:\n dp[j] = dp[j-coin[i]] + 1\n \n for i in range(2 * end):\n if dp[i] < check(i):\n return \"non-canonical\"\n \n return \"canonical\"\n \n \nprint(sol())\n\n# -\n\n\n","repo_name":"NHRWV/CT_workbook","sub_path":".ipynb_checkpoints/그리디 2-checkpoint.ipynb","file_name":"그리디 2-checkpoint.ipynb","file_ext":"py","file_size_in_byte":13248,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-jupyter-script","pt":"34"} +{"seq_id":"24634084581","text":"import pandas as pd\nimport numpy as np\nimport xgboost as xgb\n\ntrn = pd.read_csv('./data/train_ver2.csv')\ntst = pd.read_csv('./data/test_ver2.csv')\n\nprods = trn.columns[24:].tolist()\n\ntrn[prods] = trn[prods].fillna(0.0).astype(np.int8)\n\nno_product = trn[prods].sum(axis=1) == 0\ntrn = trn[~no_product]\n\nfor col in trn.columns[24:]:\n tst[col] = 0\ndf = pd.concat([trn, tst], axis=0)\n\nfeatures = []\n\ncategorical_cols = ['ind_empleado', 'pais_residencia', 'sexo', 'tiprel_1mes', 'indresi', 'indext', 'conyuemp', 'canal_entrada', 'indfall', 'tipodom', 'nomprov', 'segmento']\nfor col in categorical_cols:\n df[col], _ = df[col].factorize(na_sentinel=-99)\nfeatures += categorical_cols\n\n# +\ndf['age'].replace(' NA', -99, inplace=True)\ndf['age'] = df['age'].astype(np.int8)\n\ndf['antiguedad'].replace(' NA', -99, inplace=True)\ndf['antiguedad'] = df['antiguedad'].astype(np.int8)\n\ndf['renta'].replace(' NA', -99, inplace=True)\ndf['renta'].fillna(-99, inplace=True)\ndf['renta'] = df['renta'].astype(float).astype(np.int8)\n\ndf['indrel_1mes'].replace('P', 5, inplace=True)\ndf['indrel_1mes'].fillna(-99, inplace=True)\ndf['indrel_1mes'] = df['indrel_1mes'].astype(float).astype(np.int8)\n# -\n\nfeatures += ['age','antiguedad','renta','ind_nuevo','indrel','indrel_1mes','ind_actividad_cliente']\n\n# +\ndf['fecha_alta_month'] = df['fecha_alta'].map(lambda x: 0.0 if x.__class__ is float else float(x.split('-')[1])).astype(np.int8)\ndf['fecha_alta_year'] = df['fecha_alta'].map(lambda x: 0.0 if x.__class__ is float else float(x.split('-')[0])).astype(np.int16)\nfeatures += ['fecha_alta_month', 'fecha_alta_year']\n\ndf['ult_fec_cli_1t_month'] = df['ult_fec_cli_1t'].map(lambda x: 0.0 if x.__class__ is float else float(x.split('-')[1])).astype(np.int8)\ndf['ult_fec_cli_1t_year'] = df['ult_fec_cli_1t'].map(lambda x: 0.0 if x.__class__ is float else float(x.split('-')[0])).astype(np.int16)\nfeatures += ['ult_fec_cli_1t_month', 'ult_fec_cli_1t_year']\n# -\n\ndf.fillna(-99, inplace=True)\n\n\ndef date_to_int(str_date):\n Y, M, D = [int(a) for a in str_date.strip().split(\"-\")] \n int_date = (int(Y) - 2015) * 12 + int(M)\n return int_date\n\n\ndf['int_date'] = df['fecha_dato'].map(date_to_int).astype(np.int8)\n\ndf_lag = df.copy()\ndf_lag.columns = [col + '_prev' if col not in ['ncodpers', 'int_date'] else col for col in df.columns ]\ndf_lag['int_date'] += 1\n\ndf_trn = df.merge(df_lag, on=['ncodpers','int_date'], how='left')\n\ndel df, df_lag\n\nfor prod in prods:\n prev = prod + '_prev'\n df_trn[prev].fillna(0, inplace=True)\ndf_trn.fillna(-99, inplace=True)\n\nfeatures += [feature + '_prev' for feature in features]\nfeatures += [prod + '_prev' for prod in prods]\n\nuse_dates = ['2016-01-28', '2016-02-28', '2016-03-28', '2016-04-28', '2016-05-28']\ntrn = df_trn[df_trn['fecha_dato'].isin(use_dates)]\ntst = df_trn[df_trn['fecha_dato'] == '2016-06-28']\ndel df_trn\n\nX = []\nY = []\nfor i, prod in enumerate(prods):\n prev = prod + '_prev'\n prX = trn[(trn[prod] == 1) & (trn[prev] == 0)]\n prY = np.zeros(prX.shape[0], dtype=np.int8) + i\n X.append(prX)\n Y.append(prY)\nXY = pd.concat(X)\nY = np.hstack(Y)\nXY['y'] = Y\n\nvld_date = '2016-05-28'\nXY_trn = XY[XY['fecha_dato'] != vld_date]\nXY_vld = XY[XY['fecha_dato'] == vld_date]\n\nparam = {\n 'booster': 'gbtree',\n 'max_depth': 8,\n 'nthread': 4,\n 'num_class': len(prods),\n 'objective': 'multi:softprob',\n 'silent': 1,\n 'eval_metric': 'mlogloss',\n 'eta': 0.1,\n 'min_child_weight': 10,\n 'colsample_bytree': 0.8,\n 'colsample_bylevel': 0.9,\n 'seed': 2018,\n }\n\n# +\nX_trn = XY_trn[features].values\nY_trn = XY_trn['y'].values\ndtrn = xgb.DMatrix(X_trn, label=Y_trn, feature_names=features)\n\nX_vld = XY_vld[features].values\nY_vld = XY_vld['y'].values\ndvld = xgb.DMatrix(X_vld, label=Y_vld, feature_names=features)\n# -\n\nwatch_list = [(dtrn, 'train'), (dvld, 'eval')]\nmodel = xgb.train(param, dtrn, num_boost_round=1000, evals=watch_list, early_stopping_rounds=20)\n\nimport pickle\npickle.dump(model, open(\"./model/xgb.baseline.pkl\", \"wb\"))\nbest_ntree_limit = model.best_ntree_limit\n\nvld = trn[trn['fecha_dato'] == vld_date]\nncodpers_vld = vld['ncodpers'].values\n\nfor prod in prods:\n prev = prod + '_prev'\n padd = prod + '_add'\n vld[padd] = vld[prod] - vld[prev] \nadd_vld = vld[[prod + '_add' for prod in prods]].values\nadd_vld_list = [list() for i in range(len(ncodpers_vld))]\n\ncount_vld = 0\nfor ncodper in range(len(ncodpers_vld)):\n for prod in range(len(prods)):\n if add_vld[ncodper, prod] > 0:\n add_vld_list[ncodper].append(prod)\n count_vld += 1\n\n\n# +\ndef apk(actual, predicted, k=7, default=0.0):\n # AP@7なので、最大7個まで使用します。\n if len(predicted) > k:\n predicted = predicted[:k]\n\n score = 0.0\n num_hits = 0.0\n\n for i, p in enumerate(predicted):\n # 点数を付与する条件は次のとおり :\n # 予測値が正答に存在し (‘p in actual’)\n # 予測値に重複がなければ (‘p not in predicted[:i]’) \n if p in actual and p not in predicted[:i]:\n num_hits += 1.0\n score += num_hits / (i+1.0)\n\n # 正答値が空白である場合、ともかく 0.0点を返します。\n if not actual:\n return default\n\n # 正答の個数(len(actual))として average precisionを求めます。\n return score / min(len(actual), k)\n\ndef mapk(actual, predicted, k=7, default=0.0):\n # list of listである正答値(actual)と予測値(predicted)から顧客別 Average Precisionを求め, np.mean()を通して平均を計算します。\n return np.mean([apk(a, p, k, default) for a, p in zip(actual, predicted)]) \n\n\n# -\n\nprint(mapk(add_vld_list, add_vld_list, 7, 0.0))\n\nX_all = XY[features].values\nY_all = XY['y'].values\ndall = xgb.DMatrix(X_all, label=Y_all, feature_names=features)\nwatch_list = [(dall, 'train')]\n\nbest_ntree_limit = int(best_ntree_limit * (len(XY_trn) + len(XY_vld)) / len(XY_trn))\n\nmodel = xgb.train(param, dall, num_boost_round=best_ntree_limit, evals=watch_list)\n\nprint(\"Feature importance:\")\nfor kv in sorted([(k,v) for k,v in model.get_fscore().items()], key=lambda kv: kv[1], reverse=True):\n print(kv)\n\nX_tst = tst[features].values\ndtst = xgb.DMatrix(X_tst, feature_names=features)\npreds_tst = model.predict(dtst, ntree_limit=best_ntree_limit)\nncodpers_tst = tst['ncodpers'].values\npreds_tst = preds_tst - tst[[prod + '_prev' for prod in prods]].values\n\nsubmit_file = open('./model/xgb.baseline.2015-06-28', 'w')\nsubmit_file.write('ncodpers,added_products\\n')\nfor ncodper, pred in zip(ncodpers_tst, preds_tst):\n y_prods = [(y,p,ip) for y,p,ip in zip(pred, prods, range(len(prods)))]\n y_prods = sorted(y_prods, key=lambda a: a[0], reverse=True)[:7]\n y_prods = [p for y,p,ip in y_prods]\n submit_file.write('{},{}\\n'.format(int(ncodper), ' '.join(y_prods)))\n","repo_name":"tky/kaggle","sub_path":"santander-product-recommendation/2.7Baseline.ipynb","file_name":"2.7Baseline.ipynb","file_ext":"py","file_size_in_byte":6830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"33"} +{"seq_id":"29650009305","text":"# ## Engineering Rare Categories\n#\n# **Rare values** are categories within a categorical variable that are present only **in a small percentage of the observations**. There is no rule, but typically, any value below 5 % can be considered rare. If only on the **train set**, they may cause **over-fitting**! If only on the **test set**, our machine learning model will **not know how to score them**!\n#\n# **Highly cardinal variables** tend to have **many infrequent or rare categories**, whereas **low cardinal variables**, may have **only 1 or 2 rare labels.**\n#\n# Now we will re-group rare labels under a new category called rare, and compare the implications of this encoding in variables with: **One predominant category, A small number of categories, High cardinality!**\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\npd.set_option('display.max_columns', None) # to display the total number columns!\n\n# ## House Sale Price dataset\n\ndata = pd.read_excel('HousingPrices.xls')\ndata.head()\n\n# ### Important\n#\n# The identification of rare labels should be done **using only the training set**, and then propagated to the test set. \n\nX_train, X_test, y_train, y_test = train_test_split(\n data.drop(labels=['SalePrice'], axis=1), # predictors\n data.SalePrice, # target\n test_size=0.3,\n random_state=0)\nX_train.shape, X_test.shape\n\n# ## Variables with one dominant category\n\n# **Explore the variables with a few categories, say less than 3!**\n\nfor col in X_train.columns:\n if X_train[col].dtypes == 'O': # if the variable is categorical\n if X_train[col].nunique() < 3: # less than 3 categories\n print(X_train.groupby(col)[col].count() / len(X_train)) # Their percentage!\n\n# ### Conclusion\n#\n# The 3 variables above, **Street, Utilities and CentralAir**, show one dominating category which **accounts for more than 93-99% of the observations**. **Re-grouping the rare label in this situation does not make any sense.** We could determine if these variables are useful with exploratory analysis, or any feature selection algorithm, or drop the variables altogether.\n#\n# ## Variables with few categories\n\n# **The columns in the below list have only 4 different labels!**\n\ncols = ['MasVnrType', 'ExterQual', 'BsmtCond']\nfor col in cols:\n print(X_train.groupby(col)[col].count() / len(X_train)) # frequency\n print()\n\n# The first variable **MasVnrType** shows only **1 rare label**, BrkCmn. No sense to re-categorise it! The variables **ExterQual** and **BsmtCond** contain **more tham one label**, so we can **group these 3 under the new label 'Rare'!**\n\n# ## Variable with high cardinality\n\n# **Explore the variables with several categories, say more than 10!**\n\nmulti_cat_cols = []\nfor col in X_train.columns:\n if X_train[col].dtypes =='O': # if variable is categorical\n if X_train[col].nunique() > 10: # and has more than 10 categories\n multi_cat_cols.append(col) # add to the list\n print(X_train.groupby(col)[col].count()/ len(X_train)) # and print the percentage of observations within each category\n print()\n\n# We can see that **many categories are rare** in the 3 categorical variables printed above. In fact, we can **plot them** using the same code we learned in the lecture on rare labels in section 3:\n\n# **Plot the above percentages! Add a line at 5 % to flag the threshold for rare categories!**\n\nfor col in ['Neighborhood', 'Exterior1st', 'Exterior2nd']:\n temp_df = pd.Series(X_train[col].value_counts() / len(X_train) )\n fig = temp_df.sort_values(ascending=False).plot.bar()\n fig.set_xlabel(col)\n fig.axhline(y=0.05, color='red')\n fig.set_ylabel('Percentage of houses')\n plt.show()\n\n\n# ## Re-grouping rare labels with pandas\n\ndef find_non_rare_labels(df, variable, tolerance):\n temp = df.groupby([variable])[variable].count() / len(df)\n non_rare = [x for x in temp.loc[temp>tolerance].index.values]\n return non_rare\n\n\n# **Non rare labels!**\n\nfind_non_rare_labels(X_train, 'Neighborhood', 0.05)\n\n# **Rare labels!**\n\n[x for x in X_train['Neighborhood'].unique(\n) if x not in find_non_rare_labels(X_train, 'Neighborhood', 0.05)]\n\n# **Find the most frequent category! Re-group rare labels!**\n\n# for variable in ['Neighborhood', 'Exterior1st', 'Exterior2nd']:\n# X_train, X_test = rare_encoder(X_train, X_test, variable, 0.05)\n\nfor col in ['Neighborhood', 'Exterior1st', 'Exterior2nd']:\n temp_df = pd.Series(X_train[col].value_counts() / len(X_train) )\n fig = temp_df.sort_values(ascending=False).plot.bar() # Plot with percentages!\n fig.set_xlabel(col)\n fig.axhline(y=0.05, color='red') # The threshold line at 5 % for rare categories!\n fig.set_ylabel('Percentage of houses')\n plt.show()\n\n# And now let's encode the low cardinal variables.\n\n# + active=\"\"\n# for variable in ['MasVnrType', 'ExterQual', 'BsmtCond']:\n# X_train, X_test = rare_encoding(X_train, X_test, variable, 0.05)\n# -\n\n# **Plot with the percentages! Add a line at 5 % to flag the threshold for rare categories!**\n\nfor col in ['MasVnrType', 'ExterQual', 'BsmtCond']:\n temp_df = pd.Series(X_train[col].value_counts() / len(X_train) )\n fig = temp_df.sort_values(ascending=False).plot.bar()\n fig.set_xlabel(col)\n fig.axhline(y=0.05, color='red')\n fig.set_ylabel('Percentage of houses')\n plt.show()\n\n# ## Encoding Rare Labels with Feature-Engine\n\nfrom feature_engine.encoding import RareLabelEncoder\n\n# **Devide into train and test set!**\n\nX_train, X_test, y_train, y_test = train_test_split(\n data.drop(labels=['SalePrice'], axis=1), # predictors\n data.SalePrice, # target\n test_size=0.3,\n random_state=0)\nX_train.shape, X_test.shape\n\n# **Rare value encoder!**\n\nrare_encoder = RareLabelEncoder(\n tol=0.05, # minimal percentage to be considered non-rare\n n_categories=4, # minimal category number to group for the rare variable!\n variables=['Neighborhood', 'Exterior1st', 'Exterior2nd',\n 'MasVnrType', 'ExterQual', 'BsmtCond']) # variables to re-group\n\nrare_encoder.fit(X_train.fillna('Missing'))\n\n# Note how the encoder is warning us that the variable **ExterQual** contains less than 4 categories, and thus, categories will not be regrouped under Rare, even if the percentage of observations is less than 0.05.\n\nrare_encoder.variables_\n\n# **The encoder_dict_ is a dictionary of variable: frequent labels pair**\n\nrare_encoder.encoder_dict_\n\nX_train = rare_encoder.transform(X_train.fillna('Missing'))\nX_test = rare_encoder.transform(X_test.fillna('Missing'))\n","repo_name":"haka1453/Python","sub_path":"Machine Learning/FEML_Codes/06.10-Engineering-Rare-Categories.ipynb","file_name":"06.10-Engineering-Rare-Categories.ipynb","file_ext":"py","file_size_in_byte":6592,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"33"} +{"seq_id":"10915402084","text":"# index of an item in a list\nlist_1=[\"dhaka\",\"bangla\",\"khulna\",\"dinajpur\",12,3,4,5,6,7,8,10]\nlist_1\n\nlist_1.index(\"khulna\")\nprint(list_1)\n\nlist_1.insert(1,\"horse\")\nprint(list_1)\n\nlist_2=[1,2,3,4,5,6,7,\"bangla\",\"english\",\"math\",\"cat\"]\nmy_list=[[1,2,3,4],\n [4,5,6,7],\n [7,8,9,10]]\nmy_list\n\nflatten_list=[i for sublist in my_list for i in sublist]\nflatten_list\n\ncopy_list=list_1.copy()\nprint(copy_list)\n\nprint(list_1)\nprint(\"+++++++++++++++++++++++++++++++++++++++\")\nprint(list_2)\n\nz=list(zip(list_1,list_2))\nprint(z)\n\nlist_3=[\"p\"]*10\nprint(list_3)\n\nlist_1\n\nlist_4=[1,2,3,4,5,6,7,8,9]\nfor x in list_4:\n if x%2==0:\n print(x,\"EVEN\")\n else:\n print(x,\"ODD\")\n\nfilter_list=[i for i in list_4 if i%2!=0]\nfilter_list\n\n# list to dicrectory\nlist_key=[1,2,3]\nlist_value=[\"one\",\"two\",\"three\"]\nmy_new_dic=dict(zip(list_key,list_value))\nmy_new_dic\n\nlist_1,list_2\n\nnew=list(set(list_1)& set(list_2))\nnew\n\nnew1=set(list_1).intersection(list_2)\nnew1\n\nnew2=list(new1)\nprint(new2)\n\nx=\"bangladesh is a poor country\"\nx=list(x)\nchar_list=[ch for ch in x]\nprint(char_list)\n\n\n","repo_name":"jarif87/Python_Basic","sub_path":"Python Data Type List 02.ipynb","file_name":"Python Data Type List 02.ipynb","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"33"} +{"seq_id":"14411506226","text":"import xlrd\n\ndic_words = []\n\nworkbook = xlrd.open_workbook(\"data.xlsx\")\ndata = workbook.sheet_by_name(\"Sheet1\") \nrows = data.get_rows() #获取总的行数\n\nfor row in rows:\n dic_words.append(row[0].value) #将每个词加入数组中\nprint(\"len:\" + str(len(dic_words)))\n\ndic_words[1]\n\n\n# +\ndef fully_segment(text,dic):\n word_list = []\n for i in range(len(text)):\n for j in range(i+1,len(text)+1):\n word = text[i:j]\n if word in dic:\n word_list.append(word)\n return word_list\n\n#在不考虑效率的情况下最简单的分词方式\n\n\n# -\n\nfully_segment(\"我想出去玩呀\",dic_words)\n\n\ndef forward_segment(text,dic):\n word_list = []\n i = 0\n while ilen(longest_word):\n longest_word = word\n i += len(longest_word) #去除已经分好的词之后再继续进行分词\n word_list.append(longest_word)\n return word_list\n#分词的优先级是按照词组的长度来划分的,词组长度约长,优先级越高\n\n\nforward_segment(\"我想出去玩呀\",dic_words)\n\n\n# ###逆向最大分词###\n# 是为了解决“研究生命起源”这种分词问题的,使用最大向前分次的结果为:“研究生”“命”“起源”,而这种分词结果与我们正常的生活中的分词概念不一样\n\ndef backward_segment(text,dic):\n word_list = []\n i = len(text) - 1 #以句子的终点为起点进行分词\n while i>=0:\n longest_word = text[i]\n for j in range(0,i):\n word = text[j:i+1] #匹配长度最大的词\n if word in dic:\n if len(word)>len(longest_word):\n longest_word = word\n i -= len(longest_word)\n word_list.insert(0,longest_word) #因为是最大逆向分词,所以先分出来的词应该在最后面\n return word_list\n\n\nbackward_segment(\"我想出去玩呀\",dic_words)\n\n\n#统计单个词的出现次数\ndef count_single_char(word_list:list):\n return sum(1 for word in word_list if len(word)==1)\n\n\n#双向最长匹配:1.同时执行正向和逆向匹配,若两者词数不同,则返回词数较少的那一个结果;2.否则,返回两者中单字数量更少的那一个。当两者单字数\n#量一样时,优先返回逆向最长匹配的结果\ndef bidirectional_segment(text,dic):\n f = forward_segment(text,dic)\n b = backward_segment(text,dic)\n if(len(f)len(b)):\n return b\n else:\n if(count_single_char(f)Author's Note: Based on titleId, a project can have several titles along its development. Therefore the unique titleIds will be taken from this df and used as filter to the second df. Ordering, title, region, types, attributes and isOriginalTitle will be dropped since these data are not needed\n\n# +\n# remove duplicated title Ids, get only 1st entry\ndf_ph = df_ph.drop_duplicates(subset=['titleId'])\n\n# drop columns that will not be used\ndf_ph = df_ph.drop(columns=['ordering', 'title', 'region', 'types', 'attributes', 'isOriginalTitle'])\ndf_ph.head()\n# -\n\ndf_ph.shape\n\n# 2. Inspect contents of 2nd df, renamed to df_basics and join with df_ph\n\n# +\n# create copy of df from basic.tsv.gz extact\ndf_basics = df_list[1].copy()\n\n# drop columns that will not be used\ndf_basics = df_basics.drop(columns=['titleType', 'isAdult','endYear'])\ndf_basics.head()\n# -\n\ndf_basics.shape\n\n# +\n# join df_basic to df_ph\ndf_ph = df_ph.merge(df_basics, how='inner',left_on='titleId', right_on='tconst')\n\n# remove key from df_basics\ndf_ph.drop(columns=['tconst'], inplace=True)\n\ndf_ph.head()\n# -\n\ndf_ph.shape\n\n# Author's Note: Rows where 'titleId' is present but have no matching 'tconst' in df_basics were automatically dropped due to 'inner' merge\n\n# 3. Inspect last df (df_rating) and join to df_ph\n\ndf_rating = df_list[2].copy()\nprint(df_rating.shape)\ndf_rating.head()\n\n# +\n# join df_rating to df_ph\ndf_ph = df_ph.merge(df_rating, how='inner', left_on='titleId', right_on='tconst')\n\n# drop key from rating\ndf_ph.drop(columns=['tconst'], inplace=True)\n\ndf_ph.head()\n# -\n\ndf_ph.shape\n\n# Author's Note: Rows where 'titleId' is present but have no matching 'tconst' in df_ratings were automatically dropped due to 'inner' merge\n\n# ### Preprocess unified dataframe\n\n# Author's Note: There are no null values per se, but \\N is used as placeholder for cells with no value. Each column will be cleaned one by one\n\ndf_ph.info()\n\ndf_ph.head()\n\n\n# +\n# create function that can count number of \\N for each column (an alternative to using heatmaps)\ndef check_N(frame):\n for col in frame.columns:\n empty = sum(frame[col] == \"\\\\N\")\n print(f'Number of empty values in {col}: {empty}')\n \n \ncheck_N(df_ph)\n# -\n\n# Author's Note: language and genres can be easily replaced with another placeholder (ex. unspecified. startYears cannot be guessed and would be best researched for correct values or just deleted\n\n# +\n# replace '\\N' in languages and genres with unspecified\ndf_ph['language'] = df_ph['language'].replace(r'\\\\N','unspecified', regex=True)\ndf_ph['genres'] = df_ph['genres'].replace(r'\\\\N','unspecified', regex=True)\n\ncheck_N(df_ph)\n# -\n\n# finding rows where startYear is empty\ndf_ph[df_ph['startYear']== '\\\\N']\n\n# +\n# change values manually (data from research)\ndf_ph.at[3984, 'startYear'] = 1978\ndf_ph.at[3985, 'startYear'] = 1978\ndf_ph.at[5663, 'startYear'] = 2021\n\n# convert startYear to proper format\ndf_ph['startYear'] = pd.to_datetime(df_ph['startYear'], format = '%Y')\n\ncheck_N(df_ph)\n# -\n\n# inspect entries where runtime is not specified\ndf_ph[df_ph['runtimeMinutes'] == '\\\\N'].head()\n\n# Author's Note: A lot of entries actually were aired movies that simply have incomplete data. It would be a misrepresentation to delete the entries, but so is setting an arbitrary value. For this activity and to allow basic data viz (which will have errors due to wrong data type), it is better to set values to null \n\ndf_ph['runtimeMinutes'] = df_ph['runtimeMinutes'].replace('\\\\N',None, regex=True)\n\n# ### Final Output\n\ncheck_N(df_ph)\n\ndf_ph.info()\n\n# ### Sample data viz (not filtered, cleaned data)\n\n# +\nimport matplotlib.pyplot as plt\n\nplt.figure(figsize=(12,12))\nplt.title('Movies, Shows and Documentaries Aired in the Philippines')\n\nsns.scatterplot(data=df_ph, \n x='startYear', \n y='averageRating', \n hue='numVotes', \n alpha = 0.7,\n palette=sns.dark_palette(\"#69d\", reverse=True, as_cmap=True),\n legend=False,\n )\nsns.set_style('ticks')\n","repo_name":"vanessapigwin/ph_imdb","sub_path":"ph_imdb.ipynb","file_name":"ph_imdb.ipynb","file_ext":"py","file_size_in_byte":5563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"33"} +{"seq_id":"24304895912","text":"# 1. The following (unfinished) program implements a digital line queuing system for an amusement park ride. The system allows a rider to reserve a place in line without actually having to wait. The rider simply enters a name into a program to reserve a place. Riders that purchase a VIP pass get to skip past the common riders up to the last VIP rider in line. VIPs board the ride first. For this system, an employee manually selects when the ride is dispatched (thus removing the next riders from the front of the line). Complete the following program, as described above.\n\n# +\nline = [] # The line of riders\nnum_vips = 0 # Track number of VIPs at front of line\n\nmenu = ('(1) Reserve place in line.\\n' # Add rider to line\n '(2) Reserve place in VIP line.\\n' # Add VIP\n '(3) Dispatch riders.\\n' # Dispatch next ride car\n '(4) Print riders.\\n'\n '(5) Exit.\\n\\n')\n\nuser_input = input(menu).strip()\n\nwhile user_input != '5':\n if user_input == '1': # Add rider \n name = input('Enter name:').strip()\n print(name)\n line.add(name)\n elif user_input == '2': # Add VIP\n print('Add new VIP')\n name = input('Enter name:').strip()\n line.insert(num_vips,name)\n num_vips += 1\n elif user_input == '3': # Dispatch ride\n print('Removed riders from the front of the line.')\n line.clear()\n elif user_input == '4': # Print riders waiting in line\n print('%d person(s) waiting:' % len(line), line)\n else:\n print('Choose another menu option')\n\n user_input = input(menu).strip()\n print(user_input)\n\n\n# -\n\n# 2. Write a program that reads numbers and adds them to a list if they aren't already contained in the list. When the list contains ten numbers, the program displays the contents and quits.\n\n# +\ndef main():\n numList = []\n while len(numList) < 10:\n num = input('Enter a number: ')\n num = float(num)\n if num not in numList:\n numList.append(num)\n else:\n print('Enter a different number: ')\n print(numList)\n\nmain()\n\n\n# -\n\n# 3. We have a 12-side dice. Write a program to print the frequency of each die value from the user inputs. The user can input as many die toss values ass possible until the user quits.\n\n# +\ndef main():\n counters = countInputs(12)\n printCounters(counters)\n \ndef countInputs(sides):\n counters = [0] * (sides + 1) \n userInput = input(\"Please enter values, Q to quit:\")\n while userInput.upper() != \"Q\" :\n value = int(userInput)\n if value >= 1 and value <= sides :\n counters[value] = counters[value] + 1\n else:\n print(value, \"is not a valid input.\")\n userInput = input(\"Please enter values, Q to quit:\") \n return counters\n\ndef printCounters(counters):\n for i in range(1, len(counters)):\n print(\"%2d: %4d\" % (i, counters[i]))\n\nmain()\n\n\n# -\n\n# 4. You are given a list whose size is an even number, and you are to switch the first and second half.\n\n# +\ndef main() :\n list = [9, 13, 21, 4, 11, 7, 1, 3]\n pos1 = 0\n pos2 = len(list) // 2\n while pos1 < len(list) // 2 :\n swapPos(list, pos1, pos2)\n pos1 = pos1 + 1\n pos2 = pos2 + 1\n print(list)\n \ndef swapPos(lt, pos1, pos2) :\n temp = lt[pos1]\n lt[pos1] = lt[pos2]\n lt[pos2] = temp\n\nmain()\n\n\n# -\n\n# 5. Write a program that first gets a list of intergers from the input. That list is followed by two more integers representing lower and upper bound of a range. Your program should output all integers from the list that are within that range (inclusive of the bounds).\n\ndef range():\n numList = []\n userInput = input('Enter a integer, Q to quit: ')\n while userInput.upper() != \"Q\":\n userInput = int(userInput)\n if userInput not in numList:\n numList.append(userInput)\n else:\n print('Enter a different number.')\n userInput = input('Enter a integer, Q to quit: ')\n \n numList.sort()\n range_min = int(input('Enter the minimum range value: '))\n range_max = int(input('Enter the maximum range value: '))\n for number in numList:\n if range_min <= number <= range_max:\n print(number, end = ' ')\nrange()\n\n\n","repo_name":"AustinPerea/PythonDataProjects","sub_path":"Lab4AustinPerea.ipynb","file_name":"Lab4AustinPerea.ipynb","file_ext":"py","file_size_in_byte":4245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"33"} +{"seq_id":"4097126254","text":"# ### Dataset\n# ID : Unique Identifier for a row\n#\n# Gender: Gender of the Customer\n#\n# Age : Age of the Customer (in Years)\n#\n# Region_Code : Code of the Region for the customers\n#\n# Occupation : Occupation Type for the customer\n#\n# Channel_Code : Acquisition Channel Code for the Customer (Encoded)\n#\n# Vintage : Vintage for the Customer (In Months), Number of Days, Customer has been associated with the company\n#\n# Credit_Product : If the Customer has any active credit product (Home loan, Personal loan, Credit Card etc.)\n#\n# Avg_Account_Balance : Average Account Balance for the Customer in last 12 Months\n#\n# Is_Active : If the Customer is Active in last 3 Months\n#\n# Is_Lead(Target) : If the Customer is interested for the Credit Card, 0 / 1: Customer is not interested / interested\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport optuna\n\ndf_train=pd.read_csv('train_credit.csv')\ndf_test=pd.read_csv('test_credit.csv')\n\n\ntrain=df_train.copy()\ntest=df_test.copy()\n\ndf_train.isnull().sum()\n\ndf_test.isnull().sum()\n\n#Credit_Product column has null values. Lets remoe them\ndf_train['Credit_Product']=df_train['Credit_Product'].fillna('NA')\n\ndf_test['Credit_Product']=df_test['Credit_Product'].fillna('NA')\n\ndf_test.isnull().sum()\n\ndf_train['Is_Lead'].value_counts()\n\n#Lets take a look at the categorical columns\ncolumns=[ 'Gender', 'Region_Code', 'Occupation', 'Channel_Code',\n 'Credit_Product', 'Is_Active','Is_Lead']\nfor i in columns:\n print(\"value counts of \",i,\"is:\")\n print(df_train[i].value_counts())\n print()\n print('Unique values of',i,'is:',df_train[i].unique())\n print()\n\n\n# As we can see the data is imbalanced\n#\n# #### DAta Visualisation:\n\n# +\n# defining funtion to represent graph\n\ndef with_hue(data,feature,ax):\n #Numnber of categories\n num_of_cat=len([x for x in df[feature].unique() if x==x])\n \n bars=ax.patches\n \n for ind in range(num_of_cat):\n ## Get every hue bar\n hueBars=bars[ind:][::num_of_cat]\n # Get the total height (for percentages)\n total=sum([x.get_height() for x in hueBars])\n \n #Print percentages in bar\n for bar in hueBars:\n percentage='{:.1f}%'.format(100*bar.get_height()/total)\n ax.text(bar.get_x()+bar.get_width()/2.0,\n bar.get_height(),\n percentage,\n ha=\"center\",va=\"bottom\",fontweight='bold',fontsize=14)\n \ndef without_hue(data,feature,ax):\n total=float(len(data))\n bars_plot=ax.patches\n \n for bars in bars_plot:\n percentage = '{:.1f}%'.format(100 * bars.get_height()/total)\n x = bars.get_x() + bars.get_width()/2.0\n y = bars.get_height()\n ax.text(x, y,(percentage,bars.get_height()),ha='center',fontweight='bold',fontsize=14)\n\n\n\n# -\n\ndf=df_train.copy()\n\n# +\nsns.set(context=\"notebook\",style=\"white\",font_scale=2)\nfig=plt.figure(figsize=(15,7))\n\n#Setting plot and background color\nax=plt.axes()\nax.set_facecolor(\"#F2EDD7FF\") \nfig.patch.set_facecolor(\"#F2EDD7FF\")\n#Dealing with spines\nax.spines['top'].set_visible(False)\nax.spines['right'].set_visible(False)\nax.spines['left'].set_visible(False)\nax.grid(linestyle=\"--\",axis='y',color='gray')\n\na=sns.countplot(data=df,x='Is_Lead',palette='rocket_r')\nwithout_hue(df,'Is_Lead',a)\n\n# +\nnrows=5\nncols=2\nf,ax=plt.subplots(nrows=nrows,ncols=ncols,figsize=(20,34))\ncolumns=['Gender','Occupation', 'Channel_Code','Credit_Product', 'Is_Active']\n\nf.patch.set_facecolor('#F2EDD7FF')\n\n #Setting background and foreground color\nfor i in range(0,nrows):\n for j in range(0,ncols):\n ax[i][j].set_facecolor('#F2EDD7FF')\n ax[i][j].spines['top'].set_visible(False)\n ax[i][j].spines['right'].set_visible(False)\n ax[i][j].spines['left'].set_visible(False)\n ax[i][j].grid(linestyle=\"--\",axis='y',color='gray')\n \n if(j==0):\n a1=sns.countplot(data=df,x=columns[i-1],palette='rocket_r',ax=ax[i][j])\n without_hue(df,columns[i-1],a1)\n elif(j==1):\n a2=sns.countplot(data=df,x=columns[i-1],palette='rocket_r',ax=ax[i][j],hue=\"Is_Lead\")\n with_hue(df,columns[i-1],a2)\n# -\n\n# Self employed and salaried people are less likely to get credit card whereas entrepreneurs though limited will get credit card \n#\n# People who already have credit product shows considerable interest comapritively to get credit card\n#\n# People in channel code X2 and X3 shows considereable interest comapritively\n#\n# The ratio of male getting credit card is slightly higher than female\n\n# +\nnrows=3\nncols=2\nf,ax=plt.subplots(nrows=nrows,ncols=ncols,figsize=(25,34))\ncolumns=[\"Age\",\"Vintage\",\"Avg_Account_Balance\"]\n\nf.patch.set_facecolor('#F2EDD7FF')\n\n #Setting background and foreground color\nfor i in range(0,nrows):\n for j in range(0,ncols):\n ax[i][j].set_facecolor('#F2EDD7FF')\n ax[i][j].spines['top'].set_visible(False)\n ax[i][j].spines['right'].set_visible(False)\n ax[i][j].spines['left'].set_visible(False)\n ax[i][j].grid(linestyle=\"--\",axis='y',color='gray')\n \n if (j==0):\n a1=sns.boxplot(data=df,x=(df[columns[i-1]]),palette='rocket_r',ax=ax[i][j])\n elif (j==1):\n a2=sns.histplot(data=df,x=(df[columns[i-1]]),palette='rocket_r',ax=ax[i][j],hue='Is_Lead',kde=True)\n \n\n# -\n\n# There are outliers in avg account balance because many people have low account balance . So lets try taking log of it\n\nsns.histplot(data=df,x=np.log(df['Avg_Account_Balance']),palette='rocket_r',kde=True)\n\n#Changing the distribution of 'Avg_Account_Balance' into Log Distribution\ndf['Avg_Account_Balance']=np.log(df['Avg_Account_Balance'])\n\n\ndf1=df.copy()\n\ndf[\"Is_Active\"].replace([\"Yes\",\"No\"],[1,0],inplace=True)\ndf_test[\"Is_Active\"].replace([\"Yes\",\"No\"],[1,0],inplace=True)\n\n# +\nfrom sklearn.preprocessing import LabelEncoder\nle = LabelEncoder()\ncolumns1=['Occupation', 'Channel_Code','Credit_Product']\n\ncat_col=['Gender','Region_Code']\n\nfor col in cat_col:\n le.fit(df[col])\n df[col]= le.transform(df[col])\n \n# -\n\nfor col in cat_col:\n df_test[col]= le.transform(df_test[col])\n\ndf=pd.get_dummies(data=df,columns=columns1,drop_first=True)\n\ndf.head()\n\ndf_test=pd.get_dummies(data=df_test,columns=columns1,drop_first=True)\n\ndf.drop('ID',axis=1,\n inplace=True)\n\ndf_test.drop('ID',axis=1,inplace=True)\n\n# #### Undersampling Imbalanced dataset\n\n# +\ndf_majority=df[df['Is_Lead']==0]\ndf_minority=df[df['Is_Lead']==1]\n\nprint(\" The majority class values are\", len(df_majority))\nprint(\" The minority class values are\", len(df_minority))\nprint(\" The ratio of both classes are\", len(df_majority)/len(df_minority))\n# -\n\nX = df.drop(columns=['Is_Lead'])\ny = df[[\"Is_Lead\"]]\n\n# +\nfrom sklearn import metrics\nfrom scipy.stats import zscore\nfrom sklearn.preprocessing import LabelEncoder,StandardScaler\nfrom sklearn.model_selection import train_test_split,GridSearchCV\nfrom sklearn.decomposition import PCA\nfrom sklearn.metrics import precision_score, recall_score, confusion_matrix, f1_score, roc_auc_score, roc_curve\nfrom sklearn.metrics import accuracy_score,classification_report,confusion_matrix,roc_auc_score,roc_curve\nfrom sklearn.metrics import auc\nfrom sklearn.metrics import plot_roc_curve\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import AdaBoostClassifier,GradientBoostingClassifier\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.naive_bayes import GaussianNB\n\n#Import warnings\nimport warnings\nwarnings.filterwarnings('ignore')\n# -\n\nfrom sklearn.model_selection import cross_val_score,train_test_split , StratifiedKFold\n\n#Standardizing value of x by using standardscaler to make the data normally distributed\nsc = StandardScaler()\ndf_X = pd.DataFrame(sc.fit_transform(X),columns=X.columns)\n\n\n# +\n#defining a function to find fit of the model\n\ndef max_accuracy_scr(names,model_c,df_xc,yc):\n accuracy_scr_max = 0\n roc_scr_max=0\n train_xc,test_xc,train_yc,test_yc = train_test_split(df_X,y,random_state = 42,test_size = 0.2,stratify =y)\n model_c.fit(train_xc,train_yc)\n pred = model_c.predict_proba(test_xc)[:, 1]\n roc_score = roc_auc_score(test_yc, pred)\n accuracy_scr = accuracy_score(test_yc,model_c.predict(test_xc))\n if roc_score> roc_scr_max:\n roc_scr_max=roc_score\n final_model = model_c\n mean_acc = cross_val_score(final_model,df_X,y,cv=5,scoring=\"accuracy\").mean()\n std_dev = cross_val_score(final_model,df_X,y,cv=5,scoring=\"accuracy\").std()\n cross_val = cross_val_score(final_model,df_X,y,cv=5,scoring=\"accuracy\")\n print(\"*\"*50)\n print(\"Results for model : \",names,'\\n',\n \"max roc score correspond to random state \" ,roc_scr_max ,'\\n',\n \"Mean accuracy score is : \",mean_acc,'\\n',\n \"Std deviation score is : \",std_dev,'\\n',\n \"Cross validation scores are : \" ,cross_val) \n print(f\"roc_auc_score: {roc_score}\")\n print(\"*\"*50)\n\n\n# +\n#Now by using multiple Algorithms we are calculating the best Algo which performs best for our data set \naccuracy_scr_max = []\nmodels=[]\n#accuracy=[]\nstd_dev=[]\nroc_auc=[]\nmean_acc=[]\ncross_val=[]\nmodels.append(('Logistic Regression', LogisticRegression()))\nmodels.append(('Random Forest', RandomForestClassifier()))\nmodels.append(('Decision Tree Classifier',DecisionTreeClassifier()))\nmodels.append((\"GausianNB\",GaussianNB()))\n\nfor names,model_c in models:\n max_accuracy_scr(names,model_c,df_X,y)\n\n\n\n# +\nfrom sklearn.neighbors import KNeighborsClassifier\n\n\n# -\n\nx_train,x_test,y_train,y_test=train_test_split(df_X,y,test_size=0.3,random_state=42)\n\n\ndef objective(trial):\n \n #n_estimators = trial.suggest_int('n_estimators', 2, 200)\n n_neighbors = int(trial.suggest_int('n_neighbors', 2,50))\n clf = KNeighborsClassifier(n_neighbors=n_neighbors)\n cv=StratifiedKFold(n_splits=5,random_state=42,shuffle=True)\n\n return cross_val_score(clf, x_train, y_train, \n n_jobs=2, cv=cv,scoring='roc_auc').mean()\n\n\n\nstudy = optuna.create_study(direction='maximize',study_name='KNN')\nstudy.optimize(objective, n_trials=15)\n\n\ntrial = study.best_trial\nprint('## best_values -->',trial.value)\nprint(\"## best_parameters -->\",trial.params)\n\n\nmodel_k=KNeighborsClassifier(n_neighbors=50)\n\nmodel_k.fit(x_train,y_train)\n\ny_pred_k=model_k.predict_proba(x_test)[:,1]\n\n\nprint(roc_auc_score(y_test,y_pred_k))\n\n# XGBoost Classifier:\n\nimport xgboost as xg\nfrom xgboost import XGBClassifier\nfrom sklearn.utils import class_weight\n\nclf2 = xg.XGBClassifier(class_weight='balanced').fit(x_train, y_train)\nclass_weight.compute_class_weight('balanced', np.unique(y_train), y_train[\"Is_Lead\"])\nxg_pred = clf2.predict(x_test)\n\n\n# +\n#XG Boost Results\nxg_pred_2=clf2.predict_proba(x_test)[:,1]\nFpr,Tpr,thresholds = roc_curve(y_test,xg_pred_2,pos_label=True)\nauc = roc_auc_score(y_test,xg_pred_2)\n\nprint(\" ROC_AUC score is \",auc)\nprint(\"accuracy score is : \",accuracy_score(y_test,xg_pred))\nprint(\"Precision is : \" ,precision_score(y_test, xg_pred))\nprint(\"Recall is: \" ,recall_score(y_test, xg_pred))\nprint(\"F1 Score is : \" ,f1_score(y_test, xg_pred))\nprint(\"classification report \\n\",classification_report(y_test,xg_pred))\n\ncnf = confusion_matrix(y_test,xg_pred)\nsns.heatmap(cnf, annot=True, cmap = \"magma\")\n# -\n\n#plotting the graph for area under curve for representing accuracy of data\nplt.plot([0,1],[1,0],'g--')\nplt.plot(Fpr,Tpr)\nplt.xlabel('False_Positive_Rate')\nplt.ylabel('True_Positive_Rate')\nplt.title(\"XG_Boost Classifier\")\nplt.show()\n\n# +\n#Trying stratification modeling\nfrom sklearn.model_selection import KFold, StratifiedKFold\n\ndef cross_val(X, y, model, params, folds=10):\n\n skf = StratifiedKFold(n_splits=folds, shuffle=True, random_state=42)\n for fold, (train_idx, test_idx) in enumerate(skf.split(X, y)):\n print(f\"Fold: {fold}\")\n x_train, y_train = X.iloc[train_idx], y.iloc[train_idx]\n x_test, y_test = X.iloc[test_idx], y.iloc[test_idx]\n\n model_c= model(**params)\n model_c.fit(x_train, y_train,eval_set=[(x_test, y_test)],early_stopping_rounds=100, verbose=300)\n\n pred_y = model_c.predict_proba(x_test)[:, 1]\n roc_score = roc_auc_score(y_test, pred_y)\n print(f\"roc_auc_score: {roc_score}\")\n print(\"-\"*50)\n \n return model_c\n\n\n# +\n#Applying LGBM Model with 10 stratified cross-folds\nfrom lightgbm import LGBMClassifier\n\nlgb_params= {'learning_rate': 0.045, 'n_estimators': 10000,'max_bin': 84,'num_leaves': 10,'max_depth': 20,'reg_alpha': 8.457,'reg_lambda': 6.853,'subsample': 0.749}\nlgb_model = cross_val(X, y, LGBMClassifier, lgb_params)\n\n# +\n#LGBM results:\nlgb_pred_2=lgb_model.predict_proba(x_test)[:,1]\nFpr,Tpr,thresholds = roc_curve(y_test,lgb_pred_2,pos_label=True)\nauc = roc_auc_score(y_test,lgb_pred_2)\n\n\n\nlgb_model.fit(x_train,y_train)\nlgb_pred=lgb_model.predict(x_test)\nprint(\"accuracy score is : \",accuracy_score(y_test,lgb_pred))\nprint(\"Precision is : \" ,precision_score(y_test, lgb_pred))\nprint(\"Recall is: \" ,recall_score(y_test, lgb_pred))\nprint(\"F1 Score is : \" ,f1_score(y_test, lgb_pred))\nprint(\" ROC_AUC score is \",auc)\nprint(\"classification report \\n\",classification_report(y_test,lgb_pred))\n\ncnf = confusion_matrix(y_test,lgb_pred)\nsns.heatmap(cnf, annot=True, cmap = \"magma\")\n# -\n\n# Our final model will be LGBM with stratified KFold of roc_auc_score 0.871\n\n#plotting the graph for area under curve for representing accuracy of data\nplt.plot([0,1],[1,0],'g--')\nplt.plot(Fpr,Tpr)\nplt.xlabel('False_Positive_Rate')\nplt.ylabel('True_Positive_Rate')\nplt.title(\"LGB Classifier model\")\nplt.show()\n\ndf_test.head()\n\n#Standardizing value of x by using standardscaler to make the data normally distributed\nsc = StandardScaler()\ndf_test= pd.DataFrame(sc.fit_transform(df_test),columns=df_test.columns)\n\nlead_pred_lgb=lgb_model.predict_proba(df_test)[:,1]\n\nlead_pred_lgb= pd.DataFrame(lead_pred_lgb,columns=[\"Is_Lead\"])\n\nlead_pred_lgb\n\n\n","repo_name":"Anukuzhali/Machine-Learning","sub_path":"credit card lead - classification lgbm roc auc.ipynb","file_name":"credit card lead - classification lgbm roc auc.ipynb","file_ext":"py","file_size_in_byte":14159,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"33"} +{"seq_id":"16750528477","text":"# +\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n# %matplotlib inline\nimport warnings\nwarnings.filterwarnings('ignore')\n\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.ensemble import GradientBoostingClassifier\n\nfrom sklearn.metrics import roc_curve, roc_auc_score\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import confusion_matrix\n\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.preprocessing import RobustScaler\nfrom sklearn.compose import ColumnTransformer\n\nfrom sklearn.decomposition import PCA\nfrom imblearn.combine import SMOTETomek\n\nfrom sklearn.pipeline import Pipeline\n\n# +\nfeatures_num = ['age', 'fnlwgt', 'education_num', 'capital_gain', 'capital_loss', 'hours_per_week']\nfeatures_cat = ['workclass', 'education', 'marital_status', 'occupation', 'relationship', 'race', 'sex']\n\ncolumn_arr = ['age', 'workclass', 'fnlwgt', 'education', 'education_num',\n 'marital_status', 'occupation', 'relationship', 'race', 'sex',\n 'capital_gain', 'capital_loss', 'hours_per_week', 'native_country', 'income']\n\n\n# -\n\ndef modify_columns(df_copycat):\n \n workclass_dict = {'Without-pay': 'NP_NW', 'Never-worked': 'NP_NW'}\n education_dict = {'11th': 'Below_HS', '9th': 'Below_HS', '7th-8th': 'Below_HS', '5th-6th': 'Below_HS', \n '10th': 'Below_HS', '1st-4th': 'Below_HS', 'Preschool': 'Below_HS', '12th': 'Below_HS'}\n marital_status_dict = {'Divorced': 'DSW', 'Separated': 'DSW', 'Widowed': 'DSW', 'Married-spouse-absent': 'MSA_AF', 'Married-AF-spouse': 'MSA_AF'}\n\n df_copycat['occupation'] = df_copycat['occupation'].apply(lambda x: 'Other-service' if x is '?' else x)\n df_copycat['marital_status'] = df_copycat['marital_status'].apply(lambda x: marital_status_dict[x] if x in marital_status_dict else x)\n df_copycat['education'] = df_copycat['education'].apply(lambda x: education_dict[x] if x in education_dict else x)\n df_copycat['workclass'] = df_copycat['workclass'].apply(lambda x: workclass_dict[x] if x in workclass_dict else x)\n \n df_copycat = df_copycat.drop(columns=['native_country'])\n le = LabelEncoder()\n df_copycat['income'] = le.fit_transform(df_copycat['income'])\n \n return df_copycat\n\n\ndef import_csv(path):\n return pd.read_csv(path, names=column_arr, skipinitialspace=True) \n\n\ndf_train = import_csv('./Census Income/adult.data.csv')\ndf_train = modify_columns(df_train)\nX_train = df_train.drop(columns=['income'])\ny_train = df_train['income']\nX_train.shape\n\ndf_test = import_csv('./Census Income/adult.test.csv')\ndf_test = modify_columns(df_test)\nX_test = df_test.drop(columns=['income'])\ny_test = df_test['income']\nX_test.shape\n\nX_test.sample(10, random_state=42)\n\n# ### Resampling data using Smote\n\n'''\nsmote = SMOTETomek()\nX_resampled, y_resampled = smote.fit_resample(transformer.fit_transform(X_train), y_train)\nx_pca = pca.fit_transform(X_resampled)\n'''\n\n'''\nxgb = XGBClassifier()\nxgb.fit(x_pca, y_resampled)\nxtest_pca = pca.fit_transform(transformer.transform(X_test))\nxtest_pca = pca.fit_transform(transformer.transform(X_test))\n\nxgb.score(x, y_test)\n'''\n\n# ## Model Building\n\n# ### Pipeline 1: Random Forest\n\n# +\ntransformer = ColumnTransformer(transformers=[('OneHotEncoder', OneHotEncoder(drop='first'), features_cat), \n ('RobustScaler', RobustScaler(), features_num)], \n remainder='passthrough', sparse_threshold=0)\n\npca = PCA(n_components=30)\n\nfrom sklearn.ensemble import RandomForestClassifier\nclf_rnd = RandomForestClassifier(n_estimators=100, class_weight='balanced')\n# -\n\n#pipe = Pipeline([('preprocessor', transformer), ('Data-Balancing', smote), ('PCA', pca), ('Random Forest Clf', clf_rnd)])\npipe_rfc = Pipeline([('preprocessor', transformer), ('PCA', pca), ('Random Forest Clf', clf_rnd)])\n\npipe_rfc.fit(X_train,y_train)\n\ny_pred = pipe_rfc.predict(X_test)\ny_pred_proba = pipe_rfc.predict_proba(X_test)\n\npipe_rfc.score(X_test, y_test)\n\n# +\nsns.set_style(style='darkgrid')\nfpr, tpr, threshold = roc_curve(y_test, pipe_rfc.predict_proba(X_test)[:,1])\n\nplt.plot([0,1],[0,1], linestyle = '--')\nplt.plot(fpr, tpr)\nroc_auc_score(y_test, pipe_rfc.predict_proba(X_test)[:,1])\n# -\n\nprint(classification_report(y_test, pipe_rfc.predict(X_test)))\n\ncm = confusion_matrix(y_test, pipe_rfc.predict(X_test))\nsns.heatmap(cm, annot=True, fmt='.5g')\n\n# ### Pipeline 2: XGBoost\n\ndf_train['income'].value_counts()\n\n# +\ntransformer = ColumnTransformer(transformers=[('OneHotEncoder', OneHotEncoder(drop='first'), features_cat), \n ('RobustScaler', RobustScaler(), features_num)], \n remainder='passthrough', sparse_threshold=0)\n\npca = PCA(n_components=30)\n\nfrom xgboost import XGBClassifier\n#negative class refers to the majority class (class 0) and the positive class refers to the minority class (class 1)\nclf_xgb = XGBClassifier(scale_pos_weight=3.15) #scale_pos_weight = total_negative_examples / total_positive_examples here=======scale_pos_weight=3.15\n\npipe_xgb= Pipeline([('preprocessor', transformer), ('PCA', pca), ('XGBoost Classifier', clf_xgb)])\n# -\n\npipe_xgb.fit(X_train,y_train)\n\ny_pred = pipe_xgb.predict(X_test)\npipe_xgb.score(X_test, y_test)\n\nprint(classification_report(y_test, pipe_xgb.predict(X_test)))\n\n# +\nsns.set_style(style='darkgrid')\nfpr, tpr, threshold = roc_curve(y_test, pipe_xgb.predict_proba(X_test)[:,1])\n\nplt.plot([0,1],[0,1], linestyle = '--')\nplt.plot(fpr, tpr)\nroc_auc_score(y_test, pipe_xgb.predict_proba(X_test)[:,1])\n# -\n\ncm = confusion_matrix(y_test, pipe_xgb.predict(X_test))\nsns.heatmap(cm, annot=True, fmt='.5g')\n\n# ### Pipeline 3: Gradinet Boost\n\n# +\ntransformer = ColumnTransformer(transformers=[('OneHotEncoder', OneHotEncoder(drop='first'), features_cat), \n ('RobustScaler', RobustScaler(), features_num)], \n remainder='passthrough', sparse_threshold=0)\n\npca = PCA(n_components=30)\n\nfrom sklearn.ensemble import GradientBoostingClassifier\nclf_gbm = GradientBoostingClassifier()\n\npipe_gbm= Pipeline([('preprocessor', transformer), ('PCA', pca), ('GBM Classifier', clf_gbm)])\n\n# +\npipe_gbm.fit(X_train,y_train)\n\ny_pred = pipe_gbm.predict(X_test)\npipe_gbm.score(X_test, y_test)\n# -\n\nprint(classification_report(y_test, pipe_gbm.predict(X_test)))\n\n# +\nsns.set_style(style='darkgrid')\nfpr, tpr, threshold = roc_curve(y_test, pipe_gbm.predict_proba(X_test)[:,1])\n\nplt.plot([0,1],[0,1], linestyle = '--')\nplt.plot(fpr, tpr)\nroc_auc_score(y_test, pipe_gbm.predict_proba(X_test)[:,1])\n# -\n\ncm = confusion_matrix(y_test, pipe_gbm.predict(X_test))\nsns.heatmap(cm, annot=True, fmt='.5g')\n\n# ## Using XGBoost to export test results\n\npipe_xgb.fit(X_train,y_train)\ny_pred = pipe_xgb.predict(X_test)\npipe_xgb.score(X_test, y_test)\n\nprint(classification_report(y_test, pipe_xgb.predict(X_test)))\n\n# +\nsns.set_style(style='darkgrid')\nfpr, tpr, threshold = roc_curve(y_test, pipe_xgb.predict_proba(X_test)[:,1])\n\nplt.plot([0,1],[0,1], linestyle = '--')\nplt.plot(fpr, tpr)\nroc_auc_score(y_test, pipe_xgb.predict_proba(X_test)[:,1])\n# -\n\ncm = confusion_matrix(y_test, pipe_xgb.predict(X_test))\nsns.heatmap(cm, annot=True, fmt='.5g')\n\nnp.savetxt(\"predicted.csv\", y_pred, fmt='%d', delimiter=\",\")\n\n\n","repo_name":"eyesquare-u/Income_Classification","sub_path":"Model and Pipeline Creation.ipynb","file_name":"Model and Pipeline Creation.ipynb","file_ext":"py","file_size_in_byte":7395,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"33"} +{"seq_id":"70157862495","text":"import numpy as np\nimport pandas as pd\nimport folium\nfrom geopy.geocoders import Nominatim\nfrom geopy import distance,Point\n\ndf=pd.read_csv('dc.csv')\n#df[df['NB_COM']==\"GASOL BP FELIX CU A8\"]\n\ndf=df.drop(\"index\",axis=1)\ndf=df.groupby(['NB_COM','CP'],as_index=False).count()\n#df.sort_values(by=\"IM_TR\",ascending=False)\ndf[df['IM_TR']==6]\n\ndf=df.sort_values(by=\"IM_TR\",ascending=True)\n#str(df['CP'].iloc[7])[-5:]\ndf[df['IM_TR']==6]\n\ndf['CP']=df[\"CP\"].apply(lambda x: str(x)[-5:])\ndf\n\nnom=Nominatim(timeout=10)\ndf['dir']=df['CP']+\",\"+\"mexico\"\ndf.head()\n\n#df['dir']=df['dir'].apply(lambda x: x.replace(\" ,\",\",\").replace(\", \",\",\"))\n#geo=df['dir'].apply(lambda x: nom.geocode(x))df['dir']=df['dir'].apply(lambda x: x.replace(\" ,\",\",\").replace(\", \",\",\"))\n#geo=df['dir'][0:10].apply(lambda x: nom.geocode(x))\n##df['CP2']=df['CP'].apply(lambda x: str(x)[1:])\n#df['dir2']=df['CP2']+\",\"+\"mexico\"\n#df.head()\nnom.geocode(df['dir'].iloc[20])\n\ngeo=df['dir'].apply(lambda x: nom.geocode(x))\n\nlat=list([x.latitude for x in geo if x!=None])\nlong=list([x.longitude for x in geo if x!=None])\nind=np.where(np.array(geo)!=None)\ncost=df['NB_COM'].iloc[ind]\ntrx=df['IM_TR'].iloc[ind]\n\n\n# +\nmap=folium.Map(location=[lat[0], long[0]], zoom_start=13)\nfg=folium.FeatureGroup(name=\"Comercio\")\nfor lt, ln,ct,tr in zip(lat, long,cost,trx):#, elev, name):\n #iframe = folium.IFrame(html=html % (name, name, el), width=200, height=100)\n fg.add_child(folium.Marker(location=[lt, ln],popup=\"Comercio:\"+str(ct)+\" \"+\"n_trax:\"+str(tr), icon = folium.Icon(color = \"green\")))\n#fg.add_child(folium.Marker(location=[lat[1], long[1]],popup=\"cp\",icon=folium.Icon(color='red'))) \n \n#fg.add_child(folium.Marker(location=[ma.latitude, ma.longitude],popup=\"ma\",icon=folium.Icon(color='red')))\n#fg.add_child(folium.Marker(location=[sc.latitude, sc.longitude],popup=\"sc\",icon=folium.Icon(color='red')))\nmap.add_child(fg)\n# -\n\ndf.sort_values(by=\"IM_TR\",ascending=False)\n\ngeo\n\ndf['NB_COM']\n\n\n","repo_name":"abraham314/app2","sub_path":"geocoder_app/micomp.ipynb","file_name":"micomp.ipynb","file_ext":"py","file_size_in_byte":1981,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"33"} +{"seq_id":"6292058556","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# %matplotlib widget\n\n# ## Gradient Descent\n#\n# Simple Gradient Descent involves starting from an arbitrary point, and moving in the direction opposite to the maximum gradient\n#\n# $$\\begin{align}\n# &{\\rm algorithm\\; G{\\scriptsize RADIENT}\\text{-D}{\\scriptsize ESCENT}}\\; (\\theta^{(0)}, \\eta, \\mathcal{L}):\\\\\n# &t \\leftarrow 0 \\\\\n# &\\text{do} \\\\\n# &\\quad \\theta^{(t+1)} \\leftarrow \\theta^{(t)} - \\eta \\; \\nabla_\\theta \\mathcal{L}(\\theta^{(t)}) \\\\\n# &\\quad t \\leftarrow t+1 \\\\\n# &\\text{while not converged} \\\\\n# &\\text{return }\\theta^{(t)} \n# \\end{align}\n# $$\n#\n# $\\eta$ defines the learning rate, while $\\mathcal{L}$ is the loss function\n#\n# Here, we do a simple univariate regression on a random sample from the [Combined Cycle Power Plant Data Set](https://archive.ics.uci.edu/ml/datasets/Combined+Cycle+Power+Plant). \n\nccpp_all_samples = pd.read_csv('../data/CCPP/output.csv')\nccpp_all_samples.info()\n\n\ndf = ccpp_all_samples.sample(500)\ndf.head()\n\nx = df['AT'].to_numpy()\ny = df['PE'].to_numpy()\n#y = (y - y.mean())/y.std()\n#x = (x - x.mean())/x.std()\n\nplt.scatter(x,y)\n\n\n# Data seems nice: simple, linearly dependent and homoscedastic. Let's make a loss function for this\n\n# +\ndef loss(x, y, theta_0, theta_1):\n return (((y-theta_0-theta_1*x)**2)/(2*len(y))).sum()\n\ndef grad_loss(weights, theta_0, theta_1):\n (x,y) = weights\n return (-(y-theta_0-theta_1*x).mean(),(-x*(y-theta_0-theta_1*x)).mean())\n\ndef grad_loss_0(x, y, theta_0, theta_1):\n return -(y-theta_0-theta_1*x).mean()\n\ndef grad_loss_1(x, y, theta_0, theta_1):\n return (-x*(y-theta_0-theta_1*x)).mean()\n\n\n# -\n\n# And now plot the contours so we get an idea of our parameters\n\n# +\ntheta_0_space = np.linspace(480,520,80)\ntheta_1_space = np.linspace(-3,-1.5,80)\ntheta_space = np.meshgrid(theta_0_space, theta_1_space)\n\nvector_loss = np.vectorize(loss, signature='(m),(m),(),()->()')\nloss_space = vector_loss(x, y, theta_space[0], theta_space[1])\n\nfig = plt.figure(figsize=(5,5), dpi=150)\nax = plt.axes(projection='3d')\nax.plot_surface(theta_space[0], theta_space[1], loss_space, cmap='viridis', edgecolor=None)\n#ax.contour3D(theta_space[0], theta_space[1], loss_space, 50, cmap='binary')\nax.set_xlabel('theta_0')\nax.set_ylabel('theta_1')\nax.set_zlabel('loss')\n\n#CS = plt.contour(theta_0_space, theta_1_space, loss_space)\n#plt.clabel(CS, fmt = '%2.1d', colors = 'k', fontsize=14) #contour line labels\n#plt.quiver(theta_0_space,theta_1_space,grad_loss_space_0,grad_loss_space_1)\n# -\n\n# now the GD algo\ndef gradient_descent(params, theta_0, theta_1, grad_loss, eta, t_lim=1000):\n \n theta_0_pts = [theta_0]\n theta_1_pts = [theta_1]\n \n t = 0\n \n while t < t_lim:\n loss_grad = grad_loss(params, theta_0_pts[-1], theta_1_pts[-1])\n #print(loss_grad)\n theta_0_n = theta_0_pts[-1] - eta*loss_grad[0]\n theta_1_n = theta_1_pts[-1] - eta*loss_grad[1]\n \n if (abs(theta_0_n-theta_0_pts[-1]) < 0.00001 and abs(theta_1_n-theta_1_pts[-1]) < 0.00001):\n break\n \n theta_0_pts.append(theta_0_n)\n theta_1_pts.append(theta_1_n)\n \n t += 1\n \n return (theta_0_pts, theta_1_pts)\n\n\n# +\nfig = plt.figure(figsize=(5,5), dpi=150)\nax = plt.axes(projection='3d')\n\ngd_pts = gradient_descent((x,y),480,-3,grad_loss,0.001,t_lim=100000)\ngd_loss = [loss(x,y,gd_pt[0],gd_pt[1]) for gd_pt in zip(gd_pts[0],gd_pts[1])]\nax.plot3D(gd_pts[0], gd_pts[1], gd_loss, color='r', marker='.')\n\nax.plot_surface(theta_space[0], theta_space[1], loss_space, rstride=1, cstride=1, cmap='viridis', edgecolor=None, alpha=0.5)\n#ax.contour3D(theta_space[0], theta_space[1], loss_space, 50, cmap='binary')\nax.set_xlabel('theta_0')\nax.set_ylabel('theta_1')\nax.set_zlabel('loss')\n#plt.savefig('grad_not_perp.png')\n# -\n\n# See [Goodfellow et al, Chp4](https://www.deeplearningbook.org/contents/numerical.html). Note that our parameter space seems like a simple elliptic paraboloid, but it's a bit more complicated; rather than two, this one has 500 axes (for different values of $y^{(i)}$ and $x^{(i)}$). Here's an example, where we fit the following curve to the loss data and do gradient descent on it:\n#\n# $$t(\\vec{\\theta},(x,y)) = \\theta_0 + \\theta_1 x^2 + \\theta_2 y^2 + \\theta_3 xy + \\theta_4 x + \\theta_5 y$$\n#\n# Using the notation from bishop, this gives us\n#\n# $$\\phi^T((x,y)) = (1,x^2,y^2,xy,x,y)$$\n#\n# which is our feature vector. I'll use the closed form of regression to fit to this, rather than do gradient descent.\n#\n# Note this is not really relevant; it just gives me an excuse to do some polynomial regression\n\n# +\n# points to fit\nts_pts = np.squeeze(np.dstack([theta_space[0].ravel(), theta_space[1].ravel()]))\nfit_pts = loss_space.ravel()\n\ndef f(theta,x,y):\n return theta.T@phi((x,y))\n\ndef phi(p):\n x,y = p\n return np.array([1,x*x,y*y,x*y,x,y])\n\ndef design_mat(x_all,phi):\n return np.vstack([phi(p) for p in x_all])\n\ndef theta(Phi,t):\n return np.linalg.pinv(Phi)@t\n\nfig = plt.figure(figsize=(5,5), dpi=150)\nax = plt.axes(projection='3d')\n\nth = theta(design_mat(ts_pts,phi),fit_pts)\nvector_f = np.vectorize(f, signature='(m),(),()->()')\nfitted_loss_space = vector_f(th, theta_space[0], theta_space[1])\n\nax.plot_surface(theta_space[0], theta_space[1], fitted_loss_space, cmap='viridis', edgecolor=None, alpha=0.5)\n\ndef grad_mv(theta,x,y):\n return (theta[4]+theta[3]*y+2*theta[1]*x,theta[5]+theta[3]*x+2*theta[2]*y)\n\ngd_pts = gradient_descent(th,480,-3,grad_mv,0.001,t_lim=100000)\ngd_loss = [f(th,gd_pt[0],gd_pt[1]) for gd_pt in zip(gd_pts[0],gd_pts[1])]\nax.plot3D(gd_pts[0], gd_pts[1], gd_loss, color='r', marker='.')\n# -\n\n\n","repo_name":"Aniruddha-Deb/MLZoo","sub_path":"gradient_descent/grad_descent.ipynb","file_name":"grad_descent.ipynb","file_ext":"py","file_size_in_byte":5675,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-jupyter-script","pt":"33"} +{"seq_id":"16688515913","text":"s1={1,2,3,4}\ns2={3,4,5,6}\nres1=s1.union(s2)\nprint(res1)\nres2=s1.intersection(s2)\nprint(res2)\nres3=s1.difference(s2)#the difference is not updated in the set s1 and returns the elements which are different from s2\nprint(res3)\nprint(s1)\nres4=s1.difference_update(s2)#the difference is updated in the set s1\nprint(res4)\nprint(s1)\n\nnumber=int(input())\nif(number&1==0):\n print(number,\" is an even number\")\nelse:\n print(number,\" is an odd number\")\n\nprint('EVEN') if int(input())&1==0 else print(\"ODD\")\n\nday=int(input())\nif(day==1):\n print('SUNDAY')\nelif(day==2):\n print('MONDAY')\nelif(day==3):\n print('TUESDAY')\nelif(day==4):\n print('WEDNESDAY')\nelif(day==5):\n print('THURSDAY')\nelif(day==6):\n print('FRIDAY')\nelif(day==7):\n print('SATURDAY')\nelse:\n print('INVALID')\n\nnumber=int(input())\nif(number>0 and number<20):\n if(number&1==0):\n print(\"WEIRD NUMBER\")\n else:\n print(\"NORMAL NUMBER\")\nelif(number>=20 and number<30):\n print('NORMAL NUMBER')\nelif(number>=30 and number&1==1):\n print('NORMAL NUMBER')\nelif(number>=30 and number&1==0):\n print('WEIRD NUMBER')\n\n\nd={}\nd.update({585:\"Tanuja\"})\nd.update({574:'Pavani'})\nprint(d)\nprint(d.get(585))\n\nlist1=[1,4,5,6,7,10]\nnum=int(input())\nfor i in range(len(list1)):\n if(num==list1[i]):\n print(i)\n break\nelse:\n print(-1)\n\nl1=[]\nfor i in range(10):\n l1.append(i)\nprint(l1)\n\nx=[i for i in range(1,101) if i%7==0 and i%11==0]\nx\n\nli=list(map(int,input().split()))\nfor i in range(len(li)-1,-1,-1):\n print(li[i],end=' ')\n\nl=list(map(int,input().split()))\ns=0\nfor i in l:\n s+=i\nprint(s)\n\n\n","repo_name":"20A31A0585/Training","sub_path":"day2.ipynb","file_name":"day2.ipynb","file_ext":"py","file_size_in_byte":1607,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"33"} +{"seq_id":"17257848939","text":"# +\nimport os\nnDivCnt = 100000\n\nfilepath = \"C:/SR/py/project3_park/rawdata/csv/\"\nfileName = 'DAUM_CAFE_국립공원'\nfileExe = \".csv\"\nfileFolder = \"csv2/\"\n# -\n\n# ### nDivent : ~개마다 쪼갤지 정하는 것 ex) nDivCnt = 20000 : 20000개마다 쪼개기\n\ndirname = filepath + fileFolder\nif not os.path.isdir(dirname):\n os.mkdir(dirname)\n\nnLineCnt = 0\nnFileIdx = 0\n\nf = open(\"%s\" % (filepath + fileName + fileExe), 'r', encoding='utf-8-sig')\nfDivName = open (\"%s%06d%s\" % (filepath + fileName, nFileIdx, fileExe), 'w', encoding='utf-8-sig')\nwhile True:\n line = f.readline()\n if not line: break\n \n if nLineCnt == nDivCnt :\n fDivName.close()\n nFileIdx += 1\n nLineCnt = 0\n strPat = \"%s%06d%s\" % (filepath + fileFolder + fileName, nFileIdx, fileExe)\n fDivName = open(strPat , 'w', encoding='utf-8-sig')\n print(\"생성 완료 %s\" % strPat)\n nLineCnt += 1\n fDivName.write(line)\n #Print(line)\nfDivName.close()\nf.close()\n\n\n","repo_name":"dnjsqoqkqh/Random-Forest","sub_path":"엑셀파일쪼개기.ipynb","file_name":"엑셀파일쪼개기.ipynb","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"33"} +{"seq_id":"159722138","text":"# +\nimport random\nimport networkx as nx\nimport matplotlib.pyplot as plt\n# from networkx.drawing.nx_agraph import graphviz_layout\nfrom networkx.drawing.nx_pydot import pydot_layout\n\nnodes = 20\ndepth = 3\n\nclass Node:\n def __init__(self, id, depth):\n self.id = id\n self.depth = depth\n\nroot = Node(1, 1)\nnodenum = 2\ngraph = nx.Graph()\ngraph.add_node(root)\n\nwhile nodenum <= nodes:\n while True:\n random_node = random.choice(list(graph.nodes))\n if random_node.depth <= depth - 1:\n break\n new_node = Node(nodenum, random_node.depth + 1)\n graph.add_node(new_node)\n graph.add_edge(random_node, new_node)\n nodenum += 1\n\nvertex_labels = {}\nedge_labels = {}\n\n# pos = pydot_layout(graph, prog='dot')\n\nnx.draw_networkx(graph, labels=vertex_labels, node_size=500)\nplt.show()\n# -\n\n20 / 19\n\n# +\nimport random\nimport networkx as nx\nimport matplotlib.pyplot as plt\n# from networkx.drawing.nx_agraph import graphviz_layout\nfrom networkx.drawing.nx_pydot import pydot_layout\n\nnodes = 20\ndepth = 5\nmax_branches = nodes / (depth - 1)\n\nclass Node:\n def __init__(self, id, depth):\n self.id = id\n self.depth = depth\n\nroot = Node(1, 1)\nnodenum = 2\ngraph = nx.Graph()\ngraph.add_node(root)\n\nleaves = {root.id: root}\nbranches = 1\n\ndef is_branching_possible():\n return max_branches - branches >= 0\n\nwhile nodenum <= nodes:\n while True:\n # print(is_branching_possible(), max_branches, branches)\n if is_branching_possible():\n random_node = random.choice(list(graph.nodes))\n \n if random_node.depth <= depth - 1:\n break\n else:\n random_node_id = random.choice(list(leaves))\n random_node = leaves[random_node_id]\n break\n\n new_node = Node(nodenum, random_node.depth + 1)\n graph.add_node(new_node)\n graph.add_edge(random_node, new_node)\n nodenum += 1\n\n leaves[new_node.id] = new_node\n if(random_node.id in leaves):\n del leaves[random_node.id]\n else: \n branches = branches+1\n\nvertex_labels = {}\nedge_labels = {}\n\n# pos = pydot_layout(graph, prog='dot')\n\nnx.draw_networkx(graph, labels=vertex_labels, node_size=500)\nplt.show()\n\n# -\n\nnx.random_tree(20)\nnx.draw_networkx(graph, labels={}, node_size=500)\n\n# +\nwanted1 = 6\nwanted2 = 10\nwanted3 = 17\nallwanted = sum([wanted1, wanted2, wanted3])\n\ndef calc(wanted, nodeAmount, allwanted):\n return (wanted - nodeAmount) / allwanted\n\ncalc(wanted3, 0, allwanted),calc(wanted2, 0, allwanted),calc(wanted1, 0, allwanted), calc(wanted3, 0, allwanted)+calc(wanted2, 0, allwanted)+calc(wanted1, 0, allwanted)\n\n# +\nmaxBranchAmountPerBranch = 4\nminBranchAmountPerBranch = 2\n\nminBranches = (wanted1 + wanted2 + wanted3) * 2\n\n\n# +\nimport random\n \ndef print_tree_edges(prufer, m):\n vertices = m + 2\n vertex_set = [0] * vertices\n \n # Initialize the array of vertices\n for i in range(vertices):\n vertex_set[i] = 0\n \n # Number of occurrences of vertex in code\n for i in range(vertices - 2):\n vertex_set[prufer[i] - 1] += 1\n \n print(\"\\nThe edge set E(G) is:\")\n \n j = 0\n \n # Find the smallest label not present in prufer[].\n for i in range(vertices - 2):\n for j in range(vertices):\n # If j+1 is not present in prufer set\n if vertex_set[j] == 0:\n # Remove from Prufer set and print pair.\n vertex_set[j] = -1\n print(\"({}, {})\".format(j + 1, prufer[i]), end=\" \")\n \n vertex_set[prufer[i] - 1] -= 1\n \n break\n \n j = 0\n \n # For the last element\n for i in range(vertices):\n if vertex_set[i] == 0 and j == 0:\n print(\"({}, \".format(i + 1), end=\"\")\n j += 1\n elif vertex_set[i] == 0 and j == 1:\n print(\"{})\".format(i + 1))\n \ndef generate_random_tree(n):\n length = n - 2\n arr = [0] * length\n \n # Generate random array\n for i in range(length):\n arr[i] = random.randint(1, length + 1)\n \n print_tree_edges(arr, length)\n \n# Driver code\nn = 5\ngenerate_random_tree(n)\n\n# +\nimport random\nimport networkx as nx\nimport matplotlib.pyplot as plt\n# from networkx.drawing.nx_agraph import graphviz_layout\nfrom networkx.drawing.nx_pydot import pydot_layout\n\nnodes = 20\ndepth = 2\n\nclass Node:\n def __init__(self, id, depth):\n self.id = id\n self.depth = depth\n\nroot = Node(1, 1)\nnodenum = 2\ngraph = nx.Graph()\ngraph.add_node(root)\n\nwhile nodenum <= nodes:\n while True:\n random_node = random.choice(list(graph.nodes))\n if random_node.depth <= depth - 1:\n break\n new_node = Node(nodenum, random_node.depth + 1)\n graph.add_node(new_node)\n graph.add_edge(random_node, new_node)\n nodenum += 1\n\nvertex_labels = {}\nedge_labels = {}\n\n# pos = pydot_layout(graph, prog='dot')\n\nnx.draw_networkx(graph, labels=vertex_labels, node_size=500)\nplt.show()\n\n\n# +\nimport random\n\nclass TreeNode:\n def __init__(self, value):\n self.value = value\n self.children = []\n\ndef display_tree(root, level=0):\n if root is None:\n return\n\n print(\" \" * level + str(root.value)) # Display the current node value\n\n for child in root.children:\n display_tree(child, level + 1) # Recursively display each child\n\ndef generate_random_tree(depth, outdegree, nodes):\n if depth <= 0 or outdegree <= 0 or nodes <= 0:\n return None\n\n root = TreeNode(random.randint(1, 100)) # Generate a random value for the root node\n\n if depth == 1:\n return root\n\n # Generate children for the root node\n num_children = min(outdegree, nodes - 1)\n nodes -= num_children\n for _ in range(num_children):\n child = generate_random_tree(depth - 1, outdegree, nodes)\n if child:\n root.children.append(child)\n\n # Generate children for the rest of the nodes\n for child in root.children:\n num_children = min(outdegree, nodes)\n nodes -= num_children\n for _ in range(num_children):\n grandchild = generate_random_tree(depth - 1, outdegree, nodes)\n if grandchild:\n child.children.append(grandchild)\n\n return root\n\n# Example usage:\nrandom_tree = generate_random_tree(depth=3, outdegree=2, nodes=10)\ndisplay_tree(random_tree)\n\n# -\n\n\n\n# +\nimport sys\n\nnx.drawing.nx_pydot.write_dot(graph,sys.stdout)\n","repo_name":"HTW-ALADIN/GraphGrammar","sub_path":"graphgrammartests.ipynb","file_name":"graphgrammartests.ipynb","file_ext":"py","file_size_in_byte":6341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"33"} +{"seq_id":"2640195349","text":"# **Chapter 3 – Classification**\n#\n# _This notebook contains all the sample code and solutions to the exercises in chapter 3._\n\n# # Setup\n# First, let's make sure this notebook works well in both python 2 and 3, import a few common modules, ensure MatplotLib plots figures inline and prepare a function to save the figures:\n\n# +\n# To support both python 2 and python 3\nfrom __future__ import division, print_function, unicode_literals\n\n# Common imports\nimport numpy as np\nimport os\n\n# to make this notebook's output stable across runs\nnp.random.seed(42)\n\n# To plot pretty figures\n# %matplotlib inline\nimport matplotlib\nimport matplotlib.pyplot as plt\nplt.rcParams['axes.labelsize'] = 14\nplt.rcParams['xtick.labelsize'] = 12\nplt.rcParams['ytick.labelsize'] = 12\n\n# Where to save the figures\nPROJECT_ROOT_DIR = \".\"\nCHAPTER_ID = \"classification\"\n\ndef save_fig(fig_id, tight_layout=True):\n path = os.path.join(PROJECT_ROOT_DIR, \"images\", CHAPTER_ID, fig_id + \".png\")\n print(\"Saving figure\", fig_id)\n if tight_layout:\n plt.tight_layout()\n plt.savefig(path, format='png', dpi=300)\n\n\n# -\n\n# # MNIST\n\nfrom sklearn.datasets import fetch_mldata\nmnist = fetch_mldata('MNIST original',data_home='./datasets')\nmnist\n\nX, y = mnist[\"data\"], mnist[\"target\"]\nX.shape\n\ny.shape\n\n# +\n# %matplotlib inline\nimport matplotlib\nimport matplotlib.pyplot as plt\n\ndigit_5 = X[36000]\ndigit_5_image = digit_5.reshape(28, 28)\nplt.imshow(digit_5_image, cmap = matplotlib.cm.binary,\n interpolation=\"nearest\")\nplt.axis(\"on\")\nsave_fig(\"some_digit_plot\")\n# -\n\ny[36000]\n\n\ndef plot_digit(data):\n image = data.reshape(28, 28)\n plt.imshow(image, cmap = matplotlib.cm.binary,\n interpolation=\"nearest\")\n plt.axis(\"off\")\n\n\n# EXTRA\ndef plot_digits(instances, images_per_row=10, **options):\n size = 28\n images_per_row = min(len(instances), images_per_row)\n images = [instance.reshape(size,size) for instance in instances]\n n_rows = (len(instances) - 1) // images_per_row + 1\n row_images = []\n n_empty = n_rows * images_per_row - len(instances)\n images.append(np.zeros((size, size * n_empty)))\n for row in range(n_rows):\n rimages = images[row * images_per_row : (row + 1) * images_per_row]\n row_images.append(np.concatenate(rimages, axis=1))\n image = np.concatenate(row_images, axis=0)\n plt.imshow(image, cmap = matplotlib.cm.binary, **options)\n plt.axis(\"off\")\n\n\nplt.figure(figsize=(9,9))\nexample_images = np.r_[X[:12000:600], X[13000:30600:600], X[30600:60000:590]] # X是(70000, 784)数组,按行操作,从0到12000行,每个600采一个行数据\nexample_images.shape\n\nplot_digits(example_images, images_per_row=10)\nsave_fig(\"more_digits_plot\")\nplt.show()\n\n# +\nX_train, X_test, y_train, y_test = X[:60000], X[60000:], y[:60000], y[60000:] #行操作\nimport numpy as np\n\nshuffle_index = np.random.permutation(60000)\nX_train, y_train = X_train[shuffle_index], y_train[shuffle_index]\n# -\n\n# # Binary classifier\n\n#将0-9数字标签转为bool型标签,“5”和“非5”\ny_train_5 = (y_train == 5)\ny_test_5 = (y_test == 5)\n\n# +\nfrom sklearn.linear_model import SGDClassifier\n\nsgd_clf = SGDClassifier(random_state=42)\nsgd_clf.fit(X_train, y_train_5)\n# -\n\nsgd_clf.predict([digit_5])\n\nfrom sklearn.model_selection import cross_val_score\ncross_val_score(sgd_clf, X_train, y_train_5, cv=3, scoring=\"accuracy\")\n\n# +\n#与cross_val_score大致相同\n#每个折叠由StratifiedKFold执行分层抽样(见第2章)产生,其所包含的各个类的比例符合整体比例\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.base import clone\n\nskfolds = StratifiedKFold(n_splits=3, random_state=42)\n\nfor train_index, test_index in skfolds.split(X_train, y_train_5):\n clone_clf = clone(sgd_clf) #每个迭代会创建一个分类器的副本\n X_train_folds = X_train[train_index]\n y_train_folds = (y_train_5[train_index])\n X_test_fold = X_train[test_index]\n y_test_fold = (y_train_5[test_index])\n\n clone_clf.fit(X_train_folds, y_train_folds)\n y_pred = clone_clf.predict(X_test_fold) #用分类器的副本进行预测\n n_correct = sum(y_pred == y_test_fold)\n print(n_correct / len(y_pred))\n# -\n\n#返回的不是评估分数,而是每个折叠的预测\nfrom sklearn.model_selection import cross_val_predict\ny_train_pred = cross_val_predict(sgd_clf, X_train, y_train_5, cv=3)\ny_train_pred\n\n\n#获取混淆矩阵\nfrom sklearn.metrics import confusion_matrix\nconfusion_matrix(y_train_5, y_train_pred)\n\nfrom sklearn.metrics import precision_score, recall_score\n#精度\nprecision_score(y_train_5, y_train_pred)\n\n#召回率\nrecall_score(y_train_5, y_train_pred)\n\n#F1分数\nfrom sklearn.metrics import f1_score\nf1_score(y_train_5, y_train_pred)\n\n# +\n\ny_scores = cross_val_predict(sgd_clf, X_train, y_train_5, cv=3,\n method=\"decision_function\")#返回预测分数\ny_scores.shape\n\n# +\n##计算所有可能的阈值的精度和召回率\nfrom sklearn.metrics import precision_recall_curve\n\nprecisions, recalls, thresholds = precision_recall_curve(y_train_5, y_scores[:,1])\n\n\n# +\ndef plot_precision_recall_vs_threshold(precisions, recalls, thresholds):\n plt.plot(thresholds, precisions[:-1], \"b--\", label=\"Precision\", linewidth=2)\n plt.plot(thresholds, recalls[:-1], \"g-\", label=\"Recall\", linewidth=2)\n plt.xlabel(\"Threshold\", fontsize=16)\n plt.legend(loc=\"upper left\", fontsize=16)\n plt.ylim([0, 1])\n\nplt.figure(figsize=(8, 4))\nplot_precision_recall_vs_threshold(precisions, recalls, thresholds)\nplt.xlim([-700000, 700000])\nsave_fig(\"precision_recall_vs_threshold_plot\")\nplt.show()\n\n\n# +\n#绘制精度和召回率的函数图\ndef plot_precision_vs_recall(precisions, recalls):\n plt.plot(recalls, precisions, \"b-\", linewidth=2)\n plt.xlabel(\"Recall\", fontsize=16)\n plt.ylabel(\"Precision\", fontsize=16)\n plt.axis([0, 1, 0, 1])\n\nplt.figure(figsize=(8, 6))\nplot_precision_vs_recall(precisions, recalls)\nsave_fig(\"precision_vs_recall_plot\")\nplt.show()\n\n# +\n#计算多种阈值的TPR和FPR\nfrom sklearn.metrics import roc_curve\n\nfpr, tpr, thresholds = roc_curve(y_train_5, y_scores[:, 1])\n#绘图\ndef plot_roc_curve(fpr, tpr, label=None):\n plt.plot(fpr, tpr, linewidth=2, label=label)\n plt.plot([0, 1], [0, 1], 'k--')\n plt.axis([0, 1, 0, 1])\n plt.xlabel('False Positive Rate', fontsize=16)\n plt.ylabel('True Positive Rate', fontsize=16)\n\nplt.figure(figsize=(8, 6))\nplot_roc_curve(fpr, tpr)\nsave_fig(\"roc_curve_plot\")\nplt.show()\n\n# +\n#测量曲线下面积(AUC)\nfrom sklearn.metrics import roc_auc_score\n\nroc_auc_score(y_train_5, y_scores[:, 1])\n\n# +\n#创建一个随机森林分类器,观察其ROC曲线\nfrom sklearn.ensemble import RandomForestClassifier\nforest_clf = RandomForestClassifier(random_state=42)\ny_probas_forest = cross_val_predict(forest_clf, X_train, y_train_5, cv=3,\n method=\"predict_proba\")\ny_scores_forest = y_probas_forest[:, 1] # score = proba of positive class\nfpr_forest, tpr_forest, thresholds_forest = roc_curve(y_train_5,y_scores_forest)\n\nplt.figure(figsize=(8, 6))\nplt.plot(fpr, tpr, \"b:\", linewidth=2, label=\"SGD\")\nplot_roc_curve(fpr_forest, tpr_forest, \"Random Forest\")\nplt.legend(loc=\"lower right\", fontsize=16)\nsave_fig(\"roc_curve_comparison_plot\")\nplt.show()\n# -\n\n# # 多类别分类器\n\nsgd_clf.fit(X_train, y_train)\nsgd_clf.predict([digit_5])\n\nsome_digit_scores = sgd_clf.decision_function([digit_5])\nsome_digit_scores\n\n#目标类别的列表\nsgd_clf.classes_\n\nfrom sklearn.multiclass import OneVsOneClassifier\novo_clf = OneVsOneClassifier(SGDClassifier(random_state=42))\novo_clf.fit(X_train, y_train)\novo_clf.predict([digit_5])\n\n#采用一对一,一共训练了45个分类器\nlen(ovo_clf.estimators_)\n\nforest_clf.fit(X_train, y_train)\nforest_clf.predict([digit_5])\nforest_clf.predict_proba([digit_5])#predict_proba()可以获得分类器将每个实例分类为每个类别的概率列表\n\n# # 错误分析\n\ny_train_pred = cross_val_predict(sgd_clf, X_train, y_train, cv=3)\nconf_mx = confusion_matrix(y_train, y_train_pred)\nconf_mx\n\nplt.matshow(conf_mx, cmap=plt.cm.gray)\nplt.show()\n\n# +\n#我们比较的应该是错误率而不是错误的绝对值\nrow_sums = conf_mx.sum(axis=1, keepdims=True)\nnorm_conf_mx = conf_mx / row_sums\n\nnp.fill_diagonal(norm_conf_mx, 0)\nplt.matshow(norm_conf_mx, cmap=plt.cm.gray)\nsave_fig(\"confusion_matrix_errors_plot\", tight_layout=False)\nplt.show()\n\n# +\ncl_a, cl_b = 3, 5\nX_aa = X_train[(y_train == cl_a) & (y_train_pred == cl_a)]\nX_ab = X_train[(y_train == cl_a) & (y_train_pred == cl_b)]\nX_ba = X_train[(y_train == cl_b) & (y_train_pred == cl_a)]\nX_bb = X_train[(y_train == cl_b) & (y_train_pred == cl_b)]\n\nplt.figure(figsize=(8,8))\nplt.subplot(221); plot_digits(X_aa[:25], images_per_row=5)\nplt.subplot(222); plot_digits(X_ab[:25], images_per_row=5)\nplt.subplot(223); plot_digits(X_ba[:25], images_per_row=5)\nplt.subplot(224); plot_digits(X_bb[:25], images_per_row=5)\nsave_fig(\"error_analysis_digits_plot\")\nplt.show()\n# -\n\n# # Multilabel classification多标签\n\n# +\nfrom sklearn.neighbors import KNeighborsClassifier#KNeighborsClassifier实例,它支持多标签分类,不是所有的分类器都支持\n\ny_train_large = (y_train >= 7)#创建标签,数字是否大于等于7\ny_train_odd = (y_train % 2 == 1)# 是否为奇数\ny_multilabel = np.c_[y_train_large, y_train_odd]\n\nknn_clf = KNeighborsClassifier()\nknn_clf.fit(X_train, y_multilabel)\n# -\n\n#结果是正确的!数字5确实不大(False),为奇数(True)\nknn_clf.predict([digit_5])\n\n# # Multioutput classification多输出\n\n# +\nnoise = np.random.randint(0, 100, (len(X_train), 784))\nX_train_mod = X_train + noise\nnoise = np.random.randint(0, 100, (len(X_test), 784))\nX_test_mod = X_test + noise\ny_train_mod = X_train\ny_test_mod = X_test\n\n#观察一下其中一个数据\nsome_index = 5500\nplt.subplot(121); plot_digit(X_test_mod[some_index])\nplt.subplot(122); plot_digit(y_test_mod[some_index])\nsave_fig(\"noisy_digit_example_plot\")\nplt.show()\n# -\n\nknn_clf.fit(X_train_mod, y_train_mod)\nclean_digit = knn_clf.predict([X_test_mod[some_index]])\nplot_digit(clean_digit)\nsave_fig(\"cleaned_digit_example_plot\")\n\n\n","repo_name":"liuzheCSDN/Scikit-Learn","sub_path":"3_classification.ipynb","file_name":"3_classification.ipynb","file_ext":"py","file_size_in_byte":10146,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-jupyter-script","pt":"33"} +{"seq_id":"44097703222","text":"# +\nimport pandas as pd\n\naudio_df = pd.read_csv(\"audio/respiratory_sound_database/Respiratory_Sound_Database/audio_dataframe.csv\")\naudio_df.shape\n# -\n\naudio_df.sample(10)\n\naudio_df.drop(audio_df.columns[0],axis=1,inplace=True)\n\naudio_df.sample(10)\n\n#We won't need the column textfile_path so we will drop that \naudio_df = audio_df.drop(['textfile_path'],axis=1)\n\naudio_df.sample(10)\n\n# +\nimport librosa\nimport numpy as np\n\n\ndef extract_feature(file_name):\n \n try:\n audio_data, sample_rate = librosa.load(file_name, res_type='kaiser_fast') \n mfccs = librosa.feature.mfcc(y=audio_data, sr=sample_rate, n_mfcc=40)\n mfccsscaled = np.mean(mfccs.T,axis=0)\n \n except Exception as e:\n print(\"Error encountered while parsing file: \", file_name)\n return None, None\n\n return np.array([mfccsscaled])\n\n\n# +\nimport os\n\nfeatures = []\n\n# Iterate through each sound file and extract the features \nfor index, row in audio_df.iterrows():\n \n file_name = os.path.join(str(row[\"audiofile_path\"]))\n audio_length = row[\"audio_length\"]\n data = extract_feature(file_name)\n features.append(data)\n\n# -\n\nlen(features)\n\nlen(features[2][0])\n\nfeatures_df = pd.DataFrame({\"feature\": [features][0]})\n\nfeatures_df['audio_length'] = audio_df['audio_length']\nfeatures_df['num_channels'] = audio_df['num_channels']\nfeatures_df['sample_rate'] = audio_df['sample_rate']\nfeatures_df['bit_depth'] = audio_df['bit_depth']\nfeatures_df['cycles'] = audio_df['cycles']\n\nfeatures_df.shape\n\nfeatures_df.head(10)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"AbhijeetGhosh/Smart-Stethoscope","sub_path":"RespirationPrediction.ipynb","file_name":"RespirationPrediction.ipynb","file_ext":"py","file_size_in_byte":1569,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"33"} +{"seq_id":"42570926473","text":"# # Meta-path based Heterogeneous Graph Embeddings for Recommendations\n\n# Recommendation problems can be modeled as link prediction on graphs, and neural graph embedding methods (i.e. mapping of each node to a low-dimensional space such that node 'similar' in graph space are mapped to nearyby points in the embedding space) have been particularly succesful at various graph analytical tasks. Unsupervised graph embedding methods like [**DeepWalk**](https://arxiv.org/abs/1403.6652) and [**node2vec**](https://snap.stanford.edu/node2vec/) use word2vec models (e.g. skip-gram) to map nodes co-occuring on a fixed window on truncated random walks to nearby points. These techniques can be used for collaborative filtering by mapping users and items to the same space, kind of an extension of matrix factorization based embedding. \n#\n# However, graphs for recommendations e.g. User-Item, User-Item-Genre, User-Item-Movie-Actor-Director etc. are often heterogeneous. Methods like DeepWalk are developed for homogeneous graphs with only one type of nodes, and might not perform optimal for heterogeneous graphs. As a direct extension of DeepWalk, [**metapath2vec**]() provides an unsupervised method to obtain node embeddings for heterogeneous graphs. **metapath2vec** generates random walks guided by a metapath (path of node types) and then uses the appropriate skip-gram like model for embedding. \n#\n# In this notebook, we will explore the use to metapath2vec embeddings for recommendation tasks. We will explore the efficacy of different metapaths. \n\n# ## Data \n\n# We will use the MovieLens data which contains ratings of movies by users. The data which is publically available from [MovieLens Website](https://grouplens.org/datasets/movielens/). We are using 100k data which has 100k ratings. \n\nimport pandas as pd\nimport numpy as np\n\nfrom scipy.sparse import coo_matrix, csr_matrix\nfrom scipy.sparse.linalg import svds, norm\nfrom scipy.spatial.distance import cosine\nfrom sklearn.metrics.pairwise import cosine_similarity\n\nimport operator\nfrom collections import defaultdict\n\ndata_path = '../data/'\n\nrating_df = pd.read_csv(data_path + 'ratings.csv', sep=',', header=0)\n\nrating_df.head()\n\nrating_df.shape\n\nrating_df.userId.nunique()\n\nrating_df.movieId.nunique()\n\n# - The data has over 100k ratings by 610 users on 9724 movies\n\nmax(rating_df.userId), max(rating_df.movieId)\n\n# - The movie ids do not follow an order. \n# - 9724 movies have been selected that users with id 1 to 610 have rated so as to have 100k ratings. \n\n# ### Movies Information\n\n# We are also provided the titles and genres of the movies in a separate file. \n\nmovie_df = pd.read_csv(data_path + 'movies.csv', sep=',', header=0)\n\nmovie_df.head()\n\nmovie_df[movie_df['title'].str.contains('Avengers')]\n\n# ## Train/Test data\n\n# Split the data into train and test sets. \n\ntrain_df = rating_df.sample(frac=0.7,random_state=200) #random state is a seed value\ntest_df = rating_df.drop(train_df.index)\n\ntrain_df.shape, test_df.shape\n\ntest_users = test_df.userId.unique()\ntest_movies = test_df.movieId.unique()\n\ntest_users.shape, test_movies.shape\n\n# ## Data processing\n\n# We will be used the implementation of metapath2vec provided with the original paper which is in C++.\n\n# metapath2vec implementation terminalogy\n#\n# - a = user, from author\n# - v = movie, from venue\n#\n# Currently, the official metapath2vec implementation supports four types of nodes:\n# 1. one starting from \"v\", e.g., vKDD\n# 2. one starting from \"a\", e.g., aJiaweiHan\n# 3. one starting from \"i\"\n# 4. one starting from \"f\"\n\n# Suffix 'a' to every user node id, and 'v' to every movie id. \n\n# +\nuser2int = dict()\nmovie2int = dict()\n\nfor x in train_df.values:\n usr = int(x[0])\n movie = int(x[1])\n if usr in user2int:\n pass\n else:\n user2int[usr] = 'a' + str(usr)\n if movie in movie2int:\n pass\n else:\n movie2int[movie] = 'v' + str(movie)\n# -\n\nlen(user2int), len(movie2int)\n\nlist(user2int.keys())[:5]\n\n# ### Adjacency lists of user and movies\n\n# Create the adjacency lists of the movies and users. Unlike the setup of *metapath2vec*, we have a *weighted* graph, so inaddition to the adjacent nodes, we also record the weight of each connection. Since these weights will determine transition probabilies of the random walks, we also normalize the weights of each edge by the sum of the weights of all edges from a given node. \n\nuser_movielist = dict()\nfor x in train_df.groupby(by=['userId'])[['movieId', 'rating']]:\n usr = user2int[x[0]]\n movieids = x[1][['movieId', 'rating']].values\n user_movielist[usr] = [(movie2int[y[0]], float(y[1])) for y in movieids]\n norm_sum = np.sum([y[1] for y in user_movielist[usr]])\n user_movielist[usr] = [(y[0], float(y[1]) / norm_sum) for y in user_movielist[usr]] \n\nuser_movielist['a1'][:5]\n\nmovie_userlist = dict()\nfor x in train_df.groupby(by=['movieId'])[['userId', 'rating']]:\n mve = movie2int[int(x[0])]\n userids = x[1][['userId', 'rating']].values\n movie_userlist[mve] = [(user2int[y[0]], float(y[1])) for y in userids]\n norm_sum = np.sum([y[1] for y in movie_userlist[mve]])\n movie_userlist[mve] = [(y[0], float(y[1]) / norm_sum) for y in movie_userlist[mve]] \n\nmovie_userlist['v1'][:5]\n\n\n# ## metapath2vec\n\n# metapath2vec operates in following steps:\n# - Choose a metapath e.g. User-Movie, User-Movie-User etc. \n# - Generate random walks starting from each node guided by the chosen metapath.\n# - Run the embedding model i.e. kip-gram with negative sampling. \n\n# ### Random walks for User-Movie-User metapath\n\ndef generate_metapaths_umu(user_movielist, movie_userlist, num_walks=10, walk_length=80):\n walks = []\n for usr in user_movielist:\n usr0 = usr\n for i in range(0, num_walks):\n walk = usr0\n for j in range(0, walk_length):\n movielist = user_movielist[usr]\n movieids = [x[0] for x in movielist]\n mve_probs = [x[1] for x in movielist]\n next_movie = np.random.choice(movieids, 1, p=mve_probs)[0]\n walk += \" \" + next_movie\n \n usrlist = movie_userlist[next_movie]\n usrids = [x[0] for x in usrlist]\n usr_probs = [x[1] for x in usrlist]\n next_user = np.random.choice(usrids, 1, p=usr_probs)[0]\n walk += \" \" + next_user\n walks.append(walk)\n return walks\n \n\n\nmetapath_walks_umu = generate_metapaths_umu(user_movielist, movie_userlist, num_walks=10, walk_length=100)\n\nmetapath_walks_umu[0]\n\nlen(metapath_walks_umu)\n\n# Write the random walks to a file to be used to *metapath2vec* code. \n\noutfile = '../data/user_movie_user_metapath_walks_umu.txt'\n\nwith open(outfile, 'w') as f:\n for walk in metapath_walks_umu:\n f.write(walk + \"\\n\")\n\n# Call metapath2vec with following config\n#\n# - embedding dimension = 128\n# - context window size = 7\n# - negative samples = 5\n\n# ! ../../deep_learning_graphs/metapath2vec/metapath2vec -train ../data/user_movie_user_metapath_walks_umu.txt -output ../data/metapath_umu_embed -pp 0 -size 128 -window 7 -negative 5 -threads 32\n\n\n# + active=\"\"\n# Just for reminder \n# a = user\n# v = movie\n# -\n\n# Load embeddings\n\ndef build_embeddings(embed_file):\n embedding_dict = dict()\n for line in open(embed_file):\n if line.startswith('v') or line.startswith('a'):\n record = line.rstrip().split()\n key = record[0]\n embedding_dict[key] = np.array(record[1:], dtype=float)\n else:\n pass\n return embedding_dict\n\n\nembeddings_umu = build_embeddings('../data/metapath_umu_embed.txt')\n\nlen(embeddings_umu)\n\nembeddings_umu['v1'].shape\n\n# Movie-Movie Similarity \n\nmovie1 = movie2int[260]\nmovie2 = movie2int[1196]\n1.0 - cosine(embeddings_umu[movie1], embeddings_umu[movie2])\n\nmovie1, movie2\n\nmovie3 = movie2int[1210]\n1.0 - cosine(embeddings_umu[movie1], embeddings_umu[movie3])\n\nmovie4 = movie2int[1]\n1.0 - cosine(embeddings_umu[movie1], embeddings_umu[movie4])\n\nmetapath_vecs_umu = []\nmetapath_umu_ids = []\nfor x in embeddings_umu:\n metapath_vecs_umu.append(embeddings_umu[x])\n metapath_umu_ids.append(x)\n\nmetapath_vecs_umu = np.array(metapath_vecs_umu)\nmetapath_vecs_umu.shape, len(metapath_umu_ids)\n\nreverse_movie2int = {k:v for v,k in movie2int.items()}\n\n\n# Compute k-nearest neighboring movies to a given movie. \n\ndef get_similar_movies_metapath(movieid, embed_arr, embed_keys, top_n=10):\n movie_idx = movie2int[movieid]\n idx = embed_keys.index(movie_idx)\n query = embed_arr[idx].reshape(1,-1)\n ranking = cosine_similarity(query, embed_arr)\n top_ids = np.argsort(-ranking)[0]\n top_indices = [embed_keys[y] for y in top_ids]\n top_movie_ids = [reverse_movie2int[j] for j in top_indices if j in reverse_movie2int][:top_n] \n sim_movies = [movie_df[movie_df.movieId == id].title.values[0] for id in top_movie_ids]\n return sim_movies\n\n\nget_similar_movies_metapath(260, metapath_vecs_umu, metapath_umu_ids)\n\nget_similar_movies_metapath(1, metapath_vecs_umu, metapath_umu_ids)[:10]\n\nget_similar_movies_metapath(2, metapath_vecs_umu, metapath_umu_ids)[:10]\n\n\n# ### Recommendation\n\ndef get_recommended_movies_metapath(userid, embed_arr, embed_keys, top_n=10):\n user_idx = user2int[userid]\n idx = embed_keys.index(user_idx)\n query = embed_arr[idx].reshape(1,-1)\n ranking = cosine_similarity(query, embed_arr)\n top_ids = np.argsort(-ranking)[0]\n top_indices = [embed_keys[y] for y in top_ids]\n top_movie_ids = [reverse_movie2int[j] for j in top_indices if j in reverse_movie2int][:top_n]\n reco_movies = [movie_df[movie_df.movieId == id].title.values[0] for id in top_movie_ids]\n return reco_movies\n\n\nget_recommended_movies_metapath(1, metapath_vecs_umu, metapath_umu_ids)\n\nget_recommended_movies_metapath(2, metapath_vecs_umu, metapath_umu_ids)\n\nget_recommended_movies_metapath(3, metapath_vecs_umu, metapath_umu_ids)\n\n\n\n# ### Movie-User-Movie metapath\n\ndef generate_metapaths_mum(user_movielist, movie_userlist, num_walks=10, walk_length=80):\n walks = []\n for mve in movie_userlist:\n mve0 = mve\n for i in range(0, num_walks):\n walk = mve0\n for j in range(0, walk_length):\n usrlist = movie_userlist[mve]\n usrids = [x[0] for x in usrlist]\n usr_probs = [x[1] for x in usrlist]\n next_user = np.random.choice(usrids, 1, p=usr_probs)[0]\n walk += \" \" + next_user\n\n movielist = user_movielist[next_user]\n movieids = [x[0] for x in movielist]\n mve_probs = [x[1] for x in movielist]\n next_movie = np.random.choice(movieids, 1, p=mve_probs)[0]\n walk += \" \" + next_movie\n walks.append(walk)\n return walks\n \n\n\nmetapath_walks_mum = generate_metapaths_mum(user_movielist, movie_userlist, num_walks=10, walk_length=100)\n\nmetapath_walks_mum[0]\n\nlen(metapath_walks_mum)\n\noutfile_mum = '../data/user_movie_user_metapath_walks_mum.txt'\n\nwith open(outfile_mum, 'w') as f:\n for walk in metapath_walks_mum:\n f.write(walk + \"\\n\")\n\n# ! ../../deep_learning_graphs/metapath2vec/metapath2vec -train ../data/user_movie_user_metapath_walks_mum.txt -output ../data/metapath_mum_embed -pp 0 -size 128 -window 7 -negative 5 -threads 32\n\nembeddings_mum = build_embeddings('../data/metapath_mum_embed.txt')\n\nembeddings_mum['v1'].shape\n\nlen(embeddings_mum)\n\n1.0 - cosine(embeddings_mum[movie1], embeddings_mum[movie2])\n\n1.0 - cosine(embeddings_mum[movie1], embeddings_mum[movie3])\n\n1.0 - cosine(embeddings_mum[movie1], embeddings_mum[movie4])\n\nmetapath_vecs_mum = []\nmetapath_mum_ids = []\nfor x in embeddings_mum:\n metapath_vecs_mum.append(embeddings_mum[x])\n metapath_mum_ids.append(x)\n\nmetapath_vecs_mum = np.array(metapath_vecs_mum)\nmetapath_vecs_mum.shape, len(metapath_mum_ids)\n\nget_similar_movies_metapath(260, metapath_vecs_mum, metapath_mum_ids)\n\nget_similar_movies_metapath(1, metapath_vecs_mum, metapath_mum_ids)\n\nget_similar_movies_metapath(2, metapath_vecs_mum, metapath_mum_ids)\n\n\n\nget_recommended_movies_metapath(1, metapath_vecs_mum, metapath_mum_ids)\n\nget_recommended_movies_metapath(2, metapath_vecs_mum, metapath_mum_ids)\n\nget_recommended_movies_metapath(3, metapath_vecs_mum, metapath_mum_ids)\n\n\n\n# ### UMU and MUM meta-paths\n\nmetapath_vecs_mum_umu = []\nmetapath_vecs_mum_umu.extend(metapath_walks_umu)\nmetapath_vecs_mum_umu.extend(metapath_walks_mum)\n\noutfile_mum_umu = '../data/user_movie_user_metapath_walks_mum_umu.txt'\n\nwith open(outfile_mum_umu, 'w') as f:\n for walk in metapath_vecs_mum_umu:\n f.write(walk + \"\\n\")\n\n# ! ../../deep_learning_graphs/metapath2vec/metapath2vec -train ../data/user_movie_user_metapath_walks_mum_umu.txt -output ../data/metapath_mum_umu_embed -pp 0 -size 128 -window 7 -negative 5 -threads 32\n\nembeddings_mum_umu = build_embeddings('../data/metapath_mum_umu_embed.txt')\n\nembeddings_mum_umu['v1'].shape\n\nlen(embeddings_mum_umu)\n\n1.0 - cosine(embeddings_mum_umu[movie1], embeddings_mum_umu[movie2])\n\n1.0 - cosine(embeddings_mum_umu[movie1], embeddings_mum_umu[movie3])\n\n1.0 - cosine(embeddings_mum_umu[movie1], embeddings_mum_umu[movie4])\n\nmetapath_vecs_mum_umu = []\nmetapath_mum_umu_ids = []\nfor x in embeddings_mum_umu:\n metapath_vecs_mum_umu.append(embeddings_mum_umu[x])\n metapath_mum_umu_ids.append(x)\n\nmetapath_vecs_mum_umu = np.array(metapath_vecs_mum_umu)\nmetapath_vecs_mum_umu.shape, len(metapath_mum_umu_ids)\n\nget_similar_movies_metapath(260, metapath_vecs_mum_umu, metapath_mum_umu_ids)\n\nget_similar_movies_metapath(1, metapath_vecs_mum_umu, metapath_mum_umu_ids)\n\nget_similar_movies_metapath(2, metapath_vecs_mum_umu, metapath_mum_umu_ids)\n\nget_recommended_movies_metapath(1, metapath_vecs_mum_umu, metapath_mum_umu_ids)\n\nget_recommended_movies_metapath(2, metapath_vecs_mum_umu, metapath_mum_umu_ids)\n\nget_recommended_movies_metapath(3, metapath_vecs_mum_umu, metapath_mum_umu_ids)\n\n\n# ## Evaluation on test data\n\ndef rank_movies_metapath(userid, movie_list, embed_dict, top_n=10):\n usr_idx = user2int[userid]\n usr_vec = embed_dict[usr_idx]\n sim_dict = dict()\n for mve in movie_list:\n if (mve in movie2int):\n mve_idx = movie2int[mve]\n if (mve_idx in embed_dict):\n mve_vec = embed_dict[mve_idx]\n sim_dict[mve] = cosine(usr_vec, mve_vec)\n else:\n pass\n ranked_movies = sorted(sim_dict.items(), key=operator.itemgetter(1))\n return ranked_movies[:top_n]\n\n\ntest_df.shape\n\ntest_df[test_df['rating'] >= 3.5].shape\n\ntest_pos_examples = dict((user, set(movies)) for user, movies in test_df[test_df['rating'] >= 3.5].groupby('userId')['movieId'])\n\nlen(test_pos_examples)\n\nlist(test_pos_examples.keys())[:10]\n\n\ndef precision_at_k(userid, true_pos_dict, embeddings, k):\n true_pos = true_pos_dict[userid]\n recos = [x for x,y in rank_movies_metapath(userid, test_movies, embeddings)]\n return (len(set(recos).intersection(true_pos)) * 1.0) / k\n\n\nprecision_at_k(103, test_pos_examples, embeddings_mum, k=10)\n\n\ndef average_precision_at_k(userid, true_pos_dict, embeddings, k=10):\n ap_at_k = 0\n for i in range(1,k):\n ap_at_k += precision_at_k(userid, true_pos_dict, embeddings, i)\n return ap_at_k / k\n\n\naverage_precision_at_k(2, test_pos_examples, embeddings_mum, k=10)\n\n\ndef mAP(true_pos_dict, embeddings, k=10):\n score = 0\n for usr in true_pos_dict:\n score += average_precision_at_k(usr, true_pos_dict, embeddings, k)\n return score / len(true_pos_dict)\n\n\ntrue_pos_dict = {1:test_pos_examples[1], 2:test_pos_examples[2], 3:test_pos_examples[3]}\n\nmAP(test_pos_examples, embeddings_mum, k=10)\n\nmAP(test_pos_examples, embeddings_umu, k=10)\n\nmAP(test_pos_examples, embeddings_mum_umu, k=10)\n\n\n\n# ## Node Classification\n\nmovie_genre_edgelist = movie_df[['movieId', 'genres']]\nmovie_genre_edgelist.head()\n\nmovie2genre = dict()\ngenre2movie = defaultdict(list)\nfor x in movie_genre_edgelist.values:\n genrelist = x[1].split('|')\n movie2genre[x[0]] = genrelist\n for g in genrelist:\n genre2movie[g].append(x[0])\n\ngenre_dict = {'Adventure': 1, 'Children': 1, 'Fantasy': 1 , 'Crime': 5, 'Thriller' : 5, 'Mystery' : 5, 'Sci-Fi' : 5, 'Comedy': 3, \n 'Drama': 2, 'Action': 4}\n\nmovie_embed_mum = []\nmovie_genres = []\nfor mve in movie2int:\n mve_id = movie2int[mve]\n genre = movie2genre[mve][0]\n if genre in genre_dict:\n if mve_id in embeddings_mum:\n embed = embeddings_mum[mve_id]\n movie_embed_mum.append(embed)\n movie_genres.append(genre_dict[genre] - 1)\n else:\n pass\n\nlen(movie_embed_mum), len(movie_genres)\n\nmovie_embed_mum = np.array(movie_embed_mum)\nmovie_embed_mum.shape\n\nmovie_genres[:5]\n\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(movie_embed_mum, np.array(movie_genres), test_size=0.33, random_state=42)\n\nX_train.shape, X_test.shape, y_train.shape, y_test.shape\n\nfrom sklearn.multiclass import OneVsRestClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import accuracy_score, roc_auc_score, f1_score, confusion_matrix\n\nclf = LogisticRegression(solver='lbfgs', multi_class='multinomial', max_iter=1000)\nclf.fit(X_train, y_train)\n\ny_pred = clf.predict(X_test)\n\ny_pred[:5]\n\nconfusion_matrix(y_test, y_pred)\n\nf1_score(y_test, y_pred, average='macro')\n\nf1_score(y_test, y_pred, average='micro')\n\n\n\n# ## Parameter Senstivity\n\nmetapath = 'mum'\ntrain_file = '../data/user_movie_user_metapath_walks_' + metapath + '.txt'\ntrain_file\n\nembed_out_file = '../data/metapath_mum_umu_embed_dim_' + str(embed_dim)\nembed_out_file\n\nembed_dim = 50\nembed_dim\n\n# ! ../../deep_learning_graphs/metapath2vec/metapath2vec -train $train_file -output $embed_out_file -pp 0 -size $embed_dim -window 7 -negative 5 -threads 32\n\nembedding_dict = build_embeddings(embed_out_file + '.txt')\n\nmAP(test_pos_examples, embedding_dict, k=10)\n\n\ndef build_data_for_classification(embeddings):\n movie_embed = []\n movie_genres = []\n for mve in movie2int:\n mve_id = movie2int[mve]\n genre = movie2genre[mve][0]\n if genre in genre_dict:\n if mve_id in embeddings:\n embed = embeddings[mve_id]\n movie_embed.append(embed)\n movie_genres.append(genre_dict[genre] - 1)\n else:\n pass\n X_train, X_test, y_train, y_test = train_test_split(np.array(movie_embed), np.array(movie_genres), test_size=0.33, random_state=42)\n return X_train, X_test, y_train, y_test\n\n\nX_train, X_test, y_train, y_test = build_data_for_classification(embeddings_mum_umu)\n\nX_train.shape, X_test.shape, y_train.shape, y_test.shape\n\n\ndef evaluate_node_classification(embeddings):\n X_train, X_test, y_train, y_test = build_data_for_classification(embeddings)\n clf = LogisticRegression(solver='lbfgs', multi_class='multinomial', max_iter=1000)\n clf.fit(X_train, y_train)\n y_pred = clf.predict(X_test)\n return {'macro': f1_score(y_test, y_pred, average='macro'), 'micro': f1_score(y_test, y_pred, average='micro')}\n\n\nevaluate_node_classification(embeddings_mum)\n\nevaluate_node_classification(embeddings_umu)\n\nevaluate_node_classification(embeddings_mum_umu)\n\n\n","repo_name":"januverma/recommendation","sub_path":"heterogeneous_graph_embeddings_metapath2vec.ipynb","file_name":"heterogeneous_graph_embeddings_metapath2vec.ipynb","file_ext":"py","file_size_in_byte":19406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"33"} +{"seq_id":"1470833523","text":"# ## Python for NLP: Vocabulary and Phrase Matching with SpaCy\n# https://stackabuse.com/python-for-nlp-vocabulary-and-phrase-matching-with-spacy/\n\n# ### Creating Matcher Object\n\n# +\nimport spacy\nnlp = spacy.load('en_core_web_sm')\n\nfrom spacy.matcher import Matcher\nm_tool = Matcher(nlp.vocab)\n# -\n\n# ### Defining Patterns\n\np1 = [{'LOWER': 'quickbrownfox'}]\np2 = [{'LOWER': 'quick'}, {'IS_PUNCT': True}, {'LOWER': 'brown'}, {'IS_PUNCT': True}, {'LOWER': 'fox'}]\np3 = [{'LOWER': 'quick'}, {'LOWER': 'brown'}, {'LOWER': 'fox'}]\np4 = [{'LOWER': 'quick'}, {'LOWER': 'brownfox'}]\n\n# * p1 looks for the phrase \"quickbrownfox\"\n# * p2 looks for the phrase \"quick-brown-fox\"\n# * p3 tries to search for \"qucik brown fox\"\n# * p4 looks for the phrase \"quick brownfox\"\n\n# Once the patterns are defined, we need to add them to the Matcher object that we created earlier.\nm_tool.add('QBF', None, p1, p2, p3, p4)\n# Here \"QBF\" is the name of our matcher. You can give it any name.\n\n# ### Applying Matcher to the Document\n\nsentence = nlp(u'The quick-brown-fox jumps over the lazy dog. The quick brown fox eats well. \\\n the quickbrownfox is dead. the dog misses the quick brownfox')\n\n\nphrase_matches = m_tool(sentence)\nprint(phrase_matches )\n\nfor match_id, start, end in phrase_matches:\n string_id = nlp.vocab.strings[match_id] \n span = sentence[start:end] \n print(match_id, string_id, start, end, span.text)\n\nm_tool.remove('QBF')\n\np1 = [{'LOWER': 'quick'}, {'IS_PUNCT': True, 'OP':'*'}, {'LOWER': 'brown'}, {'IS_PUNCT': True, 'OP':'*'}, {'LOWER': 'fox'}]\nm_tool.add('QBF', None, p1)\n\nsentence = nlp(u'The quick--brown--fox jumps over the quick-brown---fox')\n\n\n# +\nphrase_matches = m_tool(sentence)\n\nfor match_id, start, end in phrase_matches:\n string_id = nlp.vocab.strings[match_id] \n span = sentence[start:end] \n print(match_id, string_id, start, end, span.text)\n# -\n\n# ## Phrase-Based Matching\n#\n\n# +\nimport bs4 as bs \nimport urllib.request \nimport re \nimport nltk\n\nscrapped_data = urllib.request.urlopen('https://en.wikipedia.org/wiki/Artificial_intelligence') \narticle = scrapped_data .read()\n\nparsed_article = bs.BeautifulSoup(article,'lxml')\n\nparagraphs = parsed_article.find_all('p')\n\narticle_text = \"\"\n\nfor p in paragraphs: \n article_text += p.text\n \n \nprocessed_article = article_text.lower() \nprocessed_article = re.sub('[^a-zA-Z]', ' ', processed_article ) \nprocessed_article = re.sub(r'\\s+', ' ', processed_article)\n# -\n\n# ### Create Phrase Matcher Object\n\n# +\nimport spacy\nnlp = spacy.load('en_core_web_sm')\n\n\nfrom spacy.matcher import PhraseMatcher\nphrase_matcher = PhraseMatcher(nlp.vocab)\n# -\n\n# ### Create Phrase List\n\n# +\nphrases = ['machine learning', 'robots', 'intelligent agents']\n\npatterns = [nlp(text) for text in phrases]\n# -\n\nphrase_matcher.add('AI', None, *patterns)\n\n# ### Applying Matcher to the Document\n\n# +\nsentence = nlp (processed_article)\n\nmatched_phrases = phrase_matcher(sentence)\nmatched_phrases\n# -\n\nfor match_id, start, end in matched_phrases:\n string_id = nlp.vocab.strings[match_id] \n span = sentence[start:end] \n print(match_id, string_id, start, end, span.text)\n\n# ## Stop Words\n\nimport spacy\nsp = spacy.load('en_core_web_sm')\nprint(sp.Defaults.stop_words)\n\nsp.vocab['wonder'].is_stop\n\nsp.Defaults.stop_words.add('wonder')\n\nsp.vocab['wonder'].is_stop = True\n\nsp.vocab['wonder'].is_stop\n\n\n","repo_name":"rodrigoms2004/sirajraval_ml_course","sub_path":"Week5/playground/NLP/3_VocabularyPhraseMatchingSpaCy.ipynb","file_name":"3_VocabularyPhraseMatchingSpaCy.ipynb","file_ext":"py","file_size_in_byte":3430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"33"} +{"seq_id":"19497212068","text":"# ## Function as argument to another function\n\n# #### Syntax\n#\n# def f1(f2,x): # f2 is another function\n\n# ## filter()\n\n# ## syntax\n#\n# ### filter(function, sequence)\n\n# without filter() function\nl=[1,2,3,4,5,6,7,8,9,10]\ndef isEven(n):\n if n%2==0:\n return True\n else:\n return False\nl1=[]\nfor n in l:\n if isEven(n) == True:\n l1.append(n)\nprint(l1)\n\n# with filter() function\nl=[1,2,3,4,5,6,7,8,9,10]\ndef isEven(n):\n if n%2==0:\n return True\n else:\n return False\nl1=list(filter(isEven,l))\nprint(l1)\n\n# filter() with lambda function\nl=[1,2,3,4,5,6,7,8,9,10]\neven=list(filter(lambda n: n%2==0,l))\nprint(even)\n\nodd=list(filter(lambda n: n%2 is not 0,l))\nprint(odd)\n\n# The number which are divisible by 3 and odd\nl=[1,2,3,4,5,6,7,8,9,10]\nnby3odd=list(filter(lambda n: n%2 !=0 and n%3==0, l))\nprint(nby3odd)\n\n# only filter heroines whose names start with k\nheroines=['Katrina','Kareena','Anushka','Deepika','Alia','Malika']\nk=list(filter(lambda name: name[0]=='K',heroines))\nprint(k)\n\n\n","repo_name":"whojayantkumar/learn-complete-python-in-simple-way","sub_path":"functions/function_as_argument_to_another_function.ipynb","file_name":"function_as_argument_to_another_function.ipynb","file_ext":"py","file_size_in_byte":1027,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"33"} +{"seq_id":"1021269867","text":"from pgmpy.models import BayesianNetwork\nfrom pgmpy.factors.discrete import TabularCPD\nm1 = BayesianNetwork()\nm1.add_nodes_from(['X','Y','Z'])\nm1.get_independencies()\ncpd_X = TabularCPD(variable=\"X\", variable_card=2, values=[[0.4], [0.6]])\ncpd_Y = TabularCPD(variable=\"Y\", variable_card=2, values=[[0.7], [0.3]])\ncpd_Z = TabularCPD(variable=\"Z\", variable_card=2, values=[[0.1], [0.9]])\nm1.add_cpds(cpd_X,cpd_Y,cpd_Z)\n\nimport numpy as np\nfrom pgmpy.factors.discrete import JointProbabilityDistribution\np1 = [0.4, 0.6]\np2 = [0.7, 0.3]\np3 = [0.1, 0.9]\njp = []\nfor i in p1:\n for j in p2:\n for k in p3:\n jp.append(i*j*k) \nprint(jp)\nJPD = JointProbabilityDistribution([\"X\",'Y','Z'],[2,2,2], jp)\nm1.is_imap(JPD)\n\nm2 = BayesianNetwork()\nm2.add_nodes_from(['X','Y','Z'])\nm2.add_edge('Y','X')\nm2.add_edge('Y','Z')\ncpd_Y = TabularCPD(variable=\"Y\", variable_card=2, values=[[0.7], [0.3]])\ncpd_X = TabularCPD(\n variable=\"X\",\n variable_card=2,\n values=[\n [0.4, 0.2],\n [0.6, 0.8],\n ],\n evidence=[\"Y\"],\n evidence_card=[2],\n )\ncpd_Z = TabularCPD(\n variable=\"Z\",\n variable_card=2,\n values=[\n [0.5, 0.4],\n [0.5, 0.6],\n ],\n evidence=[\"Y\"],\n evidence_card=[2],\n )\nprint(cpd_X.is_valid_cpd(),cpd_Y.is_valid_cpd(),cpd_Z.is_valid_cpd())\nm2.add_cpds(cpd_X,cpd_Y,cpd_Z)\nm2.get_independencies()\n\nfrom pgmpy.base import DAG\nG = DAG()\nG.add_nodes_from(m2.nodes)\nG.add_edges_from(m2.edges)\n\nprint(G.get_independencies())\n\nimport numpy as np\nP_Y = np.array([[0.7], [0.3]])\nP_X_Y = np.array([\n [0.4, 0.2],\n [0.6, 0.8],\n ])\nP_Z_Y = np.array([\n [0.5, 0.4],\n [0.5, 0.6],\n ])\njpd = []\nfor Y in [0,1]:\n for X in [0,1]:\n for Z in [0,1]:\n p_yxz = np.multiply(\n np.multiply(P_Y[Y], P_X_Y[X,Y]),\n P_Z_Y[Z,Y])\n jpd.append(p_yxz[0])\n print(Y,X,Z, p_yxz)\nprint(jpd)\nprint(sum(jpd))\nprob = JointProbabilityDistribution([\"Y\",'X','Z'],[2,2,2], jpd)\nprint(m2.is_imap(prob))\n\nm3 = BayesianNetwork()\nm3.add_nodes_from(['x','y','z'])\nm3.add_edge('x','y')\nm3.add_edge('y','z')\nm3.get_independencies()\n\nm4 = BayesianNetwork()\nm4.add_nodes_from(['x','y','z'])\nm4.add_edge('z','y')\nm4.add_edge('y','x')\nm4.get_independencies()\n\nm5 = BayesianNetwork()\nm5.add_nodes_from(['x','y','z'])\nm5.add_edge('y','x')\nm5.add_edge('y','z')\nm5.add_edge('x','z')\nm5.get_independencies()\n\nm6 = BayesianNetwork()\nm6.add_nodes_from(['x','y','z'])\nm6.add_edge('x','y')\nm6.add_edge('y','z')\nm6.add_edge('x','z')\nm6.get_independencies()\n\nm7 = BayesianNetwork()\nm7.add_nodes_from(['x','y','z'])\nm7.add_edge('y','x')\nm7.add_edge('z','y')\nm7.add_edge('z','x')\nm7.get_independencies()\n\nm8 = BayesianNetwork()\nm8.add_nodes_from(['x','y','z'])\nm8.add_edge('y','x')\nm8.add_edge('y','z')\nm8.add_edge('z','x')\nm8.get_independencies()\n\nm9 = BayesianNetwork()\nm9.add_nodes_from(['x','y','z'])\nm9.add_edge('x','y')\nm9.add_edge('z','y')\nm9.add_edge('x','z')\nm9.get_independencies()\n\nm10 = BayesianNetwork()\nm10.add_nodes_from(['x','y','z'])\nm10.add_edge('x','y')\nm10.add_edge('z','y')\nm10.add_edge('x','z')\nm10.get_independencies()\n\nimport pygraphviz as pgv\ndef dagviz(nodes, edges, name):\n G = pgv.AGraph(strict=False, directed=True)\n G.add_nodes_from(nodes)\n for edge in edges:\n G.add_edge(edge)\n G.write(name + \".dot\")\n # use dot\n G.layout(prog=\"dot\")\n # write previously positioned graph to PNG file\n G.draw(name + \".png\")\n\n\ndef viz_model(model, filename):\n dagviz(model.nodes, model.edges, filename)\n\n\ni = 1\nfor model in [m1,m2,m3,m4,m5,m6,m7,m8,m9,m10]:\n viz_model(model, \"m\" + str(i))\n i = i+1\n\nimport numpy as np\npx = np.array([[0.4], [0.6]])\npy = np.array([[0.7], [0.3]])\npz = np.array([[0.1], [0.9]])\npxy = np.multiply(px, py.transpose())\npxyz = np.multiply(pz, pxy.flatten())\nprint(pxyz.transpose().flatten())\n\n\npxyz.transpose().flatten().transpose()\n\np1 = [0.4, 0.6]\np2 = [0.7, 0.3]\np3 = [0.1, 0.9]\njpd = []\nfor i in p1:\n for j in p2:\n for k in p3:\n jpd.append(i * j * k)\nprint(jpd)\n\n\n# +\ndef create_bn(nodes, edges):\n model = BayesianNetwork()\n model.add_nodes_from(nodes)\n model.add_edges_from(edges)\n return model\n \ndef imap_demo1():\n m1 = create_bn([\"X\", \"Y\", \"Z\"], [])\n px = [[0.4], [0.6]]\n py = [[0.7], [0.3]]\n pz = [[0.1], [0.9]]\n cpd_X = TabularCPD(variable=\"X\", variable_card=2, values=px)\n cpd_Y = TabularCPD(variable=\"Y\", variable_card=2, values=py)\n cpd_Z = TabularCPD(variable=\"Z\", variable_card=2, values=pz)\n print(cpd_Z.is_valid_cpd(), cpd_Y.is_valid_cpd(), cpd_X.is_valid_cpd())\n m1.add_cpds(cpd_X, cpd_Y, cpd_Z)\n \n pxy = np.multiply(px, py.transpose())\n pxyz = np.multiply(pz, pxy.flatten())\n print(pxyz)\n jpd = pxyz.transpose().flatten()\n print(jpd)\n JPD = JointProbabilityDistribution([\"X\", \"Y\", \"Z\"], [2, 2, 2], pxyz)\n check_imap = m1.is_imap(JPD)\n print(f\"Bayesian network m1 has \\n nodes: {m1.nodes} edges: {m1.edges} \")\n print(\n f\"the model represents the following joint probability distribution on {m1.nodes}\"\n )\n\n print(f\"Conditional independencies are:\")\n print(m1.get_independencies())\n print(f\"Is m1 an I-map of the joint distribution?\\nAnswer: {check_imap}\")\n\n\n\n# -\n\nimap_demo1()\n\npx = np.array([[0.4], [0.6]])\npy = np.array([[0.7], [0.3]])\npz = np.array([[0.1], [0.9]])\njpd = (np.multiply(pz, (np.multiply(px, py.transpose())).flatten())).transpose().flatten()\nprint(jpd)\n\n\ndef bn2(p_y, p_x_y, p_z_y):\n m2 = BayesianNetwork()\n m2.add_nodes_from([\"X\", \"Y\", \"Z\"])\n m2.add_edge(\"Y\", \"X\")\n m2.add_edge(\"Y\", \"Z\")\n cpd_Y = TabularCPD(variable=\"Y\", variable_card=2, values= p_y) \n cpd_X = TabularCPD(\n variable=\"X\",\n variable_card=2,\n values=p_x_y,\n evidence=[\"Y\"],\n evidence_card=[2],\n )\n cpd_Z = TabularCPD(\n variable=\"Z\",\n variable_card=2,\n values=p_z_y,\n evidence=[\"Y\"],\n evidence_card=[2],\n )\n # print(cpd_X.is_valid_cpd(), cpd_Y.is_valid_cpd(), cpd_Z.is_valid_cpd())\n m2.add_cpds(cpd_X, cpd_Y, cpd_Z)\n return m2\n\n\ndef imap_demo2():\n P_Y = np.array([[0.7], [0.3]])\n P_X_Y = np.array(\n [\n [0.4, 0.2],\n [0.6, 0.8],\n ]\n )\n P_Z_Y = np.array(\n [\n [0.5, 0.4],\n [0.5, 0.6],\n ]\n )\n m2 = bn2(P_Y, P_X_Y, P_Z_Y)\n jpd = []\n for Y in [0, 1]:\n for X in [0, 1]:\n for Z in [0, 1]:\n p_yxz = np.multiply(np.multiply(P_Y[Y], P_X_Y[X, Y]), P_Z_Y[Z, Y])\n print(p_yxz)\n jpd.append(p_yxz[0])\n print(Y, X, Z, p_yxz)\n print(jpd)\n print(sum(jpd))\n prob = JointProbabilityDistribution([\"Y\", \"X\", \"Z\"], [2, 2, 2], jpd)\n check_imap = m2.is_imap(prob)\n print(f\"Bayesian network m1 has \\n nodes: {m2.nodes} edges: {m2.edges} \")\n print(\n f\"the model represents the following joint probability distribution on {m2.nodes}\"\n )\n print(jpd)\n print(f\"Conditional independencies are:\")\n print(m2.get_independencies())\n print(f\"Is m2 an I-map of the joint distribution?\\nAnswer: {check_imap}\")\n\n\nimap_demo2()\n\njpd = []\nfor Y in [0, 1]:\n for X in [0, 1]:\n for Z in [0, 1]:\n p_yxz = np.multiply(np.multiply(P_Y[Y], P_X_Y[X, Y]), P_Z_Y[Z, Y])\n jpd.append(p_yxz[0])\nprint(jpd)\n\npx = np.array([[0.4], [0.6]])\npy = np.array([[0.7], [0.3]])\npz = np.array([[0.1], [0.9]])\njpd = (np.multiply(pz, (np.multiply(px, py.transpose())).flatten())).transpose().flatten()\nprint(jpd)\n\nP_Y = np.array([[0.7], [0.3]])\nP_X_Y = np.array(\n [\n [0.4, 0.2],\n [0.6, 0.8],\n ]\n )\nP_Z_Y = np.array(\n [\n [0.5, 0.4],\n [0.5, 0.6],\n ]\n )\npxy = P_X_Y.flatten()\npzy = P_Z_Y.flatten().reshape(4,1)\nprint(np.multiply(pxy, pzy))\n\nfrom math import comb\nprint(comb(3,2))\n\n\ndef create_bn(nodes, edges):\n model = BayesianNetwork()\n model.add_nodes_from(nodes)\n model.add_edges_from(edges)\n return model\n\n\nm = create_bn(['A','B','C','D'],[('A','B'),('A','C'),('B','D'),('C','D')])\n\nm.get_independencies()\n\nm = create_bn(['A','S','T','L','E','B','X','D'],\n [('A','T'),('S','L'),('S','B'),('T','E'),('L','E'),('E','X'),('E','D'),('B','D')])\n\nfrom util import d_sep\nd_sep(m,['B'],['S'],['T'])\n\nd_sep(m,['B'],['S','T'],['A','L','E','X'])\n\nd_sep(m,['B'],['S'],['T','A','L','E','X'])\n\nfrom util import d_sep, viz_model\ndef demo_graphoid_intersection():\n nodes = [\"A\", \"S\", \"T\", \"L\", \"E\", \"B\", \"X\", \"D\"]\n edges = [\n (\"A\", \"T\"),\n (\"S\", \"L\"),\n (\"S\", \"B\"),\n (\"T\", \"E\"),\n (\"L\", \"E\"),\n (\"E\", \"X\"),\n (\"E\", \"D\"),\n (\"B\", \"D\"),\n ]\n m = create_bn(nodes, edges)\n print(f\"created Bayesian network model\")\n name = \"graphoid_demo\"\n viz_model(m, name)\n print(f\"Nodes:\\n{nodes}\\nEdges\\n{edges}\")\n X = [\"E\"]\n Y = [\"A\"]\n W = [\"S\"]\n Z = [\"T\", \"D\", \"B\", \"X\",\"L\"]\n print(f\"created graph layout inf files: {name}.dot and {name}.png\")\n res1 = d_sep(m, [\"E\"], [\"A\"], [\"T\", \"D\", \"B\", \"X\",\"L\",\"S\"])\n print(f\"I({X}, {Z} U {W}, {Y}) is {res1}\")\n #%%\n res2 = d_sep(m, [\"E\"], [\"S\"], [\"T\", \"D\", \"B\", \"X\",\"L\",\"A\"])\n print(f\"I({X}, {Z} U {Y}, {W}) is {res2}\")\n #%%\n res3 = d_sep(m, [\"E\"], [\"S\",\"A\"], [\"T\", \"D\", \"B\", \"X\",\"L\"])\n print(f\"I({X}, {Z}, {W} U {Y}) is {res3}\")\n print(f\"verified intersection axiom\")\n\n\ndemo_graphoid_intersection()\n\nd_sep(m, [\"E\"], [\"A\"], [\"T\", \"D\", \"B\", \"X\",\"L\",\"S\"])\n\n\ndef demo_graphoid_contraction():\n nodes = [\"A\", \"S\", \"T\", \"L\", \"E\", \"B\", \"X\", \"D\"]\n edges = [\n (\"A\", \"T\"),\n (\"S\", \"L\"),\n (\"S\", \"B\"),\n (\"T\", \"E\"),\n (\"L\", \"E\"),\n (\"E\", \"X\"),\n (\"E\", \"D\"),\n (\"B\", \"D\"),\n ]\n m = create_bn(nodes, edges)\n print(f\"created Bayesian network model\")\n name = \"graphoid_demo\"\n viz_model(m, name)\n print(f\"Nodes:\\n{nodes}\\nEdges\\n{edges}\")\n X = [\"B\"]\n Y = [\"T\"]\n Z = [\"S\"]\n W = [\"A\", \"L\", \"E\", \"X\"]\n print(f\"created graph layout inf files: {name}.dot and {name}.png\")\n res1 = d_sep(m, [\"B\"], [\"S\"], [\"T\"])\n print(f\"I({X}, {Z}, {Y}) is {res1}\")\n #%%\n res2 = d_sep(m, [\"B\"], [\"S\", \"T\"], [\"A\", \"L\", \"E\", \"X\"])\n print(f\"I({X}, {Z} U {Y}, {W}) is {res2}\")\n #%%\n res3 = d_sep(m, [\"B\"], [\"S\"], [\"T\", \"A\", \"L\", \"E\", \"X\"])\n print(f\"I({X}, {Z}, {W} U {Y}) is {res3}\")\n print(f\"verified contraction axiom\")\n\n\ndemo_graphoid_contraction()\n\n# +\nnodes = {'A', 'S', 'T', 'L', 'E', 'B', 'X', 'D'}\nnode = 'L'\nnodes.remove(node)\nprint(nodes)\nblanket = {'S', 'E', 'T'}\n\nprint(nodes.difference(blanket))\n\n# -\n\nnodes = ['A', 'S', 'T', 'L', 'E', 'B', 'X', 'D']\nnode = 'L'\nnodes.remove(node)\nprint(nodes)\nblanket = ['S', 'E', 'T']\nprint(nodes.difference(blanket))\n\n\n","repo_name":"PacktPublishing/Causal-Inference-with-Bayesian-Networks","sub_path":"Chapter_3/imap.ipynb","file_name":"imap.ipynb","file_ext":"py","file_size_in_byte":10933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"33"} +{"seq_id":"30891737339","text":"# %load_ext autoreload\n# %autoreload 2\n\n# # Team SB: Subway Balancer\n#\n# ![](sb-logo.png)\n#\n# Team memebrs\n# - Kai Xu (https://xuk.ai) Research Scientist at Amazon\n# - Victoria, Pinzhen, Liao (https://purrgramming.life) Software Engineer at Morgan Stanley\n\n# ## Motivation\n# Living in New York, we often found ourselves frustrated while trying to choose the least crowded subway car during the commute, leading to an uncomfortable journey when our estimations were off. \n# In particular, during the morning and evening rush hours on the subway.\n\nfrom IPython.display import Image\nImage(filename='crowded-subway.jpeg',width=800)\n\n# ## Solution\n#\n# We aim to build a system to guide passenger to reach to carriage with more space.\n#\n# Out system consists two steps: (1) people counting and (2) traffic routing.\n# 1. This step operates by capturing real-time images of the subway, and then employing YOLO to count the number of passengers in each carriage. \n# 2. Upon acquiring the number data, we run an route balancing algorithm. This step provides real-time instructions to passengers to move towards more emtpy carriages. \n#\n# Through this approach, we are able to balance the load, ensuring a journey that is both more comfortable and more convenient for everyone.\n\nImage(filename='pipeline.jpg', width=400)\n\n# ## Demo: overall system\n#\n# ### Step 1: people counting\n\n# +\nfrom matplotlib import pyplot as plt\n\nfrom utils import make_carriage_fig, read_level_lst, read_direction_lst, vis\n\n# +\ndata_dir = \"/Users/kai/src/nyc-ai-hackathon/subway-balancer/counter/data\"\n\nmake_carriage_fig(data_dir)\n# -\n\n# !julia --proj=../counter ../counter/count.jl /Users/kai/src/nyc-ai-hackathon/subway-balancer/counter/data 5\n\n# copying output to local for the next step (and check its content)\n\n# !cp /Users/kai/src/nyc-ai-hackathon/subway-balancer/counter/data/subway-out.txt input.txt\n# !cat input.txt\n\n# ### Step 2: routing\n\n# !java -cp /Users/kai/src/nyc-ai-hackathon/subway-balancer/balancer/balancer/out/artifacts/balancer_jar/balancer.jar SubwayCarRouting --input input.txt --output output.txt\n\nlevel_lst = read_level_lst(\"input.txt\")\ndirection_lst = read_direction_lst('output.txt')\nvis(level_lst, direction_lst)\n\n# ## Routing algorithm: details\n#\n# - **Initial Check:** If the current carriage is empty ( <5 ) or is less crowded than adjacent carriages, it would recommend passengers to use this one.\n# - **Locate Less Crowded Carriage:** Identify the nearest carriage with fewer passengers on both left and right sides.\n# - **Generate Recommendations:** If less crowded carriages are found, recommend the direction towards the nearest one.\n#\n#\n# ## Usage\n#\n# According to the physical signs on the platform, passengers can know which way to go.\n\n# ## Demo: more routing examples\n\n# !java -cp /Users/kai/src/nyc-ai-hackathon/subway-balancer/balancer/balancer/out/artifacts/balancer_jar/balancer.jar SubwayCarRouting --input example/input-1.txt --output example/output-1.txt\n\nlevel_lst = read_level_lst(\"example/input-1.txt\")\ndirection_lst = read_direction_lst('example/output-1.txt')\nvis(level_lst, direction_lst)\n\n# !java -cp /Users/kai/src/nyc-ai-hackathon/subway-balancer/balancer/balancer/out/artifacts/balancer_jar/balancer.jar SubwayCarRouting --input example/input-2.txt --output example/output-2.txt\n\nlevel_lst = read_level_lst(\"example/input-2.txt\")\ndirection_lst = read_direction_lst('example/output-2.txt')\nvis(level_lst, direction_lst)\n","repo_name":"xukai92/subway-balancer","sub_path":"demo/illustration.ipynb","file_name":"illustration.ipynb","file_ext":"py","file_size_in_byte":3445,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"33"} +{"seq_id":"37501457480","text":"# This project explored how the Pillow package has easy methods to add borders, crop pictures and create histogram from images.\n\n# We will work with this hot air balloon image\n\n# \n\n# Library Needs\n\nfrom PIL import Image, ImageOps\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom pylab import *\n\n\n# Adding Border Around Image\n\n# +\n# Function used to accepts arguments for the paths of input image, output image and border \ndef add_border(input_image, output_image, border):\n img = Image.open(input_image)\n \n ''' Draws a black border around an image. The output image will\n have a squared image keeping the ratio of the input image.''' \n \n if isinstance(border, int) or isinstance(border, tuple):\n bimg = ImageOps.expand(img, border=border)\n else:\n raise RuntimeError('Border is not an integer or tuple!')\n \n bimg.save(output_image)\n \nif __name__ == '__main__':\n in_img = 'balloon.jpg'\n \n add_border(in_img, output_image='balloon_border.jpg',\n border=200)\n\n\n# -\n\n# balloon.jpg\n# balloon_border.jpg\n\n# Change Border And Color Around Image \n\n# +\n#Function accepts an additional argument new color \ndef add_border(input_image, output_image, border, color = 0):\n img = Image.open(input_image)\n \n ''' Draws a thickened black border around an image.''' \n \n if isinstance(border, int) or isinstance(border, tuple):\n bimg = ImageOps.expand(img, border=border, fill=color)\n else:\n raise RuntimeError('Border is not an integer or tuple!')\n \n bimg.save(output_image)\n \nif __name__ == '__main__':\n in_img = 'balloon.jpg'\n \n add_border(in_img,\n output_image='balloon_border_orange_top_bottom.jpg',\n border=(5,100),color='orange')\n# -\n\n# balloon.jpg\n# balloon_border_orange_top_bottom.jpg\n\n# Plot Image With Graph Coordinates\n\n# +\n# Read in image as an array\nim = array(Image.open('balloon.jpg'))\n\n# Plot the image\nimshow(im)\n\n# Add title and show the plot\ntitle('Plotting: \"balloon.jpg\"')\nshow()\n# -\n\n# Crop Image \n\n# +\n# Read in image \nimage = Image.open('balloon.jpg')\n\n# Select region to crop\nbox = (100, 100, 600, 300)\ncroppedIm = image.crop(box)\n\n# Save cropped image\ncroppedIm.save('cropped.jpg')\n\n# Plot the image\nimshow(croppedIm)\n\naxis('off')\n\n# Add title and show the plot\ntitle('Plotting: \"cropped.jpg\"')\nshow()\n# -\n\n# Create Histogram from Grayscale Image \n\n# +\n# Read image in as array and change to gray scale\nim = array(Image.open('balloon.jpg').convert('L'))\n\n# Show contours with origin upper left corner\ncontour(im, origin='image')\naxis('equal')\naxis('off')\n\n# Add title and plot\ntitle('Plotting: \"Contour Visual\"')\n\n# Create new image and plot a histogram of \nfigure()\nhist(im.flatten(),133)\n\n# Add title and show graph\ntitle('Plotting: \"Grayscale Histogram\"')\nplt.ylabel(\"# of Pixels\")\nplt.xlabel(\"Bins\")\n\n# Plot histogram \nshow()\n","repo_name":"ktd2001/Image-Processing-with-Pillow","sub_path":"Image Processing with Pillow.ipynb","file_name":"Image Processing with Pillow.ipynb","file_ext":"py","file_size_in_byte":3195,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"33"} +{"seq_id":"26930962725","text":"# +\nimport qecstruct as qc\n\nfrom mdopt.optimiser.dephasing_dmrg import DephasingDMRG\nfrom mdopt.mps.utils import (\n create_custom_product_state,\n create_simple_product_state,\n inner_product,\n marginalise,\n)\nfrom mdopt.optimiser.utils import (\n XOR_BULK,\n XOR_LEFT,\n XOR_RIGHT,\n COPY_LEFT,\n SWAP,\n)\nfrom examples.decoding.decoding import (\n css_code_constraint_sites,\n css_code_logicals_sites,\n apply_bitflip_bias,\n apply_constraints,\n)\n\n# +\nSEED = 123\nNUM_BITS, NUM_CHECKS = 10, 6\nCHECK_DEGREE, BIT_DEGREE = 5, 3\nif NUM_BITS / NUM_CHECKS != CHECK_DEGREE / BIT_DEGREE:\n raise ValueError(\"The Tanner graph of the code must be bipartite.\")\ncode = qc.random_regular_code(\n NUM_BITS,\n NUM_CHECKS,\n BIT_DEGREE,\n CHECK_DEGREE,\n qc.Rng(SEED)\n )\nhgpc = qc.hypergraph_product(code, code)\nnum_sites = 2 * hgpc.length() + hgpc.num_x_logicals() + hgpc.num_z_logicals()\nnum_logicals = hgpc.num_x_logicals() + hgpc.num_z_logicals()\nerror = \"0\" * num_sites\nstring_state = \"+\" * num_logicals + error\nerror_mps = create_custom_product_state(string=string_state, form=\"Right-canonical\")\nconstraints_tensors = [XOR_LEFT, XOR_BULK, SWAP, XOR_RIGHT]\nlogicals_tensors = [COPY_LEFT, XOR_BULK, SWAP, XOR_RIGHT]\\\n\nchi_max = 64\n# -\n\nconstraints_sites = css_code_constraint_sites(hgpc)\nlogicals_sites = css_code_logicals_sites(hgpc)\n\nrenormalise = True\nresult_to_explicit = False\nsites_to_bias = list(range(num_logicals, num_sites))\nerror_mps = apply_bitflip_bias(\n mps=error_mps,\n sites_to_bias=sites_to_bias,\n renormalise=renormalise,\n result_to_explicit=result_to_explicit,\n )\n\nerror_mps = apply_constraints(\n error_mps,\n constraints_sites[0],\n constraints_tensors,\n chi_max=chi_max,\n renormalise=renormalise,\n result_to_explicit=result_to_explicit,\n)\nerror_mps = apply_constraints(\n error_mps,\n constraints_sites[1],\n constraints_tensors,\n chi_max=chi_max,\n renormalise=renormalise,\n result_to_explicit=result_to_explicit,\n)\nerror_mps = apply_constraints(\n error_mps,\n logicals_sites,\n logicals_tensors,\n chi_max=chi_max,\n renormalise=renormalise,\n result_to_explicit=result_to_explicit,\n)\n\nsites_to_marginalise = list(range(num_logicals, len(error)))\n\nlogicals = marginalise(mps=error_mps, sites_to_marginalise=sites_to_marginalise)\n\nnum_dmrg_sites = len(logicals)\nmps_dmrg_start = create_simple_product_state(num_dmrg_sites, which=\"+\")\nmps_dmrg_target = create_simple_product_state(num_dmrg_sites, which=\"0\")\nengine = DephasingDMRG(\n mps=mps_dmrg_start,\n mps_target=mps_dmrg_target,\n chi_max=chi_max,\n mode=\"LA\",\n silent=False,\n)\n\nengine.run(num_iter=1)\nmps_dmrg_final = engine.mps\n\noverlap = abs(inner_product(mps_dmrg_final, mps_dmrg_target))\nprint(overlap)\n\n\n","repo_name":"quicophy/mdopt","sub_path":"examples/decoding/hypergraph_product.ipynb","file_name":"hypergraph_product.ipynb","file_ext":"py","file_size_in_byte":2800,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-jupyter-script","pt":"38"} +{"seq_id":"21474599012","text":"# # Predicting Car Prices\n#\n# The purpose of this project is to use the machine learning workflow to predict a car's market price using its attributes. We will use the information about the technical aspects of the car such as motor displacement, miles per gallon, vehicle weight and more. In this Project, we are going to implement the K-nearest neighbors algorithm to predict car prices.\n\n# ## Data Source\n#\n# Collecting data takes significant amount of time and energy. So we must always try to find relevant existing data. We are going to use the automobile dataset from the UCI Machine Learning Repository.\n#\n# The following is the link to the dataset: [automobile](https://archive.ics.uci.edu/ml/datasets/automobile)\n#\n# We will begin by taking a look at the data.\n\n# ## Exploring the Dataset\n\nimport pandas as pd\nimport numpy as np\n# Reading the dataset to a dataframe #\ncar_df = pd.read_csv(\"imports-85.data\")\ncar_df.head(5)\n\n# ### Renaming columns\n#\n# We can see that column names don't match with the ones in the dataset documentation. We are going to fix this by renaming the columns to match the __[dataset documentation](https://archive.ics.uci.edu/ml/datasets/automobile)__.\n\n# Renaming the column names #\ncolumns = [\"symboling\",\"normalized-losses\",\"make\",\"fuel-type\",\" aspiration\",\"num-of-doors\",\"body-style\",\n \"drive-wheels\",\"engine-location\",\"wheel-base\",\"length\",\"width\",\"height\",\"curb-weight\",\n \"engine-type\",\"num-of-cylinders\",\"engine-size\",\"fuel-system\",\"bore\",\"stroke\",\"compression-ratio\",\n \"horsepower\",\"peak-rpm\",\"city-mpg\",\"highway-mpg\",\"price\"]\ncars = pd.read_csv(\"imports-85.data\",names = columns)\ncars.head(0)\n\ncars.head(5)\n\n# Now we will explore the columns having continuous values according to the __[dataset documentation](https://archive.ics.uci.edu/ml/datasets/automobile)__.\n\n# +\ncontinuous_values_cols = ['normalized-losses', 'wheel-base', 'length', 'width', 'height', 'curb-weight', 'bore',\n 'stroke', 'compression-ratio', 'horsepower', 'peak-rpm', 'city-mpg', 'highway-mpg', 'price']\nnumeric_columns = cars[continuous_values_cols]\n\nnumeric_columns\n# -\n\n# ## Data Cleaning\n#\n# Most of the columns have a proper format to their data. However, above we can see that `normalized_losses` contains the question mark character. Below, we will take care of this formatting issue. Then we will change the type of all the columns to float in order to use the data effectively.\n\n# replacing the missing values with nan values #\nnumeric_columns = numeric_columns.replace(\"?\", np.nan)\nnumeric_columns\n\nnumeric_columns.info()\n\n# Converting the columns to float types \nnumeric_columns = numeric_columns.astype(float)\nnumeric_columns.info()\n\n# ### Missing Values\n#\n# In order for our algorithm to work properly we need to be sure we have no missing values. We will look for missing values and then evaluate whether to drop them or fill them in with an appropriate value in order to create our model properly.\n\nnumeric_columns.isnull().sum()\n\n# Our target column will be `price`. There are rows with missing prices and\n# we will therefore drop those rows.\n\n#Remove missing values from price column \nnumeric_columns = numeric_columns.dropna(subset = [\"price\"])\nnumeric_columns.isnull().sum()\n\n# All of the columns we are using for our model are numeric and continuous. We will thus replace any missing values with the mean of the corresponding column.\n\n# Filling the missing values using the average value of the corresponding column \nnumeric_columns = numeric_columns.fillna(numeric_columns.mean())\n#check for nulls\nprint(numeric_columns.isnull().sum())\n\n# ### Normalizing the Data\n#\n# We will now normalize all the data columns with the exception of the target column `price` using min-max normalization. \n\nprice_col = numeric_columns[\"price\"]\nnumeric_columns = (numeric_columns - numeric_columns.min())/(numeric_columns.max() - numeric_columns.min())\nnumeric_columns[\"price\"] = price_col\nnumeric_columns\n\n# ## Univariate Model\n#\n# We will start our modelling using the univariate (having only one column as a feature) k-nearest neighbor model for each possible feature. Initially, we will set our k value to the default of 5 and observe the RMSE of each column. Then we will vary the k value, observe and plot the results. Scikit-learn will be used to implement the algorithm.\n\n# +\nfrom sklearn.neighbors import KNeighborsRegressor\nfrom sklearn.metrics import mean_squared_error\n\ndef knn_train_test(train_col, target, df):\n # Shuffle the order of the rows in the dataframe #\n np.random.seed(1)\n shuffled_index = np.random.permutation(df.index)\n new_df = df.reindex(shuffled_index)\n \n # Split the data into training and test datasets #\n split_index = int(len(new_df)/2)\n training_data = new_df.iloc[0:split_index]\n test_data = new_df.iloc[split_index:]\n \n # Instantiate a k neighbor instance #\n knn = KNeighborsRegressor()\n \n # fit a model to the training data #\n knn.fit(training_data[[train_col]], training_data[target])\n \n # Predict target value using the model #\n predictions = knn.predict(test_data[[train_col]])\n \n # calculate the rmse values #\n mse = mean_squared_error(test_data[target], predictions)\n rmse = np.sqrt(mse)\n return rmse\n\nrmse_values = dict()\ntrain_cols = numeric_columns.columns.drop(\"price\")\n\nfor val in train_cols:\n rmse_val = knn_train_test(val,\"price\", numeric_columns)\n rmse_values[val] = rmse_val\n\n# convert the dictionary to a series \nrmse_series = pd.Series(rmse_values)\nrmse_series.sort_values()\n\n\n# -\n\n# In the case above, we used the default k value of 5. Now, we are going to test the model with a variety of k (number of neighbors used) values.\n# The following is the set of k values that we will use to train the model : [1, 3, 5, 7, 9]. We will examine the RMSEs of each feature using each k value and view the results graphically.\n\n# +\ndef knn_train_test(train_col, target, df):\n # Shuffle the order of the rows in the dataframe #\n np.random.seed(1)\n shuffled_index = np.random.permutation(df.index)\n new_df = df.reindex(shuffled_index)\n \n # Split the data into training and test datasets #\n split_index = int(len(new_df)/2)\n training_data = new_df.iloc[0:split_index]\n test_data = new_df.iloc[split_index:]\n k_values = [1,3,5,7,9]\n k_rmses = dict()\n \n for val in k_values:\n # Instantiate a k neighbor instance #\n knn = KNeighborsRegressor(n_neighbors = val)\n \n # fit a model to the training data #\n knn.fit(training_data[[train_col]], training_data[target])\n \n # Predict target value using the model #\n predictions = knn.predict(test_data[[train_col]])\n \n # calculate the rmse values #\n mse = mean_squared_error(test_data[target], predictions)\n rmse = np.sqrt(mse)\n k_rmses[val] = rmse\n return k_rmses\n\nk_rmse_values = dict()\ntrain_cols = numeric_columns.columns.drop(\"price\")\n\nfor val in train_cols:\n rmse_val = knn_train_test(val,\"price\", numeric_columns)\n k_rmse_values[val] = rmse_val\n \nk_rmse_values\n# -\n\n# Now we will visualize the RMSE values on a scatter plot.\n\n# +\nimport matplotlib.pyplot as plt\n# %matplotlib inline\n\nk_values = [1,3,5,7,9]\nfor k, v in k_rmse_values.items():\n x = k_values\n y = list(v.values())\n \n plt.scatter(x, y)\n plt.xlabel = 'k value'\n plt.xticks(k_values, ['1', '3', '5', '7', '9'])\n plt.ylabel = 'RMSE' \n# -\n\n# ## Multivariate Model\n#\n# Now that we have a function that works well with individual columns, the next step is to modify it to work with multiple features.\n#\n# ### Feature Optimization\n#\n# We will begin by looking at the average RMSE for each feature column across the varying k values we used above and sort them by RMSE value.\n\n# calculating average of rmse values #\navg_rmse_values = dict()\nfor key,val in k_rmse_values.items():\n rmse_avg = np.mean(list(val.values()))\n avg_rmse_values[key] = rmse_avg\nseries_avg_rmse = pd.Series(avg_rmse_values)\nseries_avg_rmse.sort_values()\n\n\n# We will begin optimizing our model by varying the amount of features we are using and examining the different RMSE values. We will start using the two features with the lowest RMSE above and add additional features until we reach a total of six features.\n\n# +\ndef knn_train_test(train_col, target, df):\n # Shuffle the order of the rows in the dataframe #\n np.random.seed(1)\n shuffled_index = np.random.permutation(df.index)\n new_df = df.reindex(shuffled_index)\n \n # Split the data into training and test datasets #\n split_index = int(len(new_df)/2)\n training_data = new_df.iloc[0:split_index]\n test_data = new_df.iloc[split_index:]\n k_values = [5]\n k_rmses = dict()\n \n for val in k_values:\n # Instantiate a k neighbor instance #\n knn = KNeighborsRegressor(n_neighbors = val)\n \n # fit a model to the training data #\n knn.fit(training_data[train_col], training_data[target])\n \n # Predict target value using the model #\n predictions = knn.predict(test_data[train_col])\n \n # calculate the rmse values #\n mse = mean_squared_error(test_data[target], predictions)\n rmse = np.sqrt(mse)\n k_rmses[val] = rmse\n return k_rmses\n\nrmse_values = dict()\nbest_two_features = [\"horsepower\", \"width\"]\nrmse_val = knn_train_test(best_two_features, \"price\", numeric_columns)\nrmse_values[\"best_two_features\"] = rmse_val\n\nbest_three_features = [\"horsepower\", \"width\",\"curb-weight\"]\nrmse_val = knn_train_test(best_three_features, \"price\", numeric_columns)\nrmse_values[\"best_three_features\"] = rmse_val\n\nbest_four_features = [\"horsepower\", \"width\", \"curb-weight\", \"highway-mpg\"]\nrmse_val = knn_train_test(best_four_features, \"price\", numeric_columns)\nrmse_values[\"best_four_features\"] = rmse_val\n\nbest_five_features = [\"horsepower\", \"width\", \"curb-weight\", \"highway-mpg\", \"length\"]\nrmse_val = knn_train_test(best_five_features, \"price\", numeric_columns)\nrmse_values[\"best_five_features\"] = rmse_val\n\nbest_six_features = [\"horsepower\", \"width\", \"curb-weight\", \"highway-mpg\", \"length\", 'city-mpg']\nrmse_val = knn_train_test(best_six_features, \"price\", numeric_columns)\nrmse_values[\"best_six_features\"] = rmse_val\n\nrmse_values\n\n\n# -\n\n# ## Hyperparameter Optimization\n#\n# Now that we have examined the number of features we might like to use in our model, we will examine different possible k values. We will use the three different feature combinations with the lowest RMSE above, the two, three and four feature combinations. We will then examine and plot the RMSE results varying k from 1 to 25.\n\n# +\ndef knn_train_test(train_col, target, df):\n # Shuffle the order of the rows in the dataframe #\n np.random.seed(1)\n shuffled_index = np.random.permutation(df.index)\n new_df = df.reindex(shuffled_index)\n \n # Split the data into training and test datasets #\n split_index = int(len(new_df)/2)\n training_data = new_df.iloc[0:split_index]\n test_data = new_df.iloc[split_index:]\n k_values = [x for x in range(1,26)]\n k_rmses = dict()\n \n for val in k_values:\n # Instantiate a k neighbor instance #\n knn = KNeighborsRegressor(n_neighbors = val)\n \n # fit a model to the training data #\n knn.fit(training_data[train_col], training_data[target])\n \n # Predict target value using the model #\n predictions = knn.predict(test_data[train_col])\n \n # calculate the rmse values #\n mse = mean_squared_error(test_data[target], predictions)\n rmse = np.sqrt(mse)\n k_rmses[val] = rmse\n return k_rmses\n\nrmse_values = dict()\nbest_two_features = [\"horsepower\", \"width\"]\nrmse_val = knn_train_test(best_two_features, \"price\", numeric_columns)\nrmse_values[\"best_two_features\"] = rmse_val\n\nbest_three_features = [\"horsepower\", \"width\",\"curb-weight\"]\nrmse_val = knn_train_test(best_three_features, \"price\", numeric_columns)\nrmse_values[\"best_three_features\"] = rmse_val\n\nbest_four_features = [\"horsepower\", \"width\", \"curb-weight\", \"highway-mpg\"]\nrmse_val = knn_train_test(best_four_features, \"price\", numeric_columns)\nrmse_values[\"best_four_features\"] = rmse_val\n\nrmse_values\n# -\n\n# Here we will visualize these RMSE values on a graph.\n\n# +\nimport matplotlib.pyplot as plt\n# %matplotlib inline\n\nfor key, val in rmse_values.items():\n x = list(val.keys())\n y = list(val.values())\n plt.plot(x,y)\n plt.xlabel = \"k-values\"\n plt.ylabel = \"RMSE\"\n# -\n\n# The optimal k value for the top three models are as follows:\n# - Model with two features : k = 3, RMSE = 3403\n# - Model with three features : k = 2, RMSE = 2813\n# - Model with four features : k = 1, RMSE = 2600\n#\n# We will now use this information to implement k-fold cross validation. We will first work on establishing k-fold cross validation with the four best features and k = 1. \n\n# +\nfrom sklearn.model_selection import cross_val_score, KFold\n\nnum_folds = [2, 3, 4, 5, 6, 7, 8, 9, 10]\nfeature_sets = [best_two_features, best_three_features, best_four_features]\n\nfor fold in num_folds:\n kf = KFold(fold, shuffle=True, random_state=1)\n model = KNeighborsRegressor(n_neighbors =1)\n #for feature in feature_sets:\n \n mses = cross_val_score(model, numeric_columns[best_four_features], numeric_columns[\"price\"],\n scoring=\"neg_mean_squared_error\", cv=kf)\n rmses = np.sqrt(np.absolute(mses))\n avg_rmse = np.mean(rmses)\n std_rmse = np.std(rmses)\n print('best_four_features', str(fold), \"folds: \", \"avg RMSE: \", str(round(avg_rmse, 2)), \"std RMSE: \",\n str(round(std_rmse, 2)))\n# -\n\n# Now that we have this, we can modify our `knn_train_test()` function to perform k-fold cross validation. We will then look at results of the three best feature sets using their established optimum k value. Our data here has around 200 rows, therefore we don't need to try a high number of folds. We have chosen 10 folds as a maximum so each fold will have at least 20 rows of data. Our variance is also very likely to climb quickly as we increase folds due to having fewer rows in each fold. At this point, we will also include the data cleaning steps we established earlier into our train and test function.\n\n# +\nfrom sklearn.model_selection import cross_val_score, KFold\n\ndef knn_train_test(features, k, target, df):\n #cleaning the data\n continuous_values_cols = ['normalized-losses', 'wheel-base', 'length', 'width', 'height', 'curb-weight', 'bore',\n 'stroke', 'compression-ratio', 'horsepower', 'peak-rpm', 'city-mpg', 'highway-mpg', 'price']\n df = df[continuous_values_cols]\n df = df.replace(\"?\", np.nan)\n df =df.astype(float)\n df = df.dropna(subset = [target])\n df = df.fillna(df.mean())\n target_col = df[target]\n df = (df - df.min())/(df.max() - df.min())\n df[target] = target_col\n \n # Shuffle the order of the rows in the dataframe #\n np.random.seed(1)\n shuffled_index = np.random.permutation(df.index)\n new_df = df.reindex(shuffled_index)\n \n # Split the data into train and test sets with differing folds\n num_folds = [2, 3, 4, 5, 6, 7, 8, 9, 10]\n \n for fold in num_folds:\n kf = KFold(fold, shuffle=True, random_state=1)\n model = KNeighborsRegressor(n_neighbors = k)\n mses = cross_val_score(model, numeric_columns[features], numeric_columns[target],\n scoring=\"neg_mean_squared_error\", cv=kf)\n rmses = np.sqrt(np.absolute(mses))\n avg_rmse = np.mean(rmses)\n std_rmse = np.std(rmses)\n print(str(fold), \"folds \", \"avg RMSE: \", str(round(avg_rmse, 2)), \"std RMSE: \",\n str(round(std_rmse, 2)))\n \n \n return avg_rmse, std_rmse\n\nbest_two_features = [\"horsepower\", \"width\"]\nprint('best two features: k=3')\nrmse_val = knn_train_test(best_two_features,3, \"price\", cars)\nprint('\\n')\n\nbest_three_features = [\"horsepower\", \"width\",\"curb-weight\"]\nprint('best three features: k=2')\nrmse_val = knn_train_test(best_three_features, 2, \"price\", cars)\nprint('\\n')\n\nbest_four_features = [\"horsepower\", \"width\", \"curb-weight\", \"highway-mpg\"]\nprint('best four features: k=1')\nrmse_val = knn_train_test(best_four_features, 1, \"price\", cars)\n# -\n\n# ## Conclusion\n#\n# We have followed a machine learning workflow in this project. We used the K-nearest neighbor algorithm to predict car prices on a test set of data. We used both train/test validation and k-fold cross validation. Along the way we discovered that the more features we used to train our data, the lower our optimum value for k was in our K-nearest neighbor algorithm. \n#\n# We ended with a variety of models with varying bias and variance scores. It is beyond the scope of what we are accomplishing here to find the best model. Had this been the goal, more time would have been spent in the feature optimization. Other optimization strategies beyond just lowest RMSE, such as feature correlation would have been considered. Given the results we do currently have, it appears using a model with four features and a k value of 1 looks the most promising to optimize further.\n","repo_name":"kenp8842/KNNeighbor-Car-Price-Predictio","sub_path":"Predicting_Car_Prices.ipynb","file_name":"Predicting_Car_Prices.ipynb","file_ext":"py","file_size_in_byte":17122,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"38"} +{"seq_id":"586337437","text":"import chromadb\n\nimport pandas as pd\n\ndf = pd.read_csv(\"/Users/jaykataria/Desktop/Data hack/jay/Copy of LawYantra Dataset - lawyer_summaries.csv\")\n\ndf\n\nclient = chromadb.Client()\n\nclient.list_collections()\n\ncollection = client.create_collection(\"Lawyers\")\n\ncollection.add(\n documents=[str(doc) for doc in df.values.tolist()], \n metadatas=[{\"source\": \"given\"}]*len([str(doc) for doc in df.values.tolist()]), \n ids=list(df.index.map(str)), # unique for each doc\n)\n\ncollection.query(\n query_texts=[\"Two brothers were tenant of a landlord in a commercial property.One brother had one son and a daughter (both minor) when he got divorced with his wife.The children's went into mother's custody at the time of divorce and after some years the husband (co tenant) also died. Now can the children of the deceased brother(co tenant) claim the right\"],\n n_results=2,\n)\n\nimport streamlit as st\n\n# +\nst.title(\"Lawyer Query 2 using VectorDB\")\nst.markdown(\"###\")\nquery=st.text_input(\"Enter your query here👇\")\n\n\nst.subheader(collection.query(\n query_texts=[query],\n n_results=10,\n))\n","repo_name":"JayKataria23/DataHack_2_Case-3","sub_path":"vecdb.ipynb","file_name":"vecdb.ipynb","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"38"} +{"seq_id":"23180209652","text":"# + [markdown] id=\"view-in-github\" colab_type=\"text\"\n# \"Open\n\n# + [markdown] id=\"sPAtLchddrqm\"\n# You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.\n#\n# You may assume the two numbers do not contain any leading zero, except the number 0 itself.\n#\n# \n# ```\n# Example 1:\n#\n#\n# Input: l1 = [2,4,3], l2 = [5,6,4]\n# Output: [7,0,8]\n# Explanation: 342 + 465 = 807.\n# Example 2:\n#\n# Input: l1 = [0], l2 = [0]\n# Output: [0]\n# Example 3:\n#\n# Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]\n# Output: [8,9,9,9,0,0,0,1]\n# ```\n# ```\n# Constraints:\n#\n# The number of nodes in each linked list is in the range [1, 100].\n# 0 <= Node.val <= 9\n# It is guaranteed that the list represents a number that does not have leading zeros.\n# ```\n\n# + id=\"Y_6AMJnmdzvW\"\nl1=[9,9,9,9,9,9,9]\nl2=[9,9,9,9]\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"uNR5e-UzeGmR\" outputId=\"91c9e4b7-f363-496d-843b-9a215e329746\"\nmax(len(l1), len(l2))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"pb1asiuSd4TS\" outputId=\"02e2ea06-f0f4-443a-d4ca-5271c2aff80c\"\nfor i in range(max(len(l1), len(l2))):\n print(i) \n\n# + id=\"6XjYKQcyhshV\"\n#length 맞추기\nif len(l1) == len(l2):\n pass\nelif len(l1) > len(l2):\n for i in range(abs(len(l1)-len(l2))):\n l2.append(0)\nelse:\n for i in range(abs(len(l1)-len(l2))):\n l1.append(0)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"8aOcubA2h8vf\" outputId=\"54a9aa62-4197-4342-a993-d7bb88045211\"\nprint(l1)\nprint(l2)\n\n# + id=\"_u1OJ7WFiPw3\"\nanswer = []\nprev = 0\nfor i in range(len(l1)):\n now = l1[i]+l2[i] + prev\n answer.append(now%10)\n prev = (now//10)\n\nif prev > 0 :\n answer.append(prev)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"3xwLndBWjZmK\" outputId=\"0230d410-7643-49b4-a3b9-4e9be2efa2d0\"\nanswer\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"XnAaT8kVfvnP\" outputId=\"29d6fad1-4522-4460-c456-4d2dd246d0c4\"\n23//10, 23%10\n\n\n# + id=\"LgQj5EgqdbZu\"\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\nclass Solution:\n def list2node(self, list1: List) -> ListNode: #ref : https://velog.io/@minjung-s/node2list\n result_node = ListNode()\n\n for i,num in enumerate(list1):\n if i == 0 :\n result_node.val = num\n else :\n node = result_node\n while node.next != None:\n node = node.next\n node.next = ListNode(num)\n return result_node\n def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:\n q1: List = []\n q2: List = []\n node1 = l1\n node2 = l2\n\n # 리스트 변환\n while node1 is not None:\n q1.append(node1.val)\n node1 = node1.next\n\n\n while node2 is not None:\n q2.append(node2.val)\n node2 = node2.next\n #length 맞추기\n if len(q1) == len(q2):\n pass\n elif len(q1) > len(q2):\n for i in range(abs(len(q1)-len(q2))):\n q2.append(0)\n else:\n for i in range(abs(len(q1)-len(q2))):\n q1.append(0)\n \n answer = []\n prev = 0\n \n for i in range(len(q1)):\n now = q1[i]+q2[i] + prev\n answer.append(now%10)\n prev = (now//10)\n \n if prev > 0 :\n answer.append(prev)\n return self.list2node(answer)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 653} id=\"SYW9JLd_mPdp\" outputId=\"5962c2ae-42c9-4fd4-b4c2-90b09b481e98\"\nfrom IPython.display import Image\nImage('16. Add Two Numbers.jpg')\n\n# + id=\"a0tS_lOUmT9R\"\n\n","repo_name":"johanjun/Google_Machine_Learning_Bootcamp_KR_2021","sub_path":"python_algorithm/16_Add_Two_Numbers.ipynb","file_name":"16_Add_Two_Numbers.ipynb","file_ext":"py","file_size_in_byte":4109,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-jupyter-script","pt":"38"} +{"seq_id":"72866391151","text":"# + id=\"tXq6lprfcDuR\"\nimport requests\nraw_html = requests.get(\"https://en.wikipedia.org/wiki/COVID-19_pandemic_in_Colombia#Current_number_of_cases_by_department\")\n\n# + id=\"2q6ox3V1cXcl\"\nfrom bs4 import BeautifulSoup\n\nsoup = BeautifulSoup (raw_html.content, 'html.parser')\n\n# + id=\"YRHwIBbKdgV8\"\ndepartment = soup.find_all(class_='wikitable')\n\nfor bootcamp in department:\n state = bootcamp.find_all('tr')\n\n# + id=\"DyrjLSA_eWUI\" colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 48} outputId=\"586cdfcb-51b4-48a0-e9ec-8856d5220303\"\nimport pandas as pd\ndata = pd.DataFrame(columns=['Department', 'Cases', 'Deaths', 'Recovered', 'Active Cases'])\ndata\n\n# + id=\"-7z8miLRgIvD\"\n\nfor i, thing in enumerate (state):\n nombres = thing.find_all_next('td')\n name= nombres[0].text.replace(\",\",\"\").strip()\n cases= nombres[1].text.replace(\",\",\"\").strip()\n deaths= nombres[2].text.replace(\",\",\"\").strip()\n recovered= nombres[3].text.replace(\",\",\"\").strip()\n active= nombres[4].text.replace(\"/n\",\"\").strip()\n\n\n\n\n data.loc[i] = [name,cases,deaths,recovered,active]\n\n\ndata.loc[34] = [\"Colombia\",\"1518067\",\"40680\",\"1382340\",\"95047\"]\n\n\n# + id=\"CjinhqmNJqhV\"\ndata = data.drop([0])\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 395} id=\"M-4fr5q_QI6Q\" outputId=\"42cae7e5-0057-4a66-cbd3-69a3ca29f808\"\n\ndata['Cases'] = pd.to_numeric(data['Cases'])\n\ndatas = data[\"Cases\"]\nlables = data[\"Department\"]\nfrom matplotlib import pyplot as plt\nplt.figure(figsize = (60,20))\nplt.xticks(range(len(datas)), lables)\nplt.title(\"Covid Cases in Colombia\")\nplt.xlabel('Department')\nplt.ylabel('Total')\nplt.bar(range(len(datas)), datas)\n\nplt.show()\n\n\n\n# + id=\"CWwXovltQpC3\"\n\n","repo_name":"gbickenbach/CovidCasesColombia","sub_path":"CovidCases.ipynb","file_name":"CovidCases.ipynb","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"38"} +{"seq_id":"22445546435","text":"# +\n#Задание 1\n# -\n\nl = [1,2,3,20,15]\nsum=0\nfor element in l:\n if element >10:\n sum+=element\nprint(sum)\n\n# +\n#Задание 2\n# -\n\nmy_list = ['to', 'Russia', 'how', 'where', 'for']\n\n[x for x in my_list if x[-1]=='r']\n\n# +\n#Задание 3\n# -\n\nimport random\n\ny = ''\nfor i in range(0,7):\n y1 = random.randint(0,9)\n y += str(y1)\nif not '3' in y:\n i = random.randint(1,4)\n y = y[0:i-1] + '3' + y[i+1:] \ny\n\n# +\n#Задание 4\n# -\n\ns = input()\n\n# +\nl = len(s)\nprint(l)\n\ns = s.split()\nm = len(s)\nprint(m)\n\n# +\n#Задание 5\n# -\n\na = []\nk = 10 \nfor r in range(6): \n a.append([]) \n for c in range(6): \n a[r].append(k) \n k += 1 \nfor r in a:\n print(r)\n\nprint('Сумма элементов списка ',sum(map(sum, a)))\n\n# +\n# Задание 6\n# -\n\nlist = [['No1', 'ФИО1', 'Возраст1', 'Группа1'],['No2', 'ФИО2', 'Возраст2', 'Группа2'],['No3', 'ФИО3', 'Возраст3', 'Группа3']]\n\ndic = {}\nfor function in list:\n first, *other = function\n dic[first] = other\ndic\n\n# +\n# Задание 7\n# -\n\nfio = input()\nnomer_group = input()\n\nfor function in dic.values():\n if function[1] == fio:\n function[2] = nomer_group\ndic\n","repo_name":"IrinaBelaya87/Homework","sub_path":"laba.ipynb","file_name":"laba.ipynb","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"38"} +{"seq_id":"10648126576","text":"import pandas as pd\nimport geopandas as gpd\nimport numpy as np\nimport folium\nfrom folium import Marker\n#import warnings \n#warnings.filterwarnings('ignore')\n\n# +\nworld = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))\neurope = world.loc[world.continent == 'Europe'].reset_index(drop=True)\n\neurope_stats = europe[[\"name\", \"pop_est\", \"gdp_md_est\"]]\neurope_boundaries = europe[[\"name\", \"geometry\"]]\n# -\n\neurope_boundaries.head()\n\neurope_stats.head()\n\n# Use an attribute join to merge data about countries in Europe\neurope = europe_boundaries.merge(europe_stats, on=\"name\")\neurope.head()\n\nfrom geopy.geocoders import Nominatim\n\n# +\ngeolocator = Nominatim(user_agent=\"Anzy\")\nlocation = geolocator.geocode(\"Milimani Law courts\")\n\nprint(location.point)\nprint(location.address)\n\n# +\nuniversities = pd.read_csv(r\"C:\\Users\\mugok\\Desktop\\Data sets\\top_universities.csv\")\nuniversities.head()\n\ndef my_geocoder(row):\n try:\n point = geolocator.geocode(row).point\n return pd.Series({'Latitude': point.latitude, 'Longitude': point.longitude})\n except:\n return None\n\nuniversities[['Latitude', 'Longitude']] = universities.apply(lambda x: my_geocoder(x['Name']), axis=1)\n\nprint(\"{}% of addresses were geocoded!\".format(\n (1 - sum(np.isnan(universities[\"Latitude\"])) / len(universities)) * 100))\n\n# Drop universities that were not successfully geocoded\nuniversities = universities.loc[~np.isnan(universities[\"Latitude\"])]\nuniversities = gpd.GeoDataFrame(\n universities, geometry=gpd.points_from_xy(universities.Longitude, universities.Latitude))\nuniversities.crs = {'init': 'epsg:4326'}\n\n# -\n\nuniversities.head()\n\n# +\n# Use spatial join to match universities to countries in Europe\neuropean_universities = gpd.sjoin(universities, europe)\n\n# Investigate the result\nprint(\"We located {} universities.\".format(len(universities)))\nprint(\"Only {} of the universities were located in Europe (in {} different countries).\".format(\n len(european_universities), len(european_universities.name.unique())))\n\neuropean_universities.head()\n","repo_name":"anzykenya/Joins","sub_path":"tablejoins.ipynb","file_name":"tablejoins.ipynb","file_ext":"py","file_size_in_byte":2052,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"38"} +{"seq_id":"8340542201","text":"#

CS753 Assignment 3 Graph Mining Algorithms

\n#\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.sparse import csr_matrix\nimport time\n\n# Load dataset\ndata = np.loadtxt(r'....web-Google.txt',dtype= int)\nprint (\"total number of links: \", len(data))\n\n#

Task 1: Implementation of Power Iteration Algorithm.

\n#\n#

(a) Implement the power iteration algorithm in matrix form without teleport (on slides page 20): Let stop criteria be ||r (t+1) − r (t) ||1 < 0.02. Spider traps and dead ends are not considered in this task [30 pts].

\n# \n#

Total number of unique source nodes is 739454. Because of big data nature, we use sparsematrix to store the adjacency matrix. In order to put source nodes as column and destinations as rows, I did a transpose before matrix multiplication with initial votes. The convergence happens when newrank - oldrank smaller than a threshold 0.02. Results show the column sum of sparseMatrix

\n\n# +\n# get counts of repetitive source nodes\n\nsource,ind,counts = np.unique(data[:,0],return_inverse=True, return_counts=True)\nprint(\"Total unique source nodes: \", len(source))\n# get initial votes for each node\n\nvotes = 1/counts[ind] \n\n# size of sparse matrix\nSM_size = max(max(data[:,0]),max(data[:,1]))+1\n# creating sparse matrix\nsparseMatrix = csr_matrix((votes, (data[:,0], data[:,1])), \n shape = (SM_size, SM_size))\n\n# initialize ranks\nrank = np.ones((SM_size,1))/SM_size\n# Power iteration algorithm\nt1 = time.time()\nflag = True\nn=0\nwhile flag:\n n += 1\n sparseMatrix_t = sparseMatrix.transpose() # transpose sparseMatrix to destination as rows and source as columns\n newrank = sparseMatrix_t.dot(rank)\n #Stop condition\n if np.linalg.norm(rank-newrank,ord=1)<0.02:\n flag = False \n rank = newrank \nt2 = time.time()\n\n## column sum of sparsematrix\n\ncolsum = sparseMatrix_t.sum(axis=0)\n\nprint(\"column sum of sparse matrix :\", colsum)\n\n# -\n\n#

(b) Calculate the rank score for all the nodes and report: (1) The running time of your power iteration algorithm; (2) the number of iterations needed to stop; (3) the IDs and scores of the top-10 ranked nodes [10 pts].

\n\n# +\nprint(\"Total running time is \",round((t2-t1)*1000), \"ms\")\nprint(\"Total number of iterations till convergence : \", n)\n\ntop10_rank = np.sort(np.squeeze(rank))[::-1]\ntop10_node = np.argsort(np.squeeze(rank))[::-1]\nprint(\"IDs and scores of the top-10 ranked nodes: \", list(zip(top10_node[0:10],top10_rank[0:10])))\n# -\n\n#

2.Task 2: Exploiting dead-ends:

\n#\n#

Before extending your codes to support dead ends, let’s first do some analysis on your current implementation in Task1. Report the leaked PageRank score in each iteration of task 1 and explain the phenomenon you observe from the above experiments.

\n#\n#

According to the result shown underlying, rating scores of dead-end nodes are continuously reducing over 20 iterations, indicating the pageRank scores are leaked through the dead-end nodes. In addition, the indices of dead-end nodes and total number of dead-end nodes are reported. The sum of final total rankings after convergence is 0.193, << 1,giving further evidence of pageRank leaking.

\n#\n\n# +\nnodes_deadend = np.where(colsum==0)[1]\nprint(\"indices of dead-end nodes: \", nodes_deadend)\nprint(\"total number of dead-end nodes: \", len(nodes_deadend))\n\n# get counts of repetitive source nodes\n\nsource,ind,counts = np.unique(data[:,0],return_inverse=True, return_counts=True)\n\n# get initial votes for each node\n\nvotes = 1/counts[ind] \n\n# size of sparse matrix\nSM_size = max(max(data[:,0]),max(data[:,1]))+1\n# creating sparse matrix\nsparseMatrix = csr_matrix((votes, (data[:,0], data[:,1])),shape = (SM_size, SM_size))\n\n# initialize ranks\nrank = np.ones((SM_size,1))/SM_size\n \nflag = True\nn=0\nepsilon = 0.02\nwhile flag:\n print()\n n += 1\n sparseMatrix_t = sparseMatrix.transpose()\n newrank = sparseMatrix_t.dot(rank)\n leakedrank= 1-sum(newrank)\n while n <=20:\n print(\"iteration n: \",n, \"leaded ranking: \", leakedrank)\n #Stop condition\n if np.linalg.norm(rank-newrank,ord=1)3. Task 3: Implementation of Teleport.\n#\n#

(a) Extend your PageRank code to handle both spider traps and dead ends using the idea of teleport. Let β = 0.9 by default and the stop criteria be ||r(t+1) −r(t)||1 <0.02.

\n#\n#

Firstly all rank score would muptiply beta value, 0.9. The value of (1 - sum of all rank scores) is calculated and evenly added back into the new ranking scores. The purpose of doing it is to teleport the leaking scores back to the total network and ensure the column sum is still equal to 1 as shown underlying.

\n\n# +\n# get counts of repetitive source nodes\nsource,ind,counts = np.unique(data[:,0],return_inverse=True, return_counts=True)\n\n# get initial votes for each node\n\nvotes = 1/counts[ind] \n\n# size of sparse matrix\nSM_size = max(max(data[:,0]),max(data[:,1]))+1\n# creating sparse matrix\nsparseMatrix = csr_matrix((votes, (data[:,0], data[:,1])),shape = (SM_size, SM_size))\n# Power iteration algorithm with teleportation\nt = time.time()\ndef pRank_tele(beta):\n # initialize ranks\n rank = np.ones((SM_size,1))/SM_size\n epsilon = 0.02\n flag = True\n n=0\n while flag:\n print()\n n += 1\n sparseMatrix_t = sparseMatrix.transpose() # transpose sparseMatrix to destination as rows and source as columns\n newrank1 = (sparseMatrix_t.dot(rank))*beta\n # teleport leaked pagerank\n newrank2 = newrank1 + (1-newrank1.sum())/SM_size\n #Stop condition\n if np.linalg.norm(rank-newrank2,ord=1)(b) Run your code on the Google web data and report: (1) the running time; (2) the\n# number of iterations needed to stop; (3) the IDs and scores of the top-10 ranked\n# nodes [10 pts].\n\nprint(\"Total running time is: \",round((t2-t1)*1000), \"ms\")\nprint(\"Total number of iterations till convergence : \", teleRank[0])\ntop_rank = np.sort(np.squeeze(teleRank[1]))[::-1]\ntop_node = np.argsort(np.squeeze(teleRank[1]))[::-1]\nprint(\"IDs and scores of the top-10 ranked nodes after teleport: \", list(zip(top_node[0:10],top_rank[0:10])))\n\n\n#

(c) By varying the teleport probability β in [1, 0.9, 0.8, 0.7, 0.6, 0.5], report the num\u0002ber of iterations needed to stop for each β. Explain your findings from this\n# experiment [10 pts].

\n#\n#

From results shown underlying, we can see with decreasing beta value, the total number of iterations is also reduced. The total iterations at beta =1 is 90, which is different from the result obtained previously 62. The reason is when without teleport, it is not actual convergence. The total sum reduced (0.19 << 1) due to ranking score leakage. Therefore when the difference of ranking below threshold (epsilon 0.02), it reached so-called convergence due to the diminishing scores. When teleport is implemented, the convergence is the real convergence because the total sum of the final ranking score is 1, there is no leakage of scores.

\n\nfor beta in [1, 0.9, 0.8, 0.7, 0.6, 0.5]:\n N_iter = pRank_tele(beta)[0]\n print(\"when beta =\", beta,\"Number of iterations :\", N_iter)\n\n","repo_name":"YixuanLee/CS753_bigdata_algorithms","sub_path":"CS753_Graph_Mining_pageRanking.ipynb","file_name":"CS753_Graph_Mining_pageRanking.ipynb","file_ext":"py","file_size_in_byte":7660,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"38"} +{"seq_id":"41351727308","text":"# ## Why using Numpy if we have python lists ?\n# NumPy is more fast than python list because is store just the binary form of the number instead the in list we store many other information related to the behivior of python objects.\n#\n# also in numpy we don't check the type of the variable each time we hava one fixed type (less work ==> more performance)\n#\n# also in numpy for when we create an array we allow for it a continus space memry each element is in the next of the other element. But in the python list we don't have a coninus memory.\n#\n# also we can do more with numpy!!!.\n#\n# all resourses for this courses are quoted from the official numpy documentation https://numpy.org/doc/\n#\n# ## Load NumPy \n\nimport numpy as np\n\n# ## The Basics\n\n# +\n\na = np.array([1,2,3])\na\n\n# +\n\nb = np.array([[9,8,7,5,5,4,3],[9,7,0,1,5,9,0]])\nb\n# -\n\n# get dimention\nprint(b.ndim)\nprint(a.ndim)\n\n# get Shape\nprint(b.shape)\nprint(a.shape)\n\n# get type\nprint(a.dtype)\n\n# get size\nprint(a.itemsize)\n\n# total size\nprint(a.size*a.itemsize)\na.nbytes\n\n# you can specified your data to be more efficient with adding \n# some proprieteis to the array dtype\n\na = np.array([[1,2,3],[1,2,3]],dtype = 'int16')\nprint(a.dtype)\nprint(a,'\\n',a.nbytes)\n\n\n# **Access to element**\n\na = np.array([[0,8,7,5,5,4,3],\n [1,7,0,1,5,9,0],\n [2,8,7,5,5,4,3],\n [3,7,0,1,5,9,0]])\na\n\n# get a specific element :\nprint(a[1][5]) # way 1\nprint(a[1,5]) # way 2\n\n# get a specific row\nprint(a[0,:])\n# get a specific column\nprint(a[:,2])\n\n# get a specific values : [start_index , end_index , step_to_take]:\nprint(a[0,1:5:2])\nprint(a[0:3:2,0])\nprint(a[0,1:-2:2])\n\n# change a specific value in array\na[1,3]= 9999\na\n\n# Theirs a banch of thing that u can do with indexes now you have the assencial try to applayn it in 3d exemples (tensors), but you dont really need it for beginer problems.\n\n# ### initializing Different Types of Arrays\n\n# Zeros matrix\nnp.zeros((2,3))\n\n# ones Matrix / specifing the tye is opional\nnp.ones((2,3),dtype='int16')\n\n# chose a specifing number to initialize a matrix :\nnp.full((2,2),999)\n\n# full like method :\n''' is used to create a matrix with a unifie number \n but with a size of an other matrix already exist. '''\nprint('a =')\nprint(a)\nprint('\\nfull_like(a,1234) = ')\nprint(np.full_like(a,1234))\n\n# **INITIALIZE WITH A RANDOM NUMBER :**\n\n# randm values betwen 0 and 1 dicimal\nnp.random.rand(4,2)\n\n# random integer value\nnp.random.randint(7)\n\n# random matrix of int\nnp.random.randint(10,size=(3,3))\n\n# identity matrix:\nnp.identity(5)\n\n# repeat an array :\narr = np.array([[1,2,3]])\nprint(arr)\nr1 = np.repeat(arr ,3 ,axis=0)\nr1\n\n# **Be careful with copying matrix in numpy !!**\n\na = np.array([[1,2,3],[4,5,6],[7,8,9]])\nprint('A = \\n',a)\nb = a\nprint('B = \\n',b)\nb[0] = 100\nprint('B = \\n',b)\nprint('A = \\n',a)\nprint('>> why A also changed ? ...')\nprint('>>>> because you don\\'t make a copy to make a copy we just tell \\nnumpy to make a = b is not the same thing.')\n\n# **To make a copy follow those instraction :**\n\na = np.array([[1,2,3],[4,5,6],[7,8,9]])\nprint('A = \\n',a)\nb = a.copy() # copy with the copy method\nprint('B = \\n',b)\nb[0] = 100\nprint('B = \\n',b)\nprint('A = \\n',a)\nprint('\\n>> yahooo evry thing is fine (; ')\n\n# ### NumPy operatio \n# just like the array operations . \n\na\n\na+2\n\na-2\n\na*2 #scaler multiplication\n\na**2\n\na/2\n\nnp.sin(a)\n\n# ## Liniar Algebra\n\na = np.ones((2,3))\na\n\nb = np.full((3,2),2)\nb\n\n# **NOW WE WANNA TO CALCULATE AB OR A x B :**\n\nprint('A = \\n',a)\nprint('\\nB = \\n',b)\nprint('\\nAB = ')\nprint(np.matmul(a,b))\n\n# ### find determinant \n\n# find determinant \nc=np.matmul(a,b)\nnp.linalg.det(c)\n\nc=np.identity(3)\nnp.linalg.det(c)\n\na = np.array([[1,2,3],[4,5,6],[7,8,9]])\nprint('A = \\n',a)\nb = np.array([0,0,0])\nprint('\\nB = \\n',b)\n\n#solve the liniar system\nnp.linalg.solve(a, b)\n\n# calculate the inverses\nprint(np.linalg.inv(a))\nnp.linalg.inv(c) #c is the identety matrix we define earlyer\n\n# for more about liniar algebra in numpy vist : https://docs.scipy.org/doc/numpy/reference/routines.linalg.html\n\n# ## Statistics :\n\nstats = np.array([[1,2,3],[4,5,6]])\nstats\n\nnp.min(stats)\n\n\nnp.max(stats, axis=1)\n\n\nnp.sum(stats, axis=0)\n\n# ### Reorganizing Arrays\n\n# +\n\nbefore = np.array([[1,2,3,4],[5,6,7,8]])\nprint(before)\n\nafter = before.reshape((8,1))\nprint('\\n',after)\nafter = before.reshape((2,2,2))\nprint('\\n',after)\nafter = before.reshape((4,2))\nprint('\\n',after)\n\n# +\n# Vertically stacking vectors\nv1 = np.array([1,2,3,4])\nv2 = np.array([5,6,7,8])\n\nnp.vstack([v1,v2,v1,v2])\n\n# +\n# Horizontal stack\nh1 = np.ones((2,4))\nh2 = np.zeros((2,2))\n\nnp.hstack((h1,h2))\n# -\n\n# ### Boolean Masking and Advanced Indexing\n\na = np.random.randint(100,size=(5,5))\na\n\na > 50\n\n# thanks for\n","repo_name":"ahbarabdellah/Essential_About_Popular_Python_Library_For_Machine_Learning","sub_path":"NumPy Tutorial.ipynb","file_name":"NumPy Tutorial.ipynb","file_ext":"py","file_size_in_byte":4731,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-jupyter-script","pt":"38"} +{"seq_id":"16350041475","text":"# + colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"elapsed\": 9299, \"status\": \"ok\", \"timestamp\": 1651067682642, \"user\": {\"displayName\": \"Mary Abgaryan\", \"userId\": \"01901391193697622836\"}, \"user_tz\": -240} id=\"A_F-y9nSoJ07\" outputId=\"e130d9be-a561-48d8-db75-85313c98cdde\"\nfrom openpyxl import load_workbook\nimport matplotlib.pyplot as plt\nfrom google.colab import drive\nfrom matplotlib import cm\nfrom os import listdir\nfrom PIL import Image\nimport numpy as np\nimport torchvision\nimport cv2 as cv\nfrom torchvision import models\nimport torch\nimport pywt\nimport os\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.data import random_split\nfrom torchvision.utils import save_image\nimport torch.optim as optim\nimport shutil\nimport pandas as pd\n# !pip install split-folders\nimport splitfolders\nfrom sklearn.svm import SVC\nfrom tqdm import tqdm\nfrom torchvision import transforms, utils, datasets\nfrom torch.utils.data import Dataset, DataLoader, SubsetRandomSampler\nfrom torch.utils.data.dataloader import default_collate\nfrom sklearn.metrics import classification_report, confusion_matrix\nimport pandas as pd\nimport seaborn as sns\n\n# #!pip install tensorboard\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} id=\"39Tb2HXZrjG1\" executionInfo={\"status\": \"ok\", \"timestamp\": 1651067708560, \"user_tz\": -240, \"elapsed\": 25931, \"user\": {\"displayName\": \"Mary Abgaryan\", \"userId\": \"01901391193697622836\"}} outputId=\"c0d28d11-74f9-49a9-8ec9-0fdc51d4f657\"\nfrom google.colab import drive\ndrive.mount('/content/drive')\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"elapsed\": 2213, \"status\": \"ok\", \"timestamp\": 1651067710769, \"user\": {\"displayName\": \"Mary Abgaryan\", \"userId\": \"01901391193697622836\"}, \"user_tz\": -240} id=\"B-GT6IM5fz7l\" outputId=\"d146ece6-c27a-4127-ede8-8aafc2d7e588\"\ndrive.mount('/content/drive/')\n\n# + [markdown] id=\"zNILefik7Am0\"\n# # Defining Data Loader\n\n# + [markdown] id=\"wOGG_a5t_zPd\"\n# Set random seed\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"elapsed\": 9, \"status\": \"ok\", \"timestamp\": 1651067710769, \"user\": {\"displayName\": \"Mary Abgaryan\", \"userId\": \"01901391193697622836\"}, \"user_tz\": -240} id=\"Xn6CpFtb_1er\" outputId=\"1c3bb4b2-ee22-483d-8a73-a2671f991a7b\"\nnp.random.seed(0)\ntorch.manual_seed(0)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"elapsed\": 6, \"status\": \"ok\", \"timestamp\": 1651067710769, \"user\": {\"displayName\": \"Mary Abgaryan\", \"userId\": \"01901391193697622836\"}, \"user_tz\": -240} id=\"bvsRBtPA7EC3\" outputId=\"a642be58-9003-480e-e38b-1caeddfc32f8\"\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nprint(\"We're using =>\", device)\nroot_dir = \"/content/drive/MyDrive/ML Project/Diabetic Retinopathy/Fungus of Retina/\"\nprint(\"The data lies here =>\", root_dir)\n\n# + [markdown] id=\"W05vo10i7Y81\"\n# Defining Transformers\n\n# + id=\"CF67VJ4b7YEp\"\nimage_transforms = {\n \"train\": transforms.Compose([\n transforms.Resize((64,64)),\n transforms.ToTensor(),\n transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))]),\n \"test\": transforms.Compose([\n transforms.Resize((64,64)),\n transforms.ToTensor(),\n transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))]),\n }\n\n# + [markdown] id=\"kncwe8Ma8KMF\"\n# Initialize Datasets\n#\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"elapsed\": 31722, \"status\": \"ok\", \"timestamp\": 1651067742487, \"user\": {\"displayName\": \"Mary Abgaryan\", \"userId\": \"01901391193697622836\"}, \"user_tz\": -240} id=\"y7UtRZiY7AIM\" outputId=\"0c134179-08a0-4a87-a6fe-5b0fcdd85d92\"\nrps_dataset = datasets.ImageFolder(root = root_dir + \"train (1)\",\n transform = image_transforms[\"train\"]\n )\nrps_dataset\n\n# + [markdown] id=\"RU-3yVQo9CbO\"\n# The class_to_idx function is pre-built in PyTorch. It returns class ID's present in the dataset.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"elapsed\": 12, \"status\": \"ok\", \"timestamp\": 1651067742487, \"user\": {\"displayName\": \"Mary Abgaryan\", \"userId\": \"01901391193697622836\"}, \"user_tz\": -240} id=\"c_kHT8He9DKz\" outputId=\"147faa3e-60c8-4898-f34e-22982c33acd5\"\nrps_dataset.class_to_idx\n\n# + [markdown] id=\"lpUFtPN39Pul\"\n# We will create our own dictionary that maps class names to numbers\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"elapsed\": 10, \"status\": \"ok\", \"timestamp\": 1651067742488, \"user\": {\"displayName\": \"Mary Abgaryan\", \"userId\": \"01901391193697622836\"}, \"user_tz\": -240} id=\"PA7vJwKG9V0a\" outputId=\"57a45883-044c-4043-c76f-654e652a20df\"\nidx2class = {v: k for k, v in rps_dataset.class_to_idx.items()}\nidx2class\n\n\n# + [markdown] id=\"WCbMqSEx9kSm\"\n# Function that takes in a dataset object and returns a dictionary that contains the count of class samples. We will use this dictionary to construct plots and observe the class distribution in our data.\n# get_class_distribution() takes in an argument called dataset_obj.\n#\n#\n\n# + id=\"WaFDejgh9V6l\"\ndef get_class_distribution(dataset_obj):\n count_dict = {k:0 for k,v in dataset_obj.class_to_idx.items()}\n for _, label_id in dataset_obj:\n label = idx2class[label_id]\n count_dict[label] += 1\n return count_dict\ndef plot_from_dict(dict_obj, plot_title, **kwargs):\n return sns.barplot(data = pd.DataFrame.from_dict([dict_obj]).melt(), x = \"variable\", y=\"value\", hue=\"variable\", **kwargs).set_title(plot_title)\n\n\n# + id=\"Qwd4P9J_AHpF\"\nplt.figure(figsize=(15,8))\nplot_from_dict(get_class_distribution(rps_dataset), plot_title=\"Entire Dataset (before train/val/test split)\")\n\n# + [markdown] id=\"-QlXCEWW-b-T\"\n# # Get Train and Validation Samples\n# We use SubsetRandomSampler to make our train and validation loaders. SubsetRandomSampler is used so that each batch receives a random distribution of classes.\n#\n\n# + id=\"hnUdF35C-dDv\"\nrps_dataset_size = len(rps_dataset)\nrps_dataset_indices = list(range(rps_dataset_size))\n\n# + [markdown] id=\"odJttOKp-BNw\"\n# Shuffle the list of indices using np.shuffle.\n\n# + id=\"uCtxHA4o-5hA\"\nnp.random.shuffle(rps_dataset_indices)\n\n# + [markdown] id=\"Uuzc8BHj_Ckn\"\n# Create the split index. We choose the split index to be 20% (0.2) of the dataset size.\n\n# + id=\"kDSqcSnm_DI5\"\nval_split_index = int(np.floor(0.2 * rps_dataset_size))\n\n# + [markdown] id=\"9jdUinG__ORg\"\n# Slice the lists to obtain 2 lists of indices, one for train and other for test.\n#\n# > 0-----------val_split_index------------------------------n \n#\n# ---\n#\n#\n# > Train => val_split_index to n\n# Indented block\n#\n#\n# Val => 0 to val_split_index\n\n# + id=\"ySFNIz06_e3q\"\ntrain_idx = rps_dataset_indices[val_split_index:]\nval_idx = rps_dataset_indices[:val_split_index]\n\n# + [markdown] id=\"BcHj5EFS_kC4\"\n# Create samplers\n\n# + id=\"5_PCHuu6_iLP\"\ntrain_sampler = SubsetRandomSampler(train_idx)\nval_sampler = SubsetRandomSampler(val_idx)\n\n# + [markdown] id=\"cmjI57j6AbiY\"\n# # Now lets load our datasets\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"elapsed\": 4310, \"status\": \"ok\", \"timestamp\": 1651067746793, \"user\": {\"displayName\": \"Mary Abgaryan\", \"userId\": \"01901391193697622836\"}, \"user_tz\": -240} id=\"R_L1LG2oAeTE\" outputId=\"f4ad24eb-780b-4288-c204-65a9d769aec1\"\nrps_dataset_test = datasets.ImageFolder(root = root_dir + \"test (1)\",\n transform = image_transforms[\"test\"])\nrps_dataset_test\n\n\n# + [markdown] id=\"llJZXSG9Andf\"\n# # Train, Validation, and Test Dataloader\n#\n\n# + [markdown] id=\"uhYaXXg1jFtv\"\n# my_collate function skips files that are none, just pass it as a DataLoader parameter\n\n# + id=\"ihQu-_xcjDeH\"\ndef my_collate(batch):\n \"Puts each data field into a tensor with outer dimension batch size\"\n batch = list(filter(lambda x:x is not None, batch))\n return default_collate(batch)\n\n\n# + id=\"7DOrbMtcAorf\"\ntrain_loader = DataLoader(dataset=rps_dataset, shuffle=False, batch_size=128, sampler=train_sampler, collate_fn=my_collate)\nval_loader = DataLoader(dataset=rps_dataset, shuffle=False, batch_size=1, sampler=val_sampler, collate_fn=my_collate)\ntest_loader = DataLoader(dataset=rps_dataset_test, shuffle=False, batch_size=1,collate_fn=my_collate)\n\n\n# + [markdown] id=\"PUtZTfeNAvK_\"\n# # Explore The Data\n# To explore our train and val data-loaders, let’s create a new function that takes in a data-loader and returns a dictionary with class counts.\n# * Initialize a dictionary count_dict to all 0s.\n# * If the batch_size of the dataloader_obj is 1, then loop through the dataloader_obj and update the counter.\n# * Else, if the batch_size of the dataloader_obj is not 1, then loop through the dataloader_obj to obtain batches. Loop through the batches to obtain individual tensors. \n# * Now, updated the counter accordingly.\n#\n\n# + id=\"31NKoZqnA3hr\"\ndef get_class_distribution_loaders(dataloader_obj, dataset_obj):\n count_dict = {k:0 for k,v in dataset_obj.class_to_idx.items()}\n if dataloader_obj.batch_size == 1: \n for _,label_id in dataloader_obj:\n y_idx = label_id.item()\n y_lbl = idx2class[y_idx]\n count_dict[str(y_lbl)] += 1\n else: \n for _,label_id in dataloader_obj:\n for idx in label_id:\n y_idx = idx.item()\n y_lbl = idx2class[y_idx]\n count_dict[str(y_lbl)] += 1\n return count_dict\n\n\n# + id=\"pwVCS4PUCKJC\"\nfig, axes = plt.subplots(nrows=1, ncols=2, figsize=(18,7))\nplot_from_dict(get_class_distribution_loaders(train_loader, rps_dataset), plot_title=\"Train Set\", ax=axes[0])\nplot_from_dict(get_class_distribution_loaders(val_loader, rps_dataset), plot_title=\"Val Set\", ax=axes[1])\n\n# + [markdown] id=\"MNLv3lQ3BY4v\"\n# single_batch is a list of 2 elements. \n# * The first element (0th index) contains the image tensors \n# * the second element (1st index) contains the output labels.\n# Here’s the first element of the list which is a tensor. \n#\n#\n# ---\n#\n#\n# This tensor is of the shape `(batch, channels, height, width)`.\n\n# + id=\"6jm9KJ0aBO7t\"\nsingle_batch = next(iter(train_loader))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"elapsed\": 31, \"status\": \"ok\", \"timestamp\": 1651067800617, \"user\": {\"displayName\": \"Mary Abgaryan\", \"userId\": \"01901391193697622836\"}, \"user_tz\": -240} id=\"ZOG_BNICB69U\" outputId=\"3bd0d9ec-8a26-4cc7-ef7d-50ad889f1354\"\nprint(\"Output label tensors: \", single_batch[1])\nprint(\"\\nOutput label tensor shape: \", single_batch[1].shape)\n\n# + [markdown] id=\"29R0TrsCCskF\"\n# To plot the image, we’ll use plt.imshow from matloptlib. It expects the image dimension to be (height, width, channels). We'll .permute() our single image tensor to plot it.\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"elapsed\": 21, \"status\": \"ok\", \"timestamp\": 1651067800618, \"user\": {\"displayName\": \"Mary Abgaryan\", \"userId\": \"01901391193697622836\"}, \"user_tz\": -240} id=\"4E6dJFijCtMX\" outputId=\"0fc53807-52f1-46ec-b20f-f8c2c8a2e069\"\n# Selecting the first image tensor from the batch. \nsingle_image = single_batch[0][0]\nsingle_image.shape\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 303} executionInfo={\"elapsed\": 18, \"status\": \"ok\", \"timestamp\": 1651067800618, \"user\": {\"displayName\": \"Mary Abgaryan\", \"userId\": \"01901391193697622836\"}, \"user_tz\": -240} id=\"B2VXhbOVCzYD\" outputId=\"c7330b49-701b-4638-9369-77ab474d5649\"\nplt.imshow(single_image.permute(2, 1, 0))\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 630} executionInfo={\"elapsed\": 4800, \"status\": \"ok\", \"timestamp\": 1651067805403, \"user\": {\"displayName\": \"Mary Abgaryan\", \"userId\": \"01901391193697622836\"}, \"user_tz\": -240} id=\"EMWnXkALC5w-\" outputId=\"8eeefeea-39e3-4265-dc37-b47e78c088fc\"\n# We do single_batch[0] because each batch is a list \n# where the 0th index is the image tensor and 1st index is the\n# output label.\nsingle_batch_grid = utils.make_grid(single_batch[0], nrow=4)\nplt.figure(figsize = (10,10))\nplt.imshow(single_batch_grid.permute(1, 2, 0))\n\n\n# + [markdown] id=\"OGTOfvF0D7VM\"\n# # Now let's train the code\n\n# + [markdown] id=\"Tsipk6jUFh__\"\n# For calculating the accuracy we compare the predicted classes and the actual classes to calculate the accuracy.\n\n# + id=\"mKre0mbAFmMi\"\ndef multi_acc(y_pred, y_test): \n correct_pred = (y_pred == y_test).float()\n acc = correct_pred.sum() / len(correct_pred)\n acc = torch.round(acc * 100)\n return acc\n\n\n# + [markdown] id=\"0xn2G06OFsa6\"\n# We’ll also define 2 dictionaries which will store the accuracy/epoch and loss/epoch for both train and validation sets.\n\n# + id=\"JuS2lea_FvEF\"\naccuracy_stats = {\n 'train': [],\n \"val\": []\n}\n\nloss_stats = {\n 'train': [],\n \"val\": []\n}\n\n# + [markdown] id=\"EtCxPrhXMgAM\"\n# # AlexNet\n\n# + id=\"Bhz1Ze6KUq0Y\" colab={\"base_uri\": \"https://localhost:8080/\"} executionInfo={\"status\": \"ok\", \"timestamp\": 1651072439511, \"user_tz\": -240, \"elapsed\": 1863, \"user\": {\"displayName\": \"Mary Abgaryan\", \"userId\": \"01901391193697622836\"}} outputId=\"946169ee-5c02-4155-8762-1ffa11b1401d\"\nalexnet = torch.hub.load('pytorch/vision:v0.10.0', 'alexnet', pretrained=True)\n# model = models.alexnet(pretrained)\nclassifier = list(alexnet.classifier.children())\nalexnet.classifier = nn.Sequential(*classifier[:-1])\nnum_classes = 5\nalexnet.classifier.add_module(\n '5', nn.Linear(classifier[-1].in_features, num_classes))\nalexnet.eval()\nalexnet.to(device)\n\n# + id=\"dzXVZajbvhd_\"\nmodel = alexnet\noptimizer = torch.optim.SGD(model.parameters(),lr=0.001) \nloss_fn = nn.MSELoss() #CrossEntropyLoss with class_weights.\n\n# + [markdown] id=\"sblHGwT2MOKj\"\n# # ResNet34\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 1000, \"referenced_widgets\": [\"681e4de9239d43eaba802bc6c17fef86\", \"aa2de5c450e34ca0ab5b465aca3c6dc4\", \"0fa278277a4d461db6f39913c3598666\", \"8107cdd611b6420d892f5be4554198c2\", \"d4b6080312a042138d010ff994da685f\", \"f0c768db77144f6a90d54d91220c58fa\", \"cc7fe7b7050c46b19447486ddb530bbc\", \"34a24e2cc1b24418b64a06d4f7f3e56c\", \"b5c439e9a3d149f1ada24cad380ace41\", \"32f19a43369241b1965bbd59895ad59b\", \"c06b912e3a6d4bdfbc4edbca2ea5e405\"]} executionInfo={\"elapsed\": 10972, \"status\": \"ok\", \"timestamp\": 1651053229134, \"user\": {\"displayName\": \"Mary Abgaryan\", \"userId\": \"01901391193697622836\"}, \"user_tz\": -240} id=\"UzI9Ml_lBtl_\" outputId=\"0cf97a9b-0e8e-49bd-e358-9b0cb312fa70\"\n#Since we've less data, we'll use Transfer learning.\nmodel = models.resnet34(pretrained=True) #Downloads the resnet34 model which is pretrained on Imagenet dataset.\n\n#Replace the Final layer of pretrained resnet34 with 4 new layers.\nmodel.fc = nn.Sequential(nn.Linear(512,256),\n nn.ReLU(inplace=True),\n nn.Linear(256,128),\n nn.ReLU(inplace=True),\n nn.Linear(128,64),\n nn.ReLU(inplace=True),\n nn.Linear(64,5), \n )\n \nmodel.eval()\nmodel.to(device)\n\n# + [markdown] id=\"q4QdPrcEG61h\"\n# Visualize Loss and Accuracy\n# To plot the loss and accuracy line plots, we again create a dataframe from the accuracy_stats and loss_stats dictionaries.\n#\n\n# + id=\"TpkcjsciovOE\"\n# path to save model, optimizer ....\n# to then read and resume training\nPATH = \"/content/drive/MyDrive/ML Project/Diabetic Retinopathy/Saved Model/alexnet.pt\"\n\n# + [markdown] id=\"n-SRq8WepQHl\"\n# To load the model use\n\n# + id=\"2QuRtqaUCKIb\"\nclass_weights = torch.tensor([0.4058, 1.9795, 0.7331, 3.7948, 2.4827],dtype=torch.float).to(device)\n\noptimizer = torch.optim.SGD(model.parameters(),lr=0.001) \ncriterion = nn.MSELoss() \n\nnb_epochs = 60\n\n# + id=\"SiwxJSZepOQj\"\ncheckpoint = torch.load(PATH)\nmodel.load_state_dict(checkpoint['model_state_dict'])\noptimizer.load_state_dict(checkpoint['optimizer_state_dict'])\n\n# + id=\"K1YpekydoHJ0\"\nprint(\"Begin training.\")\nfor e in tqdm(range(1, nb_epochs)):\n # TRAINING\n train_epoch_loss = 0\n train_epoch_acc = 0\n model.train()\n for X_train_batch, y_train_batch in train_loader:\n X_train_batch, y_train_batch = X_train_batch.to(device), y_train_batch.to(device)\n optimizer.zero_grad()\n\n y_train_pred = model(X_train_batch)\n y_train_pred = torch.argmax(y_train_pred, dim=1)\n\n y_train_pred = y_train_pred.to(torch.float32) \n y_train_batch = y_train_batch.to(torch.float32) \n\n train_loss = criterion(y_train_pred, y_train_batch)\n train_loss.requires_grad_(requires_grad=True)\n\n train_acc = multi_acc(y_train_pred, y_train_batch)\n\n train_loss.backward()\n optimizer.step()\n train_epoch_loss += train_loss.item()\n train_epoch_acc += train_acc.item()\n # VALIDATION\n with torch.no_grad():\n model.eval()\n val_epoch_loss = 0\n val_epoch_acc = 0\n for X_val_batch, y_val_batch in val_loader:\n X_val_batch, y_val_batch = X_val_batch.to(device), y_val_batch.to(device)\n\n y_val_pred = model(X_val_batch)\n y_val_pred = torch.argmax(y_val_pred, dim=1)\n\n y_val_pred = y_val_pred.to(torch.float32) \n y_val_batch = y_val_batch.to(torch.float32) \n\n val_loss = criterion(y_val_pred, y_val_batch)\n val_loss.requires_grad_(requires_grad=True)\n\n val_acc = multi_acc(y_val_pred, y_val_batch)\n\n val_epoch_loss += train_loss.item()\n val_epoch_acc += train_acc.item()\n loss_stats['train'].append(train_epoch_loss/len(train_loader))\n loss_stats['val'].append(val_epoch_loss/len(val_loader))\n accuracy_stats['train'].append(train_epoch_acc/len(train_loader))\n accuracy_stats['val'].append(val_epoch_acc/len(val_loader))\n print(f'Epoch {e+0:02}: | Train Loss: {train_epoch_loss/len(train_loader):.5f} | Val Loss: {val_epoch_loss/len(val_loader):.5f} | Train Acc: {train_epoch_acc/len(train_loader):.3f}| Val Acc: {val_epoch_acc/len(val_loader):.3f}')\n\n# + [markdown] id=\"ibNNFQjsqW5s\"\n# # Save Model\n\n# + id=\"AevksaVRqWUw\"\nPATH = \"/content/drive/MyDrive/ML Project/Diabetic Retinopathy/Saved Model/alexnet.pt\"\ntorch.save({\n 'epoch': e,\n 'model_state_dict': model.state_dict(),\n 'optimizer_state_dict': optimizer.state_dict(),\n }, PATH)\n\n# + [markdown] id=\"1cakH9HSpI4Y\"\n# # Visualize Loss and Accuracy\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 531} id=\"MQjhkRmLo-GI\" executionInfo={\"status\": \"ok\", \"timestamp\": 1651087541535, \"user_tz\": -240, \"elapsed\": 1470, \"user\": {\"displayName\": \"Mary Abgaryan\", \"userId\": \"01901391193697622836\"}} outputId=\"81cc5e64-4c53-47df-e59a-13e2bc74f4ad\"\ntrain_val_acc_df = pd.DataFrame.from_dict(accuracy_stats).reset_index().melt(id_vars=['index']).rename(columns={\"index\":\"epochs\"})\ntrain_val_loss_df = pd.DataFrame.from_dict(loss_stats).reset_index().melt(id_vars=['index']).rename(columns={\"index\":\"epochs\"})\n\n# Plot line charts\nfig, axes = plt.subplots(nrows=1, ncols=2, figsize=(30,10))\nsns.lineplot(data=train_val_acc_df, x = \"epochs\", y=\"value\", hue=\"variable\", ax=axes[0]).set_title('Train-Val Accuracy/Epoch')\nsns.lineplot(data=train_val_loss_df, x = \"epochs\", y=\"value\", hue=\"variable\", ax=axes[1]).set_title('Train-Val Loss/Epoch')\n\n# + id=\"mmOMh9UJGDXF\"\nprint(\"Begin training.\")\nfor e in tqdm(range(1, 100)):\n # TRAINING\n model.train()\n for X_train_batch, y_train_batch in train_loader:\n X_train_batch, y_train_batch = X_train_batch.to(device), y_train_batch.to(device)\n optimizer.zero_grad()\n \n y_train_pred = model(X_train_batch)\n y_train_pred = torch.argmax(y_train_pred, dim=1)\n\n\n y_train_pred = y_train_pred.to(torch.float32) \n y_train_batch = y_train_batch.to(torch.float32) \n\n\n train_loss = criterion(y_train_pred, y_train_batch)\n train_loss.requires_grad_(requires_grad=True)\n # train_acc = torch.round(sum(y_train_pred == y_train_batch) * 100)\n train_acc = multi_acc(y_train_pred,y_train_batch)\n \n train_loss.backward()\n optimizer.step()\n train_epoch_loss += train_loss.item()\n train_epoch_acc += train_acc.item()\n # VALIDATION\n with torch.no_grad():\n model.eval()\n \n for X_val_batch, y_val_batch in val_loader:\n X_val_batch, y_val_batch = X_val_batch.to(device), y_val_batch.to(device)\n y_val_pred = model(X_val_batch)\n val_loss = criterion(y_val_pred, y_val_batch)\n val_acc = multi_acc(y_val_pred, y_val_batch)\n val_epoch_loss += train_loss.item()\n val_epoch_acc += train_acc.item()\n loss_stats['train'].append(train_epoch_loss/len(train_loader))\n loss_stats['val'].append(val_epoch_loss/len(val_loader))\n accuracy_stats['train'].append(train_epoch_acc/len(train_loader))\n accuracy_stats['val'].append(val_epoch_acc/len(val_loader))\n print(f'Epoch {e+0:02}: | Train Loss: {train_epoch_loss/len(train_loader):.5f} | Val Loss: {val_epoch_loss/len(val_loader):.5f} | Train Acc: {train_epoch_acc/len(train_loader):.3f}| Val Acc: {val_epoch_acc/len(val_loader):.3f}')\n torch.save({\n 'epoch': e,\n 'model_state_dict': model.state_dict(),\n 'optimizer_state_dict': optimizer.state_dict(),\n 'val_epoch_loss': val_epoch_loss,\n 'train_epoch_acc': train_epoch_acc,\n 'val_epoch_acc': val_epoch_acc,\n 'train_epoch_loss': train_epoch_loss,\n }, PATH)\n \n train_epoch_loss = 0\n train_epoch_acc = 0\n val_epoch_loss = 0\n val_epoch_acc = 0\n\n\n# + [markdown] id=\"p2JRn7KKa1El\"\n# #train\n#\n\n# + id=\"OY4_OHDba28S\"\ndef train(train_dataloader,model,loss_fn,optimizer):\n '''\n train function updates the weights of the model based on the\n loss using the optimizer in order to get a lower loss.\n \n Args :\n dataloader: Iterator for the batches in the data_set.\n model: Given an input produces an output by multiplying the input with the model weights.\n loss_fn: Calculates the discrepancy between the label & the model's predictions.\n optimizer: Updates the model weights.\n \n Returns :\n Average loss per batch which is calculated by dividing the losses for all the batches\n with the number of batches.\n Average Accurracy which is calculated by dividing correctly predicted by the size of batch.\n '''\n\n model.train() #Sets the model for training.\n \n total = 0\n correct = 0\n running_loss = 0\n \n for batch,(x,y) in enumerate(train_dataloader): #Iterates through the batches.\n \n output = model(x.to(device)) #model's predictions.\n loss = loss_fn(output,y.to(device)) #loss calculation.\n \n running_loss += loss.item()\n \n total += y.size(0)\n predictions = output.argmax(dim=1).cpu().detach() #Index for the highest score for all the samples in the batch.\n correct += (predictions == y.cpu().detach()).sum().item() #No.of.cases where model's predictions are equal to the label.\n \n optimizer.zero_grad() #Gradient values are set to zero.\n loss.backward() #Calculates the gradients.\n optimizer.step() #Updates the model weights.\n \n \n avg_loss = running_loss/len(train_dataloader) # Average loss for a single batch\n avg_accuracy = 100*(correct/total)\n print(f'\\nTraining Loss = {avg_loss:.6f}',end='\\t')\n print(f'Accuracy on Training set = {avg_accuracy:.6f}% [{correct}/{total}]') #Prints the Accuracy.\n \n return avg_loss, avg_accuracy\n\n\n# + [markdown] id=\"K8JfmXSObPY9\"\n# # Validation\n\n# + id=\"R7sCNM7ObQv1\"\ndef validate(val_dataloader,model,loss_fn):\n '''\n validate function calculates the average loss per batch and the accuracy of the model's predictions.\n \n Args :\n dataloader: Iterator for the batches in the data_set.\n model: Given an input produces an output by multiplying the input with the model weights.\n loss_fn: Calculates the discrepancy between the label & the model's predictions.\n \n Returns :\n Average loss per batch which is calculated by dividing the losses for all the batches\n with the number of batches.\n Average Accurracy which is calculated by dividing correctly predicted by the size of batch\n '''\n \n model.eval() #Sets the model for evaluation.\n \n total = 0\n correct = 0\n running_loss = 0\n \n with torch.no_grad(): #No need to calculate the gradients.\n \n for x,y in val_dataloader:\n \n output = model(x.to(device)) #model's output.\n loss = loss_fn(output,y.to(device)).item() #loss calculation.\n running_loss += loss\n \n total += y.size(0)\n predictions = output.argmax(dim=1).cpu().detach()\n correct += (predictions == y.cpu().detach()).sum().item()\n \n avg_loss = running_loss/len(val_dataloader) #Average loss per batch. \n avg_accuracy = 100*(correct/total)\n\n print(f'\\nValidation Loss = {avg_loss:.6f}',end='\\t')\n print(f'Accuracy on Validation set = {avg_accuracy:.6f}% [{correct}/{total}]') #Prints the Accuracy.\n \n return avg_loss, avg_accuracy\n\n\n\n# + [markdown] id=\"DFqzqkIib-qW\"\n# # Optimize the Mode\n\n# + id=\"aQdV74e3b_v6\"\ndef optimize(train_dataloader,valid_dataloader,model,loss_fn,optimizer,nb_epochs, PATH):\n '''\n optimize function calls the train & validate functions for (nb_epochs) times.\n \n Args :\n train_dataloader: DataLoader for the train_set.\n valid_dataloader: DataLoader for the valid_set.\n model: Given an input produces an output by multiplying the input with the model weights.\n loss_fn: Calculates the discrepancy between the label & the model's predictions.\n optimizer: Updates the model weights.\n nb_epochs: Number of epochs.\n \n Returns :\n Tuple of lists containing losses and accuracyes for all the epochs.\n '''\n #Lists to store losses for all the epochs.\n train_losses = []\n valid_losses = []\n\n train_accuracys = []\n valid_accuracys = []\n\n for epoch in range(nb_epochs):\n print(f'\\nEpoch {epoch+1}/{nb_epochs}')\n print('-------------------------------')\n train_loss, train_accuracy = train(train_dataloader,model,loss_fn,optimizer) #Calls the train function.\n train_losses.append(train_loss)\n train_accuracys.append(train_accuracy)\n valid_loss, val_accuracy = validate(valid_dataloader,model,loss_fn) #Calls the validate function.\n valid_losses.append(valid_loss)\n valid_accuracys.append(val_accuracy)\n \n print('\\nTraining has completed!')\n \n return train_losses,train_accuracys,valid_losses,valid_accuracys, epoch\n\n\n# + [markdown] id=\"GCaVt_NIMuNw\"\n# Since the classes are inbalanced, we use class weights in the loss function\n\n# + id=\"EhZOs7uscpbL\"\nnb_epochs = 10\n#Call the optimize function.\ntrain_losses, train_accuracy, valid_losses, val_accuracy, epoch = optimize(train_loader,val_loader,model,loss_fn,optimizer,nb_epochs, PATH)\n\n\nloss_stats['train'].append(train_losses)\nloss_stats['val'].append(valid_losses)\naccuracy_stats['train'].append(train_accuracy)\naccuracy_stats['val'].append(val_accuracy)\ntorch.save({\n 'epoch': epoch,\n 'model_state_dict': model.state_dict(),\n 'optimizer_state_dict': optimizer.state_dict(),\n 'val_epoch_loss': valid_losses,\n 'train_epoch_acc': train_accuracy,\n 'val_epoch_acc': val_accuracy,\n 'train_epoch_loss': train_losses,\n }, PATH)\n\n# + id=\"bbNK1CkfBWOE\"\ntorch.save({\n 'epoch': 25,\n 'model_state_dict': model.state_dict(),\n 'optimizer_state_dict': optimizer.state_dict(),\n }, PATH)\n\n# + id=\"OC7ALURv-8oU\"\n#Plot the graph of train_losses & valid_losses against nb_epochs.\nepochs = range(nb_epochs)\nplt.plot(epochs, train_losses, 'g', label='Training loss')\nplt.plot(epochs, valid_losses, 'b', label='validation loss')\nplt.title('Training and Validation loss')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.legend()\nplt.show()\n\n# + id=\"7VZ1g0TjfiXr\"\n# print(\"Begin training.\")\n\n\n# for e in tqdm(range(0, 100)):\n# # TRAINING\n# model.train()\n# total = 0\n# correct = 0\n# running_loss = 0\n# for X_train_batch, y_train_batch in train_loader:\n \n\n# y_train_batch = y_train_batch.type(torch.LongTensor) # <---- Here (casting)\n# X_train_batch, y_train_batch = X_train_batch.to(device), y_train_batch.to(device)\n# optimizer.zero_grad()\n\n# train_epoch_loss = 0\n# train_epoch_acc = 0\n\n# y_train_pred = model(X_train_batch)\n# # y_train_pred = torch.argmax(y_train_pred, dim=1)\n\n\n# y_train_pred = y_train_pred.to(torch.float32) \n# # y_train_batch = y_train_batch.to(torch.float32) \n\n# # print('y_train_pred.shape',y_train_pred.shape)\n# # print(\"y_train_batch\", y_train_batch.shape)\n\n# train_loss = criterion(y_train_pred, y_train_batch)\n# # train_loss.requires_grad_(requires_grad=True)\n# # train_acc = torch.round(sum(y_train_pred == y_train_batch) * 100)\n# running_loss += train_loss.item()\n \n# total += y_train_batch.size(0)\n# predictions = y_train_pred.argmax(dim=1).cpu().detach() #Index for the highest score for all the samples in the batch.\n# correct += (predictions == y_train_batch.cpu().detach()).sum().item() #No.of.cases where model's predictions are equal to the label.\n \n# train_loss.backward()\n# optimizer.step()\n\n# # VALIDATION\n# with torch.no_grad():\n# model.eval()\n# total_val = 0\n# correct_val = 0\n# running_loss_val = 0\n \n# for X_val_batch, y_val_batch in val_loader:\n# X_val_batch, y_val_batch = X_val_batch.to(device), y_val_batch.to(device)\n# y_val_pred = model(X_val_batch)\n# val_loss = criterion(y_val_pred, y_val_batch)\n\n# running_loss_val += val_loss.item()\n \n# total_val += y_val_batch.size(0)\n# predictions_val = y_val_pred.argmax(dim=1).cpu().detach() #Index for the highest score for all the samples in the batch.\n# correct_val += (predictions_val == y_val_batch.cpu().detach()).sum().item() #No.of.cases where model's predictions are equal to the label.\n \n\n# train_avg_loss = running_loss/len(train_loader) # Average loss for a single batch\n# train_avg_accuracy = 100*(correct/total)\n# print(f'\\nTraining Loss = {train_avg_loss:.6f}',end='\\t')\n# print(f'Accuracy on Training set = {100*(correct/total):.6f}% [{correct}/{total}]') #Prints the Accuracy.\n\n# val_avg_loss = running_loss_val/len(val_loader) # Average loss for a single batch\n# val_avg_accuracy = 100*(correct_val/total_val)\n# print(f'\\nValidation Loss = {val_avg_loss:.6f}',end='\\t')\n# print(f'Accuracy on Validation set = {100*(correct_val/total_val):.6f}% [{correct_val}/{total_val}]') #Prints the Accuracy.\n\n\n# loss_stats['train'].append(train_avg_loss)\n# loss_stats['val'].append(val_avg_loss)\n# accuracy_stats['train'].append(train_avg_accuracy)\n# accuracy_stats['val'].append(val_avg_accuracy)\n# torch.save({\n# 'epoch': e,\n# 'model_state_dict': model.state_dict(),\n# 'optimizer_state_dict': optimizer.state_dict(),\n# 'val_epoch_loss': val_avg_loss,\n# 'train_epoch_acc': train_epoch_acc,\n# 'val_epoch_acc': val_avg_accuracy,\n# 'train_epoch_loss': train_epoch_loss,\n# }, PATH)\n \n\n# + id=\"DjGyH5OEG4uW\"\ntrain_val_acc_df = pd.DataFrame.from_dict(accuracy_stats).reset_index().melt(id_vars=['index']).rename(columns={\"index\":\"epochs\"})\ntrain_val_loss_df = pd.DataFrame.from_dict(loss_stats).reset_index().melt(id_vars=['index']).rename(columns={\"index\":\"epochs\"})\n\n# Plot line charts\nfig, axes = plt.subplots(nrows=1, ncols=2, figsize=(30,10))\nsns.lineplot(data=train_val_acc_df, x = \"epochs\", y=\"value\", hue=\"variable\", ax=axes[0]).set_title('Train-Val Accuracy/Epoch')\nsns.lineplot(data=train_val_loss_df, x = \"epochs\", y=\"value\", hue=\"variable\", ax=axes[1]).set_title('Train-Val Loss/Epoch')\n\n# + [markdown] id=\"8BmGqtf-HIwU\"\n# # Test\n# After training is done, we need to test how our model fared. Note that we’ve used model.eval() before we run our testing code. To tell PyTorch that we do not want to perform back-propagation during inference, we use torch.no_grad(), just like we did it for the validation loop above.\n# * We start by defining a list that will hold our predictions. Then we loop through our batches using the test_loader. For each batch -\n# * We move our input mini-batch to GPU.\n# * We make the predictions using our trained model.\n# * Apply log_softmax activation to the predictions and pick the index of highest probability.\n# * Move the batch to the GPU from the CPU.\n# * Convert the tensor to a numpy object and append it to our list.\n#\n\n# + id=\"a-CWwzyuHYmU\"\ny_pred_list = []\ny_true_list = []\nwith torch.no_grad():\n for x_batch, y_batch in tqdm(test_loader):\n x_batch, y_batch = x_batch.to(device), y_batch.to(device)\n y_test_pred = model(x_batch)\n _, y_pred_tag = torch.max(y_test_pred, dim = 1)\n y_pred_list.append(y_pred_tag.cpu().numpy())\n y_true_list.append(y_batch.cpu().numpy())\n\n# + id=\"omiERKy8HV8J\"\ny_pred_list = [i for i in y_pred_list]\ny_true_list = [i for i in y_true_list]\n\n# + [markdown] id=\"RJxz9FfmHeUw\"\n# # Print classification report\n\n# + id=\"DOaGW5Q1Hh51\"\nprint(classification_report(y_true_list, y_pred_list))\n\n# + [markdown] id=\"qmE9z43yHk9t\"\n# # Confusion matrix\n\n# + id=\"pP_mUmcyHkZz\"\nprint(confusion_matrix(y_true_list, y_pred_list))\n\n# + id=\"GVTSKZUcHqpq\"\nconfusion_matrix_df = pd.DataFrame(confusion_matrix(y_true_list, y_pred_list)).rename(columns=idx2class, index=idx2class)\nfig, ax = plt.subplots(figsize=(7,5)) \nsns.heatmap(confusion_matrix_df, annot=True, ax=ax)\n","repo_name":"diana-sargsyan/Diabetic_Retinopathy","sub_path":"Diabetic Retinopathy/Neural_nets.ipynb","file_name":"Neural_nets.ipynb","file_ext":"py","file_size_in_byte":34014,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"38"} +{"seq_id":"73785568110","text":"# + [markdown] pycharm={\"name\": \"#%% md\\n\"}\n# # On the Objective Functions\n# ### 1. Context\n#\n# Given:\n# \\begin{align}\n# Z &= \\begin{bmatrix}\n# z_{1, 1} & z_{1, 2} & \\dots & z_{1, N} \\\\\n# z_{2, 1} & z_{2, 2} & \\dots & z_{2, N} \\\\\n# z_{3, 1} & z_{3, 2} & \\dots & z_{3, N} \\\\\n# \\vdots & \\vdots & \\ddots & \\vdots\\\\\n# z_{T, 1} & z_{t, 2} & \\dots & z_{T, N} \\\\\n# \\end{bmatrix}_{T \\times N, T >> N} \\\\\n# \\Sigma & \\equiv Z^{T}Z\\\\\n# \\Sigma &= V\\Lambda V^{T} \\\\\n# V^{T} V &= I \\\\\n# \\Lambda &= \\begin{bmatrix}\n# \\lambda_{1} & 0 & \\dots & 0 \\\\\n# 0 & \\lambda_{2} & \\dots & 0 \\\\\n# \\vdots & \\vdots & \\ddots & \\vdots\\\\\n# 0 & 0 & \\dots & \\lambda_{N} \\\\\n# \\end{bmatrix}_{N \\times N} \\\\\n# V &= \\begin{bmatrix}\n# v_{1, 1} & v_{1, 2} & \\dots & v_{1, N} \\\\\n# v_{2, 1} & v_{2, 2} & \\dots & v_{2, N} \\\\\n# \\vdots & \\vdots & \\ddots & \\vdots\\\\\n# v_{N, 1} & v_{N, 2} & \\dots & v_{N, N} \\\\\n# \\end{bmatrix}_{N \\times N}\n# \\end{align}\n#\n# We want to find the vector $x$ that maximizes following problem:\n#\n# \\begin{align}\n# \\arg \\max_{x} \\eta(x)\n# \\end{align}\n#\n# where\n#\n# \\begin{align}\n# \\eta (x) & \\equiv \\exp \\left( -\\sum^{N}_{j=1} \\theta_{j} \\ln{(\\theta_{j})} \\right)\n# \\end{align}\n#\n# and\n#\n# \\begin{align}\n# \\theta = diag\\left(V^{T} x\\right) \\Lambda V^{T} x = \\begin{bmatrix}\n# \\lambda_{1} \\left( \\sum^{N}_{i=1} x_{i}v_{i, 1}\\right)^{2} \\\\\n# \\lambda_{2} \\left( \\sum^{N}_{i=1} x_{i}v_{i, 2}\\right)^{2} \\\\\n# \\vdots \\\\\n# \\lambda_{N} \\left( \\sum^{N}_{i=1} x_{i}v_{i, N}\\right)^{2} \\\\\n# \\end{bmatrix}\n# \\end{align}\n#\n# When $\\theta$ is normalized so that $\\sum_{i=1}^{N} \\theta = 1$, $\\eta(x)$ is equivalent to the exponential of Shannon's entropy, which is maximized the $\\forall \\theta_{i}=\\theta_{j}$, in which case $\\eta (x) = N$.\n#\n#\n#\n# ### 2. Data\n# I am using random mock data here, just to illustrate the point.\n\n# + pycharm={\"name\": \"#%%\\n\"}\nimport numpy as np\nfrom scipy.stats import random_correlation\nimport scipy.linalg\nfrom scipy.optimize import minimize\nimport itertools\n\nseed = 0\n\nN = 4 # Number of columns of Z\nnp.random.seed(seed)\nl = np.random.exponential(size=4) # Eigenvectors of ZtZ = Sigma\nl = l * 4 / l.sum()\nl.sort()\nl = l[::-1]\n\n# Sigma Matrix\nSigma = random_correlation.rvs(\n eigs=l,\n random_state=np.random.default_rng(seed=seed)\n)\n\n# Eigen-decomposition of Sigma\nLambda, V = np.linalg.eig(Sigma)\nsort = Lambda.argsort()[::-1]\nLambda = Lambda[sort]\nLambda = np.diag(Lambda)\nV = V[:, sort]\n\nprint('Sigma Matrix:\\n', Sigma)\nprint('\\nLambda Matrix:\\n', Lambda)\nprint('\\nV Matrix:\\n', V)\n\n# + [markdown] pycharm={\"name\": \"#%% md\\n\"}\n# ### 3. Set of possible solutions\n#\n# Given that we know that the problem above achieve its maximum when $\\forall \\theta_{i}=\\theta_{j}$, the problem has a closed form solution (when unconstrained):\n#\n# \\begin{align}\n# \\theta &= \\boldsymbol{1}_{N} \\\\\n# diag\\left(V^{T} x\\right) \\Lambda V^{T} x &= \\boldsymbol{1}_{N}\\\\\n# \\Lambda^{\\frac{1}{2}}V^{T} x &= \\boldsymbol{1}_{N} \\\\\n# x^{\\star} &\\propto V \\Lambda^{-\\frac{1}{2}} \\boldsymbol{1}_{N}\n# \\end{align}\n#\n# For a given $\\Sigma$, there are $2^{N-1}$ solution vectors ($x$) that can yield $\\eta(w)=N$. This is due to the irrelevance of each eigen-vector's sign in the projection. The set of solutions $X_{N \\times 2^{N-1}}$ that spans all the possible linear transformations that result in $\\eta(w)=N$ is given by:\n#\n# \\begin{align}\n# X \\propto V \\Lambda^{-\\frac{1}{2}}J\n# \\end{align}\n#\n# where\n#\n# \\begin{align}\n# J = \\begin{bmatrix}\n# \\mid & \\mid & & \\mid \\\\\n# j_{1} & j_{2} & \\dots & j_{2^{N-1}} \\\\\n# \\mid & \\mid & & \\mid \\\\\n# \\end{bmatrix}_{N \\times 2^{N-1}}\n# \\end{align}\n#\n# Where each $j_{i}$ is a vector with entries 1 and -1 as entries that change the sign of each eigenvector, and together all $j$ span every possible combination of signs.\n#\n# The set of possible 16 solutions is shown below:\n\n# + pycharm={\"name\": \"#%%\\n\"}\ncombinations = [np.reshape(np.array(i), (N, 1)) for i in itertools.product([1, -1], repeat=N)]\nJ = np.concatenate(combinations, axis=1)\nX = V @ np.linalg.inv(np.sqrt(Lambda)) @ J\nX = np.divide(X, X.sum(axis=0))\n\nprint('Set of possible solutions:\\n')\nfor i in range(X.shape[1]):\n print(f'Sol {i + 1}:', X[:, i])\n\n\n# + [markdown] pycharm={\"name\": \"#%% md\\n\"}\n# ### 4. Original optimization problem\n#\n# \\begin{align}\n# \\arg \\max_{x} \\hspace{1em} \\exp \\left( -\\sum^{N}_{j=1} \\theta_{j} \\ln{(\\theta_{j})} \\right)\n# \\end{align}\n#\n# The solution given by the code below is one of the columns in the set of solutions. The function, when evaluated, yields N.\n\n# + pycharm={\"name\": \"#%%\\n\"}\ndef original_objfunc(x, Lambda, V):\n w = x.reshape(-1, 1)\n theta = np.diag((V.T @ w).flatten()) @ Lambda @ V.T @ w\n theta_norm = np.divide(theta.flatten(), theta.sum()) # Normalize the vector so it adds up to 1\n val = -np.exp(-np.sum(np.multiply(theta_norm, np.log(theta_norm))))\n return val\n\nopti = minimize(\n fun=original_objfunc,\n x0=np.array([1 / N] * N),\n args=(Lambda, V),\n method='SLSQP',\n options={'maxiter': 1E9, 'ftol': 1E-14}\n)\n\nprint('x: ', opti.x / opti.x.sum())\nprint('eval', original_objfunc(opti.x, Lambda, V))\n\n\n# + [markdown] pycharm={\"name\": \"#%% md\\n\"}\n# ### 3. Alternative optimization problem\n#\n# \\begin{align}\n# \\arg \\min_{x} \\hspace{1em} \\sum_{j=1}^{N} \\left( \\theta_{j} - c\\right)^{2}\n# \\end{align}\n#\n# where $c$ is a given constant.\n#\n# The solution given by the code below also is one of the columns in the set of solutions. The function, when evaluated, yields N.\n#\n\n# + pycharm={\"name\": \"#%%\\n\"}\ndef alternative_objfunc(x, Lambda, V, constant):\n w = x.reshape(-1, 1)\n theta = np.diag((V.T @ w).flatten()) @ Lambda @ V.T @ w\n c = constant * np.ones(shape=(len(x), 1))\n val = (theta - c).T @ (theta - c)\n return val.item()\n\nopti = minimize(\n fun=alternative_objfunc,\n x0=np.array([1 / N] * N),\n args=(Lambda, V, 1),\n method='SLSQP',\n options={'maxiter': 1E9, 'ftol': 1E-14}\n)\n\nprint('x: ', opti.x / opti.x.sum())\nprint('eval', original_objfunc(opti.x, Lambda, V))\n","repo_name":"fcoibanez/eigenportfolio","sub_path":"notebooks/objective_function_equivalence.ipynb","file_name":"objective_function_equivalence.ipynb","file_ext":"py","file_size_in_byte":5963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"38"} +{"seq_id":"9946060567","text":"# # Financial Analysis\n#\n# The idea here is to start with an analysis of the market data. So we start by observing the market by many visualisation and details.\n#\n# ## Initialisation\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport datetime\nimport pandas as pd\n\n# ## Reading of data\n\nstock = pd.read_csv('data/nasdaq/AAPL.csv', index_col=0)\nstock = stock[-1500:]\nprint(stock.index)\nstock.index = pd.to_datetime(stock.index, format=\"%d-%m-%Y\")\nprint(stock.index)\nstock.head()\n\n# ## First Visualisation\n\nstock['Open'].plot(label=\"AAPL\",figsize=(20,9), title='Open Price')\n\nstock['Volume'].plot(figsize=(20,9), title='Open Price')\n\nstock['Total Traded'] = stock['Volume']*stock['Open']\nstock['Total Traded'].plot(figsize=(20,9), title='Total Traded Price')\n\nstock['MA50'] = stock['Open'].rolling(50).mean()\nstock['MA200'] = stock['Open'].rolling(200).mean()\nstock[['Open','MA50','MA200']].plot(figsize=(20,9))\n\n# +\nfrom mplfinance.original_flavor import candlestick_ohlc\n\nfrom matplotlib.dates import DateFormatter, date2num, WeekdayLocator, DayLocator, MONDAY\n\n\nstock_reset = stock[\"2021\":].reset_index()\n\nstock_reset['date_ax'] = stock_reset['Date'].apply(lambda date: date2num(date))\nstock_values = [tuple(val) for val in stock_reset[['date_ax', 'Open', 'High', 'Low', 'Close']].values]\n\nmondays = WeekdayLocator(MONDAY)\nalldays = DayLocator()\nweekFormatter = DateFormatter(\"%b %d\")\ndayFormatter = DateFormatter('%d')\nfig, ax = plt.subplots()\nfig.set_figwidth(20)\nfig.set_figheight(9)\nfig.subplots_adjust(bottom=0.2)\nax.xaxis.set_minor_locator(alldays)\nax.xaxis.set_major_formatter(weekFormatter)\n\ncandlestick_ohlc(ax, stock_values, width=0.6, colorup='g', colordown='r',)\n\nplt.plot()\n# -\n\n# ## Daily Yield\n# $r_t= \\frac{p_t}{p_{t-1}}$\n#\n\n# stock['Returns'] = (stock['Close']/stock['Close'].shift(1))\nstock['Returns'] = stock['Close'].pct_change(1)\nstock.head()\n\nstock['Returns'].hist(bins=80)\n\nstock['Returns'].plot(kind='kde')\n\nbox_df = stock['Returns']\nbox_df.columns = ['Stock Returns']\nbox_df.plot(kind='box')\n\n# ## Cumulative Returns\n#\n# $i_t = (1+r_t)*i_{t-1}$\n\nstock['Cumulative Return'] = (1+stock['Returns']).cumprod()\n\nstock['Cumulative Return'].plot()\n","repo_name":"yohannts/market_strategy","sub_path":"analysis.ipynb","file_name":"analysis.ipynb","file_ext":"py","file_size_in_byte":2174,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"35"} +{"seq_id":"70547057061","text":"# +\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport math\nimport pandas as pd\n\nN = 7\nx = np.linspace(0,1,100)\n\ndef f_n(x, n):\n f = np.sin((2*n - 1)*np.pi*x)\n coeff = (-1)**(n+1)/(2*n - 1)**2\n return coeff*f\n\ndef f_N(x, N):\n f = np.zeros_like(x)\n for i in range(1, N+1):\n f = f + f_n(x, i)\n return f\n \nfig, ax = plt.subplots(1, 3, figsize= (20,2))\n\nfor i in range (0,3):\n ax[i].set_xlim([0,1])\n ax[i].set_xlabel(str(5*(2**i)) + 'terms')\n ax[i].plot(x, f_N(x, 5*(2**i)), 'r-')\n \nplt.savefig('K13.5.png')\n \n# -\n\n\n","repo_name":"LaneEllisor/Rogue-Waves-CofC-UCF-Project","sub_path":"Knobel13.5.ipynb","file_name":"Knobel13.5.ipynb","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"35"} +{"seq_id":"7785942181","text":"# # Multivariable Regression\n\n# ## Library & Data\n\n#import libraries\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns # visualisation\n\n#load the data\ndf = pd.read_csv('https://raw.githubusercontent.com/satishgunjal/datasets/master/multivariate_housing_prices_in_portlans_oregon.csv')\ndf.head() \n\n# +\nX = df.values[:, 0:2] # get input values from first two columns\ny = df.values[:, 2] # get output values from last coulmn\nm = len(y) # number of training examples\n\nprint('Total number of training examples (m) = %s \\n' %(m))\n\n# show only first 5 records\nfor i in range(5):\n print('x =', X[i, ], ', y =', y[i])\n# -\n\n# ## Correlation\n\n#plotting the interaction between the features\nx = pd.DataFrame(X)\ndef myplotGrid(X,y):\n \n fig = plt.figure(figsize=(12,12))\n #columns names\n x.columns = ['size(in square feet)', 'number of bedrooms']\n x['y'] = y\n # checking the correlation of the variables\n sns.pairplot(x, hue='y') \n plt.show()\n\n\nmyplotGrid(x,y)\n\n# ## Normalization\n\n# mean Normalization\n\"\"\"\nThe house and number of bedrooms are not in same range(house sizes are about 1000 times the number of bedrooms). \nThis will have negative impact on gradient descent algorithm performance.\nWe can avoid this by changing the range of our input variables with mean normalization\n\"\"\"\ndef feature_normalize(X):\n\n # we need mean of indivdual column here, hence axis = 0\n mean = np.mean(X, axis = 0) \n # the parameter ddof (Delta Degrees of Freedom) value is 1\n sd = np.std(X, axis= 0, ddof = 1) # Standard deviation (can also use range)\n X_norm = (X - mean)/sd\n return X_norm, mean, sd\n\n\nX, mean, sd = feature_normalize(X)\n\"\"\"\nNew mean or avearage value of normalized X feature is 0\n\"\"\"\nprint('mean= ', mean)\nprint('standard deviation= ', sd)\nprint('X_norm= ', X[:5])\n\n# using hstack() function from numpy to add column of ones to X feature \n# the final X matrix (feature matrix)\nX = np.hstack((np.ones((m,1)), X))\nX[:5]\n\nprint(X.shape)\nprint(y.shape)\n\n\n# ## Model\n\ndef model(X, Y, learning_rate, iteration):\n m = Y.size\n theta = np.zeros((3,1))\n cost_list = []\n for i in range(iteration):\n y_pred = np.dot(X, theta)\n cost = (1/(2*m))*np.sum(np.square(y_pred - Y))\n d_theta = (1/m)*np.dot(X.T, y_pred - Y)\n theta = theta - learning_rate*d_theta\n cost_list.append(cost)\n return theta, cost_list\n\n\niteration = 100\nlr = 0.00000005\ntheta, cost_list = model(X, y, learning_rate = lr,\niteration = iteration)\n\n# ## Prediction\n\nnew_houses = np.array([[1, 1547,2], [1, 1896,3], [1, 1934,3]]);\nfor house in new_houses :\n print(\"Our model predicts the price of house with\",\n house[1], \"sq. ft. area as : $\", round(np.dot(house, theta)[1],\n 3))\n\n\n","repo_name":"Gsidi9/ML-From-Scratch","sub_path":"Regression/multivariable_regression.ipynb","file_name":"multivariable_regression.ipynb","file_ext":"py","file_size_in_byte":2775,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-jupyter-script","pt":"35"} +{"seq_id":"24239496621","text":"# + [markdown] colab_type=\"text\" id=\"gFaG1l5_u92f\"\n# # Import Packages\n\n# +\nfrom __future__ import print_function\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nimport gensim\n\n#For Feature Engineering\nimport re\nimport random\nfrom scipy import sparse as sp\nimport string\nimport nltk\nfrom nltk.tokenize import wordpunct_tokenize,TweetTokenizer\nfrom sklearn.impute import KNNImputer\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nfrom time import time\nfrom sklearn.model_selection import StratifiedKFold\n\n\nimport tensorflow as tf\nimport random as rn\nimport os\nfrom tensorflow.keras import optimizers,backend as K\nfrom tensorflow.keras.preprocessing.text import Tokenizer\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\nfrom tensorflow.keras.models import Sequential, Model,load_model\nfrom tensorflow.keras.layers import Input,Dense, Dropout, Embedding,Conv1D,GlobalMaxPooling1D,Concatenate,GaussianNoise,LSTM,BatchNormalization,Activation\nfrom tensorflow.keras.utils import plot_model\nfrom tensorflow.keras import regularizers\n\n\n# + [markdown] colab_type=\"text\" id=\"-UTowTEE5IDO\"\n# # Function Definition\n\n# +\ndef MLP_model(model,df_train,df_test,sentence_vector=False):\n #Filter Data\n if not sentence_vector:\n #Feature Engineering\n df_train,df_test=PMI(df_train,df_test)\n for gram in [1,2,3,4]:\n df_train,df_test=rf_ngram(df_train,df_test,gram=gram)\n\n df_train=df_train.drop(['cashtag','spans','text','clean_text','base_text','source'],1)\n df_test=df_test.drop(['cashtag','spans','text','clean_text','base_text','source'],1)\n else:\n df_train=W2V_sentence_embedding(df_train)\n df_test=W2V_sentence_embedding(df_test)\n df_train=df_train.drop('source',1)\n df_test=df_test.drop('source',1)\n\n #Split data into dependent and independent variable\n X_train=df_train.drop(['sentiment score'],1)\n X_test=df_test.drop(['sentiment score'],1)\n y_train=df_train['sentiment score']\n y_test=df_test['sentiment score']\n\n #Impute Missing Testues\n imputer = KNNImputer(n_neighbors=3)\n X_train=pd.DataFrame(imputer.fit_transform(X_train))\n X_test=pd.DataFrame(imputer.fit_transform(X_test))\n\n #Predict \n y_pred=model.predict(X_test,batch_size=32)\n y_pred=pd.Series(y_pred.tolist()).apply(lambda x: x[0])\n print('Val Cosine Similarity:{} '.format(cosine_similarity(y_test,y_pred)))\n return y_pred\n\ndef model_CNN_LSTM(model,df_train,df_test):\n X_train=df_train['clean_text'].tolist()\n y_train=np.array(df_train['sentiment score'])\n X_test=df_test['clean_text'].tolist()\n y_test=np.array(df_test['sentiment score'])\n\n # prepare tokenizer\n t = Tokenizer()\n t.fit_on_texts(X_train)\n X_train = t.texts_to_sequences(X_train)\n X_test = t.texts_to_sequences(X_test)\n\n # Adding 1 because of reserved 0 index\n vocab_size = len(t.word_index) + 1\n\n X_train = pad_sequences(X_train, padding='post', maxlen=50)\n X_test = pad_sequences(X_test, padding='post', maxlen=50)\n\n #Predict \n y_pred=model.predict(X_test,batch_size=32)\n y_pred=pd.Series(y_pred.tolist()).apply(lambda x: x[0])\n print('Val Cosine Similarity:{} '.format(cosine_similarity(y_test,y_pred)))\n return y_pred\n\ndef grid_model_ensemble(df_train,df_test,hidden_nodes,dropout,l2_regularizer,act,optimizer,epochs,batch_size=16):\n X_train=df_train.drop(columns=['source','sentiment score'])\n y_train=df_train['sentiment score']\n X_test=df_test.drop(columns=['source','sentiment score'])\n y_test=df_test['sentiment score']\n\n #Define MLP Ensemble\n model = Sequential()\n if dropout==0:\n model.add(Dense(hidden_nodes,input_shape=(X_train.shape[1],),\n kernel_regularizer=regularizers.l2(l2_regularizer),activity_regularizer=regularizers.l2(l2_regularizer)))\n else:\n model.add(Dropout(dropout, input_shape=(X_train.shape[1],)))\n model.add(Dense(hidden_nodes,kernel_regularizer=regularizers.l2(l2_regularizer),activity_regularizer=regularizers.l2(l2_regularizer)))\n model.add(Activation(act))\n model.add(Dense(1,activation='tanh'))\n \n model.compile(loss='MSE',optimizer=optimizer,metrics=['cosine_proximity']) \n history=model.fit(X_train, y_train,epochs=epochs,batch_size=batch_size,validation_data=(X_test,y_test),verbose=False)\n plt.figure(figsize=(6,6))\n plt.plot(history.history['loss'])\n plt.plot(history.history['val_loss'])\n plt.title('model loss')\n plt.ylabel('loss')\n plt.xlabel('epoch')\n plt.legend(['train', 'val'], loc='upper left')\n plt.show()\n pred_test=model.predict(X_test)\n pred_test=pd.Series(pred_test.tolist()).apply(lambda x: x[0])\n cos=cosine_similarity(y_test,pred_test)\n print('Val Cosine Similarity: {}'.format(cos))\n\ndef model_ensemble(df_train,hidden_nodes,dropout,l2_regularizer,act,optimizer,epochs,batch_size=16):\n X_train=df_train.drop(columns=['source','sentiment score'])\n y_train=df_train['sentiment score']\n\n #Define MLP Ensemble\n model = Sequential()\n if dropout==0:\n model.add(Dense(hidden_nodes,input_shape=(X_train.shape[1],),\n kernel_regularizer=regularizers.l2(l2_regularizer),activity_regularizer=regularizers.l2(l2_regularizer)))\n else:\n model.add(Dropout(dropout, input_shape=(X_train.shape[1],)))\n model.add(Dense(hidden_nodes,kernel_regularizer=regularizers.l2(l2_regularizer),activity_regularizer=regularizers.l2(l2_regularizer)))\n model.add(Activation(act))\n model.add(Dense(1,activation='tanh'))\n \n model.compile(loss='MSE',optimizer=optimizer,metrics=['cosine_proximity']) \n history=model.fit(X_train, y_train,epochs=epochs,batch_size=batch_size,verbose=False)\n return model\n\ndef cosine_similarity(a,b):\n return np.dot(a,b)/(np.linalg.norm(a)*np.linalg.norm(b))\n\ndef tokenize(sentence):\n '''\n tokenize input sentence into token\n '''\n return (nltk.regexp_tokenize(sentence, pattern=r\"\\s|[\\.,;]\\D\", gaps=True))\n\ndef n_grams_handled(sentence):\n '''\n Filter before generate n-gram\n '''\n try:\n tk=TweetTokenizer()\n cashtag_pat=r'\\$[^\\s]+'\n hashtag_pat=r'#([^\\s]+)'\n word_number_pat=r'\\w*\\d\\w*'\n \n #Remove word which has length < 2\n stripped=' '.join([word for word in sentence.split() if len(word)>=2])\n \n #Remove hashtag\n hashtag_handled= re.sub(hashtag_pat,\"\", stripped)\n \n #Remove cashtag\n cashtag_handled= re.sub(cashtag_pat,\"\", hashtag_handled)\n \n #Remove word with number\n number_handled= re.sub(word_number_pat,\"\", cashtag_handled)\n \n #Remove unnecesary white spaces\n words = tk.tokenize(number_handled)\n words = [x for x in words if x not in string.punctuation]\n clean_sentence=(\" \".join(words)).strip()\n return clean_sentence\n except:\n return sentence\n\ndef rf_ngram(df_train,df_test,gram): \n '''\n create rf-ngram\n '''\n def sentence_sparse(sentence,gram,rf_ngram,sparse_rf_ngram):\n #Initiate Linke List Sparse Matrix\n zero_sparse=sp.lil_matrix( (1,len(rf_ngram)), dtype=float)\n #Assign Value of rf_ngram to each word in sentence\n splitted_text=tokenize(n_grams_handled(sentence))\n #Unigram\n if gram==1:\n for word in splitted_text:\n if word in rf_ngram.index:\n zero_sparse[0,rf_ngram.index.get_loc(word)]+=sparse_rf_ngram[0,rf_ngram.index.get_loc(word)]\n #Convert LinkedList Sparse Matrix into CSR Sparse Matrix\n sparse=zero_sparse.tocsr()\n #Bigram\n elif gram==2:\n bigram=lambda x: splitted_text[x]+' '+splitted_text[x+1]\n it_2_gram=range(len(splitted_text)-1)\n for i in it_2_gram:\n if bigram(i) in rf_ngram.index:\n zero_sparse[0,rf_ngram.index.get_loc(bigram(i))]+=sparse_rf_ngram[0,rf_ngram.index.get_loc(bigram(i))]\n #Convert LinkedList Sparse Matrix into CSR Sparse Matrix\n sparse=zero_sparse.tocsr()\n #Trigram\n elif gram==3:\n trigram=lambda x: splitted_text[x]+' '+splitted_text[x+1]+' '+splitted_text[x+2]\n it_3_gram=range(len(splitted_text)-2)\n for i in it_3_gram:\n if trigram(i) in rf_ngram.index:\n zero_sparse[0,rf_ngram.index.get_loc(trigram(i))]+=sparse_rf_ngram[0,rf_ngram.index.get_loc(trigram(i))]\n #Convert LinkedList Sparse Matrix into CSR Sparse Matrix\n sparse=zero_sparse.tocsr()\n #4grams\n elif gram==4:\n fourgram=lambda x: splitted_text[x]+' '+splitted_text[x+1]+' '+splitted_text[x+2]+' '+splitted_text[x+3]\n it_4_gram=range(len(splitted_text)-3)\n for i in it_4_gram:\n if fourgram(i) in rf_ngram.index:\n zero_sparse[0,rf_ngram.index.get_loc(fourgram(i))]+=sparse_rf_ngram[0,rf_ngram.index.get_loc(fourgram(i))]\n #Convert LinkedList Sparse Matrix into CSR Sparse Matrix\n sparse=zero_sparse.tocsr()\n return(sparse)\n\n BOW_df= pd.DataFrame(columns=['pos','neutral','neg'])\n words_set = set()\n \n #Creating the rf_ngram dictionary of words\n it=range(len(df_train))\n for i in it:\n score=df_train.loc[i,'sentiment score']\n if score>0:\n score='pos'\n elif score<0:\n score='neg'\n else:\n score='neutral'\n try:\n text=df_train.loc[i,'clean_text']\n cleaned_text=n_grams_handled(text)\n splitted_text=tokenize(cleaned_text)\n if gram==1:\n for word in splitted_text:\n if word not in words_set:#check if this word already counted or not in the full corpus\n words_set.add(word)\n BOW_df.loc[word] = [0,0,0]\n BOW_df.loc[word,score]+=1\n else:\n BOW_df.loc[word,score]+=1\n elif gram==2:\n it_2_gram=range(len(splitted_text)-1)\n bigram=lambda x: splitted_text[x]+' '+splitted_text[x+1]\n for i in it_2_gram:\n if bigram(i) not in words_set:\n words_set.add(bigram(i))\n BOW_df.loc[bigram(i)] = [0,0,0]\n BOW_df.loc[bigram(i),score]+=1\n else:\n BOW_df.loc[bigram(i),score]+=1\n elif gram==3:\n it_3_gram=range(len(splitted_text)-2)\n trigram=lambda x: splitted_text[x]+' '+splitted_text[x+1]+' '+splitted_text[x+2]\n for i in it_3_gram:\n if trigram(i) not in words_set:\n words_set.add(trigram(i))\n BOW_df.loc[trigram(i)] = [0,0,0]\n BOW_df.loc[trigram(i),score]+=1\n else:\n BOW_df.loc[trigram(i),score]+=1\n elif gram==4:\n it_4_gram=range(len(splitted_text)-3)\n fourgram=lambda x: splitted_text[x]+' '+splitted_text[x+1]+' '+splitted_text[x+2]+' '+splitted_text[x+3]\n for i in it_4_gram:\n if fourgram(i) not in words_set:\n words_set.add(fourgram(i))\n BOW_df.loc[fourgram(i)] = [0,0,0]\n BOW_df.loc[fourgram(i),score]+=1\n else:\n BOW_df.loc[fourgram(i),score]+=1 \n except:\n None\n #Calculate rf_ngram for each word\n series_1=pd.Series([1 for x in range(len(BOW_df))])\n series_1.index=BOW_df.index\n series_2=pd.Series([2 for x in range(len(BOW_df))])\n series_2.index=BOW_df.index\n frac_1=np.log(series_2+(BOW_df['pos']/pd.concat([series_1,BOW_df['neg']],1).max(axis=1)))\n frac_2=np.log(series_2+(BOW_df['neg']/pd.concat([series_1,BOW_df['pos']],1).max(axis=1)))\n rf_ngram_series= pd.concat([frac_1,frac_2],1).max(axis=1)\n sparse_rf_ngram=sp.csr_matrix(rf_ngram_series)\n\n def rf_ngram_calculate(x):\n lst=[i for i in sentence_sparse(x,gram,rf_ngram_series,sparse_rf_ngram).toarray()[0].tolist() if i!=0]\n if type(x)!=str:\n return(np.nan)\n else:\n if len(lst)>0:\n return(np.mean(lst))\n else:\n return(np.nan)\n\n rf_ngram_avg_list_train=df_train['clean_text'].apply(lambda x: rf_ngram_calculate(x))\n rf_ngram_avg_list_test=df_test['clean_text'].apply(lambda x: rf_ngram_calculate(x))\n\n df_train['Avg_rf_'+str(gram)+'-grams']= rf_ngram_avg_list_train\n df_test['Avg_rf_'+str(gram)+'-grams']= rf_ngram_avg_list_test\n\n return(df_train,df_test)\n\ndef PMI(df_train,df_test): \n '''\n create PMI variable\n '''\n BOW_df= pd.DataFrame(columns=['pos','neutral','neg'])\n words_set = set()\n \n #Creating the dictionary of words\n it=range(len(df_train))\n for i in it:\n score=df_train.loc[i,'sentiment score']\n if score>0:\n score='pos'\n elif score<0:\n score='neg'\n else:\n score='neutral'\n try:\n text=df_train.loc[i,'clean_text']\n cleaned_text=n_grams_handled(text)\n splitted_text=tokenize(cleaned_text)\n for word in splitted_text:\n if word not in words_set:#check if this word already counted or not in the full corpus\n words_set.add(word)\n BOW_df.loc[word] = [0,0,0]\n BOW_df.loc[word,score]+=1\n else:\n BOW_df.loc[word,score]+=1\n except:\n None\n \n N=len(BOW_df) #Number of unique tokens in the corpus\n pos_N=len(BOW_df[BOW_df.pos!=0]) #Number of unique positive tokens in the corpus\n neg_N=len(BOW_df[BOW_df.neg!=0]) #Number of unique positive tokens in the corpus\n total=BOW_df.sum().sum() #Number of tokens in the corpus\n pos_total=BOW_df.sum()['pos'] #Number of tokens in the positive corpus\n neg_total=BOW_df.sum()['neg'] #Number of tokens in the negative corpus\n PMI_df=pd.DataFrame(columns=['freq_word','freq_word_pos','freq_word_neg'])\n PMI_df['freq_word']=pd.Series(BOW_df.index).apply(lambda x: (BOW_df.loc[x,'pos']+BOW_df.loc[x,'neutral']+BOW_df.loc[x,'neg'])/total)\n PMI_df['freq_word_pos']=pd.Series(BOW_df.index).apply(lambda x: BOW_df.loc[x,'pos']/pos_total) #Freq of word w in positive text\n PMI_df['freq_word_neg']=pd.Series(BOW_df.index).apply(lambda x: BOW_df.loc[x,'neg']/neg_total) #Freq of word w in negative text\n PMI_df.index=BOW_df.index\n \n #Calculate PMI for each word\n PMI_df['PMI_pos']=np.log2(1+((PMI_df['freq_word_pos']*N)/(PMI_df['freq_word']*pos_N)))\n PMI_df['PMI_neg']=np.log2(1+((PMI_df['freq_word_neg']*N)/(PMI_df['freq_word']*neg_N)))\n PMI_df['PMI']=PMI_df['PMI_pos']-PMI_df['PMI_neg']\n \n def PMI_calculate(x):\n lst=[PMI_df.loc[i,'PMI'] for i in tokenize(n_grams_handled(x)) if i in PMI_df.index]\n if type(x)!=str:\n return(np.nan)\n else:\n if len(lst)>0:\n return(np.mean(lst))\n else:\n return(np.nan)\n\n PMI_avg_list_train=df_train['clean_text'].apply(lambda x: PMI_calculate(x))\n PMI_avg_list_test=df_test['clean_text'].apply(lambda x: PMI_calculate(x))\n \n df_train['PMI_score']=PMI_avg_list_train\n df_test['PMI_score']=PMI_avg_list_test\n\n return(df_train,df_test)\n\ndef W2V_sentence_embedding(df,span=False):\n '''\n return dataframe for W2V sentence embedding\n '''\n if not span:\n column='clean_text'\n else:\n column='spans'\n \n zero=np.array([float(0) for i in range(300)])\n nan=np.array([np.nan for i in range(300)])\n vec_W2V=lambda x: model_w2v[x] if x in model_w2v else zero\n W2V_avg=df[column].apply(lambda sent: pd.Series(tokenize(sent)).apply(lambda x: vec_W2V(x)).mean() if type(sent)==str else nan)\n \n W2V_df=pd.DataFrame(dict(zip(W2V_avg.index, W2V_avg.values))).T\n W2V_df['source']=df['source']\n W2V_df['sentiment score']=df['sentiment score']\n col=['x'+str(i) for i in W2V_df.drop(['source','sentiment score'],1).columns.tolist()]\n col.append('source')\n col.append('sentiment score')\n W2V_df.columns=col\n return(W2V_df)\n\n\n# + [markdown] colab_type=\"text\" id=\"QK_REtl9xwFm\"\n# # Import Data\n\n# +\ndf_train = pd.read_csv('C:/Users/Louis Owen/Desktop/NLP_Stacking_Ensemble/df_train_final.csv')\ndf_train=df_train.drop(['Unnamed: 0','index'],1)\n\ndf_test = pd.read_csv('C:/Users/Louis Owen/Desktop/NLP_Stacking_Ensemble/df_test_final.csv')\ndf_test=df_test.drop(['Unnamed: 0','index'],1)\n\ndf_train=df_train.drop(columns=['created_at','official_account','sentiment','total_likes'])\ndf_test=df_test.drop(columns=['created_at','official_account','sentiment','total_likes'])\n\ndf_val_index_list=random.sample(df_test.index.tolist(),k=round(0.85*len(df_test)))\ndf_test_index_list=[x for x in df_test.index.tolist() if x not in df_val_index_list]\ndf_val=df_test.loc[df_val_index_list].reset_index(drop=True)\ndf_test=df_test.loc[df_test_index_list].reset_index(drop=True)\n\n# + [markdown] colab_type=\"text\" id=\"qMFdvCaoHuVQ\"\n# # Import Supporting Files\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 0} colab_type=\"code\" executionInfo={\"elapsed\": 455091, \"status\": \"ok\", \"timestamp\": 1581772536553, \"user\": {\"displayName\": \"Louis Owen\", \"photoUrl\": \"\", \"userId\": \"06346350967386333294\"}, \"user_tz\": -420} id=\"Ktu7ezwHHxK4\" outputId=\"8306e01e-d62c-4544-e41f-4cbdc814717b\"\n#Google Word2Vec Pretrained Model\nmodel_w2v = gensim.models.KeyedVectors.load_word2vec_format('C:/Users/Louis Owen/Desktop/NLP_Stacking_Ensemble/Pre-Trained Word Embedding/GoogleNews-vectors-negative300.bin', binary=True) \n\n# + [markdown] colab_type=\"text\" id=\"7E6soWeK64m1\"\n# # Import Model\n# -\n\n\n\n# + [markdown] colab_type=\"text\" id=\"OxJzze5YSPdr\"\n# # Data Preparation for Ensemble\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 84} colab_type=\"code\" executionInfo={\"elapsed\": 82028, \"status\": \"ok\", \"timestamp\": 1581772648332, \"user\": {\"displayName\": \"Louis Owen\", \"photoUrl\": \"\", \"userId\": \"06346350967386333294\"}, \"user_tz\": -420} id=\"wg-CRIlD7m6z\" outputId=\"4fc08b32-8a13-4a89-82bf-3b47f3c4a640\"\npred_MLP=MLP_model(model_MLP,df_train,df_val,sentence_vector=False)\npred_MLP_W2V_Sentence_Vector=MLP_model(model_MLP_W2V_Sentence_Vector,df_train,df_val,sentence_vector=True)\npred_CNN=model_CNN_LSTM(model_CNN_W2V,df_train,df_val)\npred_LSTM=model_CNN_LSTM(model_LSTM_W2V,df_train,df_val)\n\ndf=pd.DataFrame(pred_MLP,columns=['pred_MLP_Feature_Driven'])\ndf['pred_MLP_W2V_Sentence_Vector']=pred_MLP_W2V_Sentence_Vector\ndf['pred_CNN_W2V']=pred_CNN\ndf['pred_lstm_W2V']=pred_LSTM\ndf['source']=df_val['source']\ndf['sentiment score']=df_val['sentiment score']\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 84} colab_type=\"code\" executionInfo={\"elapsed\": 70469, \"status\": \"ok\", \"timestamp\": 1581772718870, \"user\": {\"displayName\": \"Louis Owen\", \"photoUrl\": \"\", \"userId\": \"06346350967386333294\"}, \"user_tz\": -420} id=\"u8_SuBD-UDwS\" outputId=\"3cf32d52-7212-4d98-fa20-8f1937683b07\"\npred_MLP_test=MLP_model(model_MLP,df_train,df_test,sentence_vector=False)\npred_MLP_W2V_Sentence_Vector_test=MLP_model(model_MLP_W2V_Sentence_Vector,df_train,df_test,sentence_vector=True)\npred_CNN_test=model_CNN_LSTM(model_CNN_W2V,df_train,df_test)\npred_LSTM_test=model_CNN_LSTM(model_LSTM_W2V,df_train,df_test)\n\ndf_test_ensemble=pd.DataFrame(pred_MLP_test,columns=['pred_MLP_Feature_Driven'])\ndf_test_ensemble['pred_MLP_W2V_Sentence_Vector']=pred_MLP_W2V_Sentence_Vector_test\ndf_test_ensemble['pred_CNN_W2V']=pred_CNN_test\ndf_test_ensemble['pred_lstm_W2V']=pred_LSTM_test\ndf_test_ensemble['source']=df_test['source']\ndf_test_ensemble['sentiment score']=df_test['sentiment score']\n\n# + colab={} colab_type=\"code\" id=\"Lk8zHPNw9uX0\"\ndf_full_ensemble=pd.concat([df,df_test_ensemble])\n\n# + [markdown] colab_type=\"text\" id=\"ka6G0eRVETyO\"\n# # Baseline (Avg) Ensemble\n\n# + colab={\"base_uri\": \"https://localhost:8080/\"} colab_type=\"code\" executionInfo={\"elapsed\": 836, \"status\": \"ok\", \"timestamp\": 1581746252897, \"user\": {\"displayName\": \"Louis Owen\", \"photoUrl\": \"\", \"userId\": \"06346350967386333294\"}, \"user_tz\": -420} id=\"UNCv8W2eEWHA\" outputId=\"5a19ae0e-f271-4b7d-b32a-ceae6741527a\"\n#pred_MLP_Feature_Driven, pred_CNN_W2V, pred_MLP_W2V_Sentence_Vector, pred_lstm_W2V\npred=(df_test_ensemble['pred_MLP_Feature_Driven']+df_test_ensemble['pred_CNN_W2V']+df_test_ensemble['pred_MLP_W2V_Sentence_Vector']+df_test_ensemble['pred_lstm_W2V'])/4\nprint('Cosine Similarity: {}'.format(cosine_similarity(pred,df_test_ensemble['sentiment score'])))\n\n# + [markdown] colab_type=\"text\" id=\"lKL9QQqHZh62\"\n# # MLP Ensemble\n\n# + [markdown] colab_type=\"text\" id=\"0zC3h9SS9U-j\"\n# ## Hyperparameter Tuning\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 421} colab_type=\"code\" executionInfo={\"elapsed\": 15425, \"status\": \"ok\", \"timestamp\": 1581745622356, \"user\": {\"displayName\": \"Louis Owen\", \"photoUrl\": \"\", \"userId\": \"06346350967386333294\"}, \"user_tz\": -420} id=\"0RIUuaHMUg1_\" outputId=\"2e2ef997-d341-4c69-c701-4da0c9c6c4a5\"\n# Run it to obtain reproducible results across machines (from keras.io)\nos.environ['PYTHONHASHSEED'] = '0'\nnp.random.seed(42)\nrn.seed(12345)\nsession_conf = tf.ConfigProto(intra_op_parallelism_threads=1, inter_op_parallelism_threads=1)\ntf.set_random_seed(1234)\nsess = tf.Session(graph=tf.get_default_graph(), config=session_conf)\nK.set_session(sess)\n\nadam=tf.keras.optimizers.Adam(learning_rate=0.001)\n\ngrid_model_ensemble(df,df_test_ensemble,hidden_nodes=4,\n dropout=0.05,l2_regularizer=0.02,\n act='relu',optimizer=adam,epochs=200)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 421} colab_type=\"code\" executionInfo={\"elapsed\": 15390, \"status\": \"ok\", \"timestamp\": 1581745670295, \"user\": {\"displayName\": \"Louis Owen\", \"photoUrl\": \"\", \"userId\": \"06346350967386333294\"}, \"user_tz\": -420} id=\"DzoQx0YKYvGX\" outputId=\"c174dbc1-fe47-4883-ae15-236dec74f3e1\"\n# Run it to obtain reproducible results across machines (from keras.io)\nos.environ['PYTHONHASHSEED'] = '0'\nnp.random.seed(42)\nrn.seed(12345)\nsession_conf = tf.ConfigProto(intra_op_parallelism_threads=1, inter_op_parallelism_threads=1)\ntf.set_random_seed(1234)\nsess = tf.Session(graph=tf.get_default_graph(), config=session_conf)\nK.set_session(sess)\n\nadam=tf.keras.optimizers.Adam(learning_rate=0.001)\n\ngrid_model_ensemble(df,df_test_ensemble,hidden_nodes=4,\n dropout=0.05,l2_regularizer=0.03,\n act='relu',optimizer=adam,epochs=200)\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 421} colab_type=\"code\" executionInfo={\"elapsed\": 23164, \"status\": \"ok\", \"timestamp\": 1581746128914, \"user\": {\"displayName\": \"Louis Owen\", \"photoUrl\": \"\", \"userId\": \"06346350967386333294\"}, \"user_tz\": -420} id=\"UEqvuZ-KY7Er\" outputId=\"5639d3ff-df00-45bb-d6f1-268658d8e9c3\"\n# Run it to obtain reproducible results across machines (from keras.io)\nos.environ['PYTHONHASHSEED'] = '0'\nnp.random.seed(42)\nrn.seed(12345)\nsession_conf = tf.ConfigProto(intra_op_parallelism_threads=1, inter_op_parallelism_threads=1)\ntf.set_random_seed(1234)\nsess = tf.Session(graph=tf.get_default_graph(), config=session_conf)\nK.set_session(sess)\n\nadam=tf.keras.optimizers.Adam(learning_rate=0.00075)\n\ngrid_model_ensemble(df,df_test_ensemble,hidden_nodes=4,\n dropout=0.05,l2_regularizer=0.02,\n act='relu',optimizer=adam,epochs=300)\n\nfinal_model.save(\"gdrive/My Drive/TA/Seminar 1/Jupyter Notebook/model_Ensemble.h5\")\n\n# + [markdown] colab_type=\"text\" id=\"rnV_wwG59YMU\"\n# ## Final Model\n\n# + colab={} colab_type=\"code\" id=\"softadzM9aVE\"\n# Run it to obtain reproducible results across machines (from keras.io)\nos.environ['PYTHONHASHSEED'] = '0'\nnp.random.seed(42)\nrn.seed(12345)\nsession_conf = tf.ConfigProto(intra_op_parallelism_threads=1, inter_op_parallelism_threads=1)\ntf.set_random_seed(1234)\nsess = tf.Session(graph=tf.get_default_graph(), config=session_conf)\nK.set_session(sess)\n\nadam=tf.keras.optimizers.Adam(learning_rate=0.00075)\n\nfinal_model=model_ensemble(df_full_ensemble,hidden_nodes=4,\n dropout=0.05,l2_regularizer=0.02,\n act='relu',optimizer=adam,epochs=300)\n\nfinal_model.save(\"gdrive/My Drive/TA/Seminar 1/Jupyter Notebook/model_Ensemble.h5\")\n\n\n# + [markdown] colab_type=\"text\" id=\"10qa7UtlMMXK\"\n# # Plot Model\n\n# + colab={} colab_type=\"code\" id=\"h1Icls-LMOpf\"\ndef plot(model):\n '''\n Function for plot model\n '''\n K.clear_session()\n if model.lower()=='ensemble':\n model=Sequential()\n model.add(Dropout(0.05, input_shape=(4,)))\n model.add(Dense(4,kernel_regularizer=regularizers.l2(0.02),activity_regularizer=regularizers.l1(0.02)))\n model.add(Activation('relu'))\n model.add(Dense(1,activation='tanh'))\n plot_model(model, show_shapes=True,to_file='model_MLP_Ensemble.png')\n print('Done Plot Model Ensemble')\n\n elif model.lower()=='cnn_w2v':\n\n max_sequence_length=50\n embedding_layer = Embedding(30, 300, input_length=max_sequence_length, trainable=False) #30 is just a random number, because this number won't show in the plot\n sequence_input = Input(shape=(max_sequence_length,), dtype='int32')\n submodels=[]\n for kw in (1,2,3,4): # kernel sizes\n embedded_sequences = embedding_layer(sequence_input)\n sub=GaussianNoise(0.01)(embedded_sequences)\n sub_submodels=[]\n for i in range(25):\n subsub=BatchNormalization()(sub)\n subsub=Conv1D(1,kw,padding='valid',activation='tanh',strides=1)(sub)\n subsub=GlobalMaxPooling1D()(subsub)\n subsubmodel=Model(sequence_input,subsub)\n sub_submodels.append(subsubmodel)\n sub_submodel_outputs=[subsubmodel.output for subsubmodel in sub_submodels]\n sub_out=Concatenate(axis=1)(sub_submodel_outputs)\n submodel=Model(sequence_input,sub_out)\n submodels.append(submodel)\n #Concatenate Multiple Filter Sizes\n submodel_outputs = [submodel.output for submodel in submodels]\n out = Concatenate(axis=1)(submodel_outputs)\n out = Dropout(0.45)(out)\n out = Dense(15,kernel_regularizer=regularizers.l2(0.008),activity_regularizer=regularizers.l1(0.008))(out)\n out=Activation('tanh')(out)\n out = Dense(15,kernel_regularizer=regularizers.l2(0.008),activity_regularizer=regularizers.l1(0.008))(out)\n out=Activation('tanh')(out)\n out = Dense(1)(out)\n big_model = Model(sequence_input,out)\n plot_model(big_model, show_shapes=True,to_file='model_CNN_W2V.png')\n print('Done Plot Model CNN W2V')\n\n elif model.lower()=='lstm_w2v':\n\n max_sequence_length=50\n embedding_layer = Embedding(30, 300, input_length=max_sequence_length, trainable=False) #30 is just a random number, because this number won't show in the plot\n sequence_input = Input(shape=(max_sequence_length,), dtype='int32')\n embedded_sequences = embedding_layer(sequence_input)\n out=GaussianNoise(0.1)(embedded_sequences)\n out=tf.keras.layers.CuDNNLSTM(100,return_sequences=True)(out)\n out=tf.keras.layers.CuDNNLSTM(100)(out)\n out = Dropout(0.3)(out)\n out = Dense(50,kernel_regularizer=regularizers.l2(0.05),activity_regularizer=regularizers.l1(0.05))(out)\n out=Activation('relu')(out)\n out = Dense(10,kernel_regularizer=regularizers.l2(0.05),activity_regularizer=regularizers.l1(0.05))(out)\n out=Activation('tanh')(out)\n out = Dense(1)(out)\n model = Model(sequence_input,out)\n plot_model(model, show_shapes=True,to_file='model_LSTM_W2V.png')\n print('Done Plot Model LSTM W2V')\n \n elif model.lower()=='feature_driven':\n\n model = Sequential()\n model.add(Dropout(0.25, input_shape=(55,),seed=0))\n model.add(Dense(50,kernel_regularizer=regularizers.l2(0.01),activity_regularizer=regularizers.l1(0.01)))\n model.add(Activation('relu'))\n model.add(Dropout(0.2))\n model.add(Dense(30,kernel_regularizer=regularizers.l2(0.01),activity_regularizer=regularizers.l1(0.01)))\n model.add(Activation('relu'))\n model.add(Dropout(0.2))\n model.add(Dense(15,kernel_regularizer=regularizers.l2(0.01),activity_regularizer=regularizers.l1(0.01)))\n model.add(Activation('tanh'))\n model.add(Dense(1))\n plot_model(model, show_shapes=True,to_file='model_MLP_Feature_Driven.png')\n print('Done Plot Model MLP Feature Driven')\n \n elif model.lower()=='mlp_w2v':\n\n model = Sequential()\n model.add(Dropout(0.25, input_shape=(300,),seed=0))\n model.add(Dense(30,kernel_regularizer=regularizers.l2(0.004),activity_regularizer=regularizers.l1(0.004)))\n model.add(Activation('relu'))\n model.add(Dropout(0.25))\n model.add(Dense(30,kernel_regularizer=regularizers.l2(0.004),activity_regularizer=regularizers.l1(0.004)))\n model.add(Activation('relu'))\n model.add(Dropout(0.25))\n model.add(Dense(30,kernel_regularizer=regularizers.l2(0.004),activity_regularizer=regularizers.l1(0.004)))\n model.add(Activation('tanh'))\n model.add(Dense(1))\n plot_model(model, show_shapes=True,to_file='model_MLP_W2V.png')\n print('Done Plot Model MLP W2V')\n\n\n# + colab={\"base_uri\": \"https://localhost:8080/\", \"height\": 134} colab_type=\"code\" executionInfo={\"elapsed\": 15931, \"status\": \"ok\", \"timestamp\": 1581747317637, \"user\": {\"displayName\": \"Louis Owen\", \"photoUrl\": \"\", \"userId\": \"06346350967386333294\"}, \"user_tz\": -420} id=\"n8B48joaOc9k\" outputId=\"502688cc-5e89-4ede-8c29-424d79a18552\"\nfor model in ['feature_driven','cnn_w2v','lstm_w2v','mlp_w2v','ensemble']:\n plot(model=model)\n","repo_name":"louisowen6/NLP_Stacking_Ensemble","sub_path":"Model/Ensemble.ipynb","file_name":"Ensemble.ipynb","file_ext":"py","file_size_in_byte":28245,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-jupyter-script","pt":"35"} +{"seq_id":"42725932424","text":"import glob\nvehicleImages = glob.glob('../Data/vehicles/**/*.png')\nnonVehicleImages = glob.glob('../Data/non-vehicles/**/*.png')\nprint('# of vehicle images -> {}'.format(len(vehicleImages)))\nprint('# of non-vehicle images -> {}'.format(len(nonVehicleImages)))\n\n#import matplotlib.image as mpimg\nimport scipy.ndimage as snd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport cv2\nimport time\nfrom skimage.feature import hog\nfrom sklearn.svm import LinearSVC\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\n\n\n# +\n# define all functions like in lessons -- helper functions\n\n# Define a function to return HOG features and visualization\ndef get_hog_features(img, orient, pix_per_cell, cell_per_block, \n vis=False, feature_vec=True):\n # Call with two outputs if vis==True\n if vis == True:\n features, hog_image = hog(img, orientations=orient, \n pixels_per_cell=(pix_per_cell, pix_per_cell),\n cells_per_block=(cell_per_block, cell_per_block), \n transform_sqrt=True, \n visualise=vis, feature_vector=feature_vec)\n return features, hog_image\n # Otherwise call with one output\n else: \n features = hog(img, orientations=orient, \n pixels_per_cell=(pix_per_cell, pix_per_cell),\n cells_per_block=(cell_per_block, cell_per_block), \n transform_sqrt=True, \n visualise=vis, feature_vector=feature_vec)\n return features\n\n# Define a function to compute binned color features \ndef bin_spatial(img, size=(32, 32)):\n # Use cv2.resize().ravel() to create the feature vector\n #features = cv2.resize(img, size).ravel() \n color1 = cv2.resize(img[:,:,0],size).ravel()\n color2 = cv2.resize(img[:,:,1],size).ravel()\n color3 = cv2.resize(img[:,:,2],size).ravel()\n # concatenate the feature vector\n features = np.concatenate((color1,color2,color3))\n # Return the feature vector\n return features\n\n# Define a function to compute color histogram features \n# NEED TO CHANGE bins_range if reading .png files with mpimg!--> No need as I read using scipy.ndimage.imread which has bin range from 0 to 255 included\ndef color_hist(img, nbins=32, bins_range=(0, 256)):\n # Compute the histogram of the color channels separately\n channel1_hist = np.histogram(img[:,:,0], bins=nbins, range=bins_range)\n channel2_hist = np.histogram(img[:,:,1], bins=nbins, range=bins_range)\n channel3_hist = np.histogram(img[:,:,2], bins=nbins, range=bins_range)\n # Concatenate the histograms into a single feature vector\n hist_features = np.concatenate((channel1_hist[0], channel2_hist[0], channel3_hist[0]))\n # Return the individual histograms, bin_centers and feature vector\n return hist_features\n\n# Define a function to extract features from a list of images\n# Have this function call bin_spatial() and color_hist()\ndef extract_features(imgs, color_space='RGB', spatial_size=(32, 32),\n hist_bins=32, orient=9, \n pix_per_cell=8, cell_per_block=2, hog_channel=0,\n spatial_feat=True, hist_feat=True, hog_feat=True):\n # Create a list to append feature vectors to\n features = []\n # Iterate through the list of images\n for file in imgs:\n file_features = []\n # Read in each one by one\n #image = mpimg.imread(file)\n image = snd.imread(file)\n # apply color conversion if other than 'RGB'\n if color_space != 'RGB':\n if color_space == 'HSV':\n feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)\n elif color_space == 'LUV':\n feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2LUV)\n elif color_space == 'HLS':\n feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2HLS)\n elif color_space == 'YUV':\n feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2YUV)\n elif color_space == 'YCrCb':\n feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2YCrCb)\n else: feature_image = np.copy(image) \n\n if spatial_feat == True:\n spatial_features = bin_spatial(feature_image, size=spatial_size)\n file_features.append(spatial_features)\n if hist_feat == True:\n # Apply color_hist()\n hist_features = color_hist(feature_image, nbins=hist_bins)\n file_features.append(hist_features)\n if hog_feat == True:\n # Call get_hog_features() with vis=False, feature_vec=True\n if hog_channel == 'ALL':\n hog_features = []\n for channel in range(feature_image.shape[2]):\n hog_features.append(get_hog_features(feature_image[:,:,channel], \n orient, pix_per_cell, cell_per_block, \n vis=False, feature_vec=True))\n hog_features = np.ravel(hog_features) \n else:\n hog_features = get_hog_features(feature_image[:,:,hog_channel], orient, \n pix_per_cell, cell_per_block, vis=False, feature_vec=True)\n # Append the new feature vector to the features list\n file_features.append(hog_features)\n features.append(np.concatenate(file_features))\n # Return list of feature vectors\n return features\n\n\n# +\n# %matplotlib inline\n\n# choose random car/ not-car indices\ncar_ind = np.random.randint(0,len(vehicleImages))\nnotcar_ind = np.random.randint(0,len(nonVehicleImages))\n\n# read in car/not car image\ncar_image = snd.imread(vehicleImages[car_ind])\nnotcar_image = snd.imread(nonVehicleImages[notcar_ind])\n\n# Define feature parameters\ncolor_space = 'YUV'\norient = 9\npix_per_cell = 8\ncell_per_block = 2\nhog_channel = 2 # Can be 0,1,2 or 'ALL'\nspatial_size = (16,16)\nhist_bins = 16\nspatial_feat, hist_feat, hog_feat = True, True, True\n\ncar_features, car_hog_image = single_img_features(car_image, color_space=color_space, \n spatial_size=spatial_size, hist_bins=hist_bins, \n orient=orient, pix_per_cell=pix_per_cell, \n cell_per_block=cell_per_block, \n hog_channel=hog_channel, spatial_feat=spatial_feat, \n hist_feat=hist_feat, hog_feat=hog_feat, vis = True)\nnotcar_features, notcar_hog_image = single_img_features(notcar_image, color_space=color_space, \n spatial_size=spatial_size, hist_bins=hist_bins, \n orient=orient, pix_per_cell=pix_per_cell, \n cell_per_block=cell_per_block, \n hog_channel=hog_channel, spatial_feat=spatial_feat, \n hist_feat=hist_feat, hog_feat=hog_feat, vis = True)\n\nimages = [car_image, car_hog_image, notcar_image, notcar_hog_image]\ntitles = ['car image', 'car HOG image', 'notcar image', 'notcar HOG image']\nfig = plt.figure(figsize = (12,3))\nvisualize(fig,1,4,images,titles)\n\n\n# +\ncolor_space = 'LUV' # Can be RGB, HSV, LUV, HLS, YUV, YCrCb\norient = 9 # HOG orientations\npix_per_cell = 8 # HOG pixels per cell\ncell_per_block = 2 # HOG cells per block\nhog_channel = \"ALL\" # Can be 0, 1, 2, or \"ALL\"\nspatial_size = (16, 16)# Spatial binning dimensions\nhist_bins = 16 # Number of histogram bins\nspatial_feat = True # Spatial features on or off\nhist_feat = True # Histogram features on or off\nhog_feat = True # HOG features on or off\n\n#y_start_stop = [400, None] # Min and max in y to search in slide_window()\nt = time.time()\nn_samples = 1000\nrandom_idxs = np.random.randint(0,len(vehicleImages),n_samples)\ntest_cars = vehicleImages #np.array(vehicleImages)[random_idxs]\ntest_notcars = nonVehicleImages #np.array(nonVehicleImages)[random_idxs]\n\ncar_features = extract_features(test_cars, color_space=color_space, \n spatial_size=spatial_size, hist_bins=hist_bins, \n orient=orient, pix_per_cell=pix_per_cell, \n cell_per_block=cell_per_block, \n hog_channel=hog_channel, spatial_feat=spatial_feat, \n hist_feat=hist_feat, hog_feat=hog_feat)\nnotcar_features = extract_features(test_notcars, color_space=color_space, \n spatial_size=spatial_size, hist_bins=hist_bins, \n orient=orient, pix_per_cell=pix_per_cell, \n cell_per_block=cell_per_block, \n hog_channel=hog_channel, spatial_feat=spatial_feat, \n hist_feat=hist_feat, hog_feat=hog_feat)\n\nprint(time.time()-t, 'Seconds to compute features...')\n\nX = np.vstack((car_features, notcar_features)).astype(np.float64) \n# Fit a per-column scaler\nX_scaler = StandardScaler().fit(X)\n# Apply the scaler to X\nscaled_X = X_scaler.transform(X)\n\n# Define the labels vector\ny = np.hstack((np.ones(len(car_features)), np.zeros(len(notcar_features))))\n\n\n# Split up data into randomized training and test sets\nrand_state = np.random.randint(0, 100)\nX_train, X_test, y_train, y_test = train_test_split(\n scaled_X, y, test_size=0.2, random_state=rand_state)\n\nprint('Using:',orient,'orientations',pix_per_cell,\n 'pixels per cell and', cell_per_block,'cells per block')\nprint('Feature vector length:', len(X_train[0]))\n# Use a linear SVC \nsvc = LinearSVC()\n# Check the training time for the SVC\nt=time.time()\nsvc.fit(X_train, y_train)\nt2 = time.time()\nprint(round(t2-t, 2), 'Seconds to train SVC...')\n# Check the score of the SVC\nprint('Test Accuracy of SVC = ', round(svc.score(X_test, y_test), 4))\n\n\n# +\n# Define a function that takes an image,\n# start and stop positions in both x and y, \n# window size (x and y dimensions), \n# and overlap fraction (for both x and y)\ndef slide_window(img, x_start_stop=[None, None], y_start_stop=[None, None], \n xy_window=(64, 64), xy_overlap=(0.5, 0.5)):\n # If x and/or y start/stop positions not defined, set to image size\n if x_start_stop[0] == None:\n x_start_stop[0] = 0\n if x_start_stop[1] == None:\n x_start_stop[1] = img.shape[1]\n if y_start_stop[0] == None:\n y_start_stop[0] = 0 #img.shape[0]/1.5\n if y_start_stop[1] == None:\n y_start_stop[1] = img.shape[0]\n # Compute the span of the region to be searched \n xspan = x_start_stop[1] - x_start_stop[0]\n yspan = y_start_stop[1] - y_start_stop[0]\n # Compute the number of pixels per step in x/y\n nx_pix_per_step = np.int(xy_window[0]*(1 - xy_overlap[0]))\n ny_pix_per_step = np.int(xy_window[1]*(1 - xy_overlap[1]))\n # Compute the number of windows in x/y\n nx_buffer = np.int(xy_window[0]*(xy_overlap[0]))\n ny_buffer = np.int(xy_window[1]*(xy_overlap[1]))\n nx_windows = np.int((xspan-nx_buffer)/nx_pix_per_step) \n ny_windows = np.int((yspan-ny_buffer)/ny_pix_per_step) \n # Initialize a list to append window positions to\n window_list = []\n # Loop through finding x and y window positions\n # Note: you could vectorize this step, but in practice\n # you'll be considering windows one by one with your\n # classifier, so looping makes sense\n for ys in range(ny_windows):\n for xs in range(nx_windows):\n # Calculate window position\n startx = xs*nx_pix_per_step + x_start_stop[0]\n endx = startx + xy_window[0]\n starty = ys*ny_pix_per_step + y_start_stop[0]\n endy = starty + xy_window[1]\n \n # Append window position to list\n window_list.append(((startx, starty), (endx, endy)))\n # Return the list of windows\n return window_list\n\n# Define a function to draw bounding boxes\ndef draw_boxes(img, bboxes, color=(0, 0, 255), thick=6):\n # Make a copy of the image\n imcopy = np.copy(img)\n # Iterate through the bounding boxes\n for bbox in bboxes:\n # Draw a rectangle given bbox coordinates\n cv2.rectangle(imcopy, bbox[0], bbox[1], color, thick)\n # Return the image copy with boxes drawn\n return imcopy\n\n\n# +\ndef single_img_features(img, color_space='RGB', spatial_size=(32, 32),\n hist_bins=32, orient=9, \n pix_per_cell=8, cell_per_block=2, hog_channel=0,\n spatial_feat=True, hist_feat=True, hog_feat=True, vis = False): \n #1) Define an empty list to receive features\n img_features = []\n #2) Apply color conversion if other than 'RGB'\n if color_space != 'RGB':\n if color_space == 'HSV':\n feature_image = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)\n elif color_space == 'LUV':\n feature_image = cv2.cvtColor(img, cv2.COLOR_RGB2LUV)\n elif color_space == 'HLS':\n feature_image = cv2.cvtColor(img, cv2.COLOR_RGB2HLS)\n elif color_space == 'YUV':\n feature_image = cv2.cvtColor(img, cv2.COLOR_RGB2YUV)\n elif color_space == 'YCrCb':\n feature_image = cv2.cvtColor(img, cv2.COLOR_RGB2YCrCb)\n else: feature_image = np.copy(img) \n #3) Compute spatial features if flag is set\n if spatial_feat == True:\n spatial_features = bin_spatial(feature_image, size=spatial_size)\n #4) Append features to list\n img_features.append(spatial_features)\n #5) Compute histogram features if flag is set\n if hist_feat == True:\n hist_features = color_hist(feature_image, nbins=hist_bins)\n #6) Append features to list\n img_features.append(hist_features)\n #7) Compute HOG features if flag is set\n if hog_feat == True:\n if hog_channel == 'ALL':\n hog_features = []\n for channel in range(feature_image.shape[2]):\n hog_features.extend(get_hog_features(feature_image[:,:,channel], \n orient, pix_per_cell, cell_per_block, \n vis=False, feature_vec=True)) \n else:\n if vis == True:\n hog_features, hog_image = get_hog_features(feature_image[:,:,hog_channel], orient, \n pix_per_cell, cell_per_block, vis=True, feature_vec=True)\n else:\n hog_features = get_hog_features(feature_image[:,:,hog_channel], orient, \n pix_per_cell, cell_per_block, vis=False, feature_vec=True)\n #8) Append features to list\n img_features.append(hog_features)\n\n #9) Return concatenated array of features\n if vis == True:\n return np.concatenate(img_features), hog_image\n else:\n return np.concatenate(img_features)\n\n\n# Define a function you will pass an image \n# and the list of windows to be searched (output of slide_windows())\ndef search_windows(img, windows, clf, scaler, color_space='RGB', \n spatial_size=(32, 32), hist_bins=32, \n hist_range=(0, 256), orient=9, \n pix_per_cell=8, cell_per_block=2, \n hog_channel=0, spatial_feat=True, \n hist_feat=True, hog_feat=True):\n\n #1) Create an empty list to receive positive detection windows\n on_windows = []\n #2) Iterate over all windows in the list\n for window in windows:\n #3) Extract the test window from original image\n test_img = cv2.resize(img[window[0][1]:window[1][1], window[0][0]:window[1][0]], (64, 64)) \n #4) Extract features for that window using single_img_features()\n features = single_img_features(test_img, color_space=color_space, \n spatial_size=spatial_size, hist_bins=hist_bins, \n orient=orient, pix_per_cell=pix_per_cell, \n cell_per_block=cell_per_block, \n hog_channel=hog_channel, spatial_feat=spatial_feat, \n hist_feat=hist_feat, hog_feat=hog_feat)\n #5) Scale extracted features to be fed to classifier\n test_features = scaler.transform(np.array(features).reshape(1, -1))\n #6) Predict using your classifier\n prediction = clf.predict(test_features)\n #7) If positive (prediction == 1) then save the window\n if prediction == 1:\n on_windows.append(window)\n #8) Return windows for positive detections\n return on_windows\n\ndef visualize(fig, rows, cols, imgs, titles):\n for i,img in enumerate(imgs):\n plt.subplot(rows,cols,i+1)\n plt.title(i+1)\n img_dims = len(img.shape)\n if img_dims<3:\n plt.imshow(img,cmap = 'hot')\n plt.title(titles[i])\n else:\n plt.imshow(img)\n plt.title(titles[i])\n\n\n# +\n# %matplotlib inline\ntest_images = glob.glob('./test_images/*.jpg')\nimages, titles = [], []\ny_start_stop = [400, 656] # Min, Max search in slide_window()\noverlap = 0.5\nfor img_src in test_images:\n t1 = time.time()\n img = snd.imread(img_src)\n draw_img = np.copy(img)\n \n #windows1 = slide_window(img, x_start_stop = [None, None], y_start_stop = y_start_stop,\n # xy_window = (128,128), xy_overlap = (overlap,overlap))\n windows = slide_window(img, x_start_stop = [None, None], y_start_stop = y_start_stop,\n xy_window = (96,96), xy_overlap = (overlap,overlap))\n #windows = windows1 + windows2\n hot_windows = search_windows(img, windows, svc, X_scaler, color_space = color_space,\n spatial_size = spatial_size, hist_bins = hist_bins,\n orient = orient, pix_per_cell = pix_per_cell,\n cell_per_block = cell_per_block,\n hog_channel = hog_channel, spatial_feat = spatial_feat,\n hist_feat = hist_feat, hog_feat = hog_feat)\n window_img = draw_boxes(draw_img, hot_windows, color = (0,0,255), thick = 6)\n images.append(window_img)\n titles.append(img_src[-9:])\n print(time.time()-t1, 'Seconds to process 1 img search', len(windows), 'windows')\n\nfig = plt.figure(figsize = (12,12), dpi = 300)\nvisualize(fig, 3,2, images, titles)\n\n\n# +\n# Rather than extracting hog features for each 96x96 window, \n# take the hog feature of whole image and then take sub-sample the array\n# to extract features of each window\ndef convert_color(img, conv = 'RGB2YCrCb'):\n if conv == 'RGB2YCrCb':\n return cv2.cvtColor(img,cv2.COLOR_RGB2YCrCb)\n elif conv == 'RGB2LUV':\n return cv2.cvtColor(img,cv2.COLOR_RGB2LUV)\n\ndef find_cars(img, scale=1):\n draw_img = np.copy(img)\n # make a heatmap of zeros\n heatmap = np.zeros_like(img[:,:,0])\n img_tosearch = img[ystart:ystop,:,:]\n ctrans_tosearch = convert_color(img_tosearch, conv = 'RGB2LUV')\n # resize whole search image instead of resize window size\n if scale !=1:\n imshape = ctrans_tosearch.shape\n ctrans_tosearch = cv2.resize(ctrans_tosearch, (np.int(imshape[1]/scale), np.int(imshape[0]/scale)))\n\n ch1, ch2, ch3 = ctrans_tosearch[:,:,0], ctrans_tosearch[:,:,1], ctrans_tosearch[:,:,2] \n \n # compute individual channel HOG features for the entire image\n hog1 = get_hog_features(ch1, orient, pix_per_cell, cell_per_block, feature_vec=False)\n hog2 = get_hog_features(ch2, orient, pix_per_cell, cell_per_block, feature_vec=False)\n hog3 = get_hog_features(ch3, orient, pix_per_cell, cell_per_block, feature_vec=False)\n\n # Define blocks and steps\n nxblocks = (ch1.shape[1] // pix_per_cell) - 1\n nyblocks = (ch1.shape[0] // pix_per_cell) - 1\n nfeat_per_block = orient*cell_per_block**2\n window = 64\n nblocks_per_window = (window //pix_per_cell) - 1\n \n cells_per_step = 2 # Instead of overlap define how many cells to step ~75% overlap\n nxsteps = (nxblocks - nblocks_per_window) // cells_per_step\n nysteps = (nyblocks - nblocks_per_window) // cells_per_step\n\n for xb in range(nxsteps):\n for yb in range(nysteps):\n ypos = yb*cells_per_step\n xpos = xb*cells_per_step\n # Extract hog for only this patch\n hog_feat1 = hog1[ypos:ypos+nblocks_per_window,xpos:xpos+nblocks_per_window].ravel()\n hog_feat2 = hog2[ypos:ypos+nblocks_per_window,xpos:xpos+nblocks_per_window].ravel()\n hog_feat3 = hog3[ypos:ypos+nblocks_per_window,xpos:xpos+nblocks_per_window].ravel()\n hog_features = np.hstack((hog_feat1, hog_feat2, hog_feat3))\n\n xleft = xpos*pix_per_cell\n ytop = ypos*pix_per_cell\n\n # Extract the image patch\n subimg = cv2.resize(ctrans_tosearch[ytop:ytop+window, xleft:xleft+window], (64,64))\n\n # Get color features\n spatial_features = bin_spatial(subimg, size = spatial_size)\n hist_features = color_hist(subimg, nbins = hist_bins)\n\n # Scale features and make a prediction\n test_features = X_scaler.transform(np.hstack((spatial_features, hist_features, hog_features)).reshape(1,-1))\n test_prediction = svc.predict(test_features)\n\n if test_prediction == 1:\n xbox_left = np.int(xleft*scale)\n ytop_draw = np.int(ytop*scale)\n win_draw = np.int(window*scale)\n cv2.rectangle(draw_img,(xbox_left, ytop_draw+ystart),(xbox_left+win_draw, ytop_draw+win_draw+ystart),(0,0,255),6)\n #img_boxes.append(((xbox_left, ytop_draw+ystart),(xbox_left+win_draw,ytop_draw+win_draw+ystart)))\n heatmap[ytop_draw+ystart:ytop_draw+win_draw+ystart, xbox_left:xbox_left+win_draw] +=1\n \n return draw_img, heatmap\n\n\n# +\nfrom scipy.ndimage.measurements import label\n\ndef apply_threshold(heatmap, threshold):\n # zero below threshold\n heatmap[heatmap<=threshold] = 0\n return heatmap\n\ndef draw_labeled_bboxes(img, labels):\n # Iterate thru all detected cars\n bbox_topleft = []\n bbox_bottomright = []\n for iCar in range(1, labels[1]+1):\n # find pixels with each car number label value\n nonzero = (labels[0] == iCar).nonzero()\n # identify x and y values of those pixels\n nonzeroy = np.array(nonzero[0])\n nonzerox = np.array(nonzero[1])\n #define a bounding box based on min/max x and y\n bbox_topleft.append((np.min(nonzerox), np.min(nonzeroy)))\n bbox_bottomright.append((np.max(nonzerox),np.max(nonzeroy)))\n # draw box on the image only one rectangle at a time\n cv2.rectangle(img, (bbox_topleft[iCar-1]), (bbox_bottomright[iCar-1]), (0,0,255),6)\n \n return img, bbox_topleft, bbox_bottomright\n \n\n\n# -\n\nout_images = []\nout_titles = []\nystart, ystop, scale = 400, 656, 1.5\norient = 9 # HOG orientations\npix_per_cell = 8 # HOG pixels per cell\ncell_per_block = 2 # HOG cells per block\nhog_channel = \"ALL\" # Can be 0, 1, 2, or \"ALL\"\nspatial_size = (16, 16)# Spatial binning dimensions\nhist_bins = 16 # Number of histogram bins\n# Iterate over test images\nfor img_src in test_images:\n img = snd.imread(img_src)\n out_img, heat_map = find_cars(img, scale)\n # Don't really think we need this\n #heat_map = apply_threshold(heat_map,1)\n labels = label(heat_map)\n # Draw bounding boxes on a copy of image\n draw_img,_,temp = draw_labeled_bboxes(np.copy(img), labels)\n out_images.append(draw_img)\n out_titles.append(img_src[-9:])\n out_images.append(heat_map)\n out_titles.append(img_src[-9:])\n #print(temp)\nfig = plt.figure(figsize = (12,24))\nvisualize(fig, 8, 2, out_images, out_titles)\n\nfrom moviepy.editor import VideoFileClip\nfrom IPython.display import HTML\n\n\ndef process_image(img):\n \n out_img, heat_map = find_cars(img,scale)\n heat_map = apply_threshold(heat_map,1)\n labels = label(heat_map)\n draw_img,_,_ = draw_labeled_bboxes(np.copy(img), labels)\n return draw_img\n\n\ntest_output = 'ptest.mp4'\nclip = VideoFileClip('project_video.mp4')\ntest_clip = clip.fl_image(process_image)\ntest_clip.write_videofile(test_output, audio = False)\n\nHTML(\"\"\"\n