thesis-prediction-ml/fetchDatafromDb/getProductDetails.ipynb
2023-06-21 11:13:32 +00:00

799 lines
26 KiB
Text

{
"cells": [
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Collecting seaborn\n",
" Using cached seaborn-0.12.2-py3-none-any.whl (293 kB)\n",
"Collecting pandas>=0.25\n",
" Using cached pandas-2.0.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (12.3 MB)\n",
"Collecting numpy!=1.24.0,>=1.17\n",
" Downloading numpy-1.25.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (17.6 MB)\n",
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m17.6/17.6 MB\u001b[0m \u001b[31m1.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m00:01\u001b[0m00:01\u001b[0m\n",
"\u001b[?25hCollecting matplotlib!=3.6.1,>=3.1\n",
" Using cached matplotlib-3.7.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (11.6 MB)\n",
"Collecting contourpy>=1.0.1\n",
" Using cached contourpy-1.1.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (300 kB)\n",
"Collecting cycler>=0.10\n",
" Using cached cycler-0.11.0-py3-none-any.whl (6.4 kB)\n",
"Collecting pillow>=6.2.0\n",
" Using cached Pillow-9.5.0-cp310-cp310-manylinux_2_28_x86_64.whl (3.4 MB)\n",
"Requirement already satisfied: python-dateutil>=2.7 in /home/shoney/dev/.venv/lib/python3.10/site-packages (from matplotlib!=3.6.1,>=3.1->seaborn) (2.8.2)\n",
"Collecting pyparsing>=2.3.1\n",
" Downloading pyparsing-3.1.0-py3-none-any.whl (102 kB)\n",
"\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m102.6/102.6 kB\u001b[0m \u001b[31m829.5 kB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m00:01\u001b[0m00:01\u001b[0m\n",
"\u001b[?25hCollecting kiwisolver>=1.0.1\n",
" Using cached kiwisolver-1.4.4-cp310-cp310-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (1.6 MB)\n",
"Collecting fonttools>=4.22.0\n",
" Using cached fonttools-4.40.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (4.2 MB)\n",
"Requirement already satisfied: packaging>=20.0 in /home/shoney/dev/.venv/lib/python3.10/site-packages (from matplotlib!=3.6.1,>=3.1->seaborn) (23.1)\n",
"Collecting pytz>=2020.1\n",
" Using cached pytz-2023.3-py2.py3-none-any.whl (502 kB)\n",
"Collecting tzdata>=2022.1\n",
" Using cached tzdata-2023.3-py2.py3-none-any.whl (341 kB)\n",
"Requirement already satisfied: six>=1.5 in /home/shoney/dev/.venv/lib/python3.10/site-packages (from python-dateutil>=2.7->matplotlib!=3.6.1,>=3.1->seaborn) (1.16.0)\n",
"Installing collected packages: pytz, tzdata, pyparsing, pillow, numpy, kiwisolver, fonttools, cycler, pandas, contourpy, matplotlib, seaborn\n",
"Successfully installed contourpy-1.1.0 cycler-0.11.0 fonttools-4.40.0 kiwisolver-1.4.4 matplotlib-3.7.1 numpy-1.25.0 pandas-2.0.2 pillow-9.5.0 pyparsing-3.1.0 pytz-2023.3 seaborn-0.12.2 tzdata-2023.3\n",
"\n",
"\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m23.0.1\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m23.1.2\u001b[0m\n",
"\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpip install --upgrade pip\u001b[0m\n",
"Collecting scikit-learn\n",
" Using cached scikit_learn-1.2.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (9.6 MB)\n",
"Requirement already satisfied: numpy>=1.17.3 in /home/shoney/dev/.venv/lib/python3.10/site-packages (from scikit-learn) (1.25.0)\n",
"Collecting scipy>=1.3.2\n",
" Using cached scipy-1.10.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (34.4 MB)\n",
"Collecting joblib>=1.1.1\n",
" Using cached joblib-1.2.0-py3-none-any.whl (297 kB)\n",
"Collecting threadpoolctl>=2.0.0\n",
" Using cached threadpoolctl-3.1.0-py3-none-any.whl (14 kB)\n",
"Installing collected packages: threadpoolctl, scipy, joblib, scikit-learn\n",
"Successfully installed joblib-1.2.0 scikit-learn-1.2.2 scipy-1.10.1 threadpoolctl-3.1.0\n",
"\n",
"\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m23.0.1\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m23.1.2\u001b[0m\n",
"\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpip install --upgrade pip\u001b[0m\n"
]
}
],
"source": [
"!python -m pip install seaborn\n",
"!python -m pip install scikit-learn"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Collecting elasticsearch<7.0.0,>=6.4.0\n",
" Using cached elasticsearch-6.8.2-py2.py3-none-any.whl (90 kB)\n",
"Collecting urllib3>=1.21.1\n",
" Using cached urllib3-2.0.3-py3-none-any.whl (123 kB)\n",
"Installing collected packages: urllib3, elasticsearch\n",
"Successfully installed elasticsearch-6.8.2 urllib3-2.0.3\n",
"\n",
"\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m23.0.1\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m23.1.2\u001b[0m\n",
"\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpip install --upgrade pip\u001b[0m\n"
]
}
],
"source": [
"!python -m pip install \"elasticsearch>=6.4.0,<7.0.0\""
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"from elasticsearch import Elasticsearch\n",
"client = Elasticsearch(\"http://172.17.212.35:9200\")\n",
"resp = client.search(index=\"retromotion-indexer_development_products\",\n",
" body={\"_source\":[\"descriptions\",\"descriptionsSource\",\"nameSource\",\"shortDescriptionSource\",\"categoriesSource\"],\n",
" \"query\": {\"match_all\": {}}})\n"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Got 22329 Hits:\n"
]
}
],
"source": [
"print(\"Got %d Hits:\" % resp['hits']['total'])"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"import re\n",
"import numpy as np\n",
"\n",
"import sklearn\n",
"import matplotlib.pyplot as plt\n",
"import seaborn as sns"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"df_eng = pd.DataFrame(columns=['name','sdesc','category','catlevel0','catlevel1','catlevel2','catlevel3','catlevel4','catlevel5'])\n",
"df_de = pd.DataFrame(columns=['name','sdesc','desc','category','categorypath'])"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"name denso dtm82363 thermostat coolant\n",
"sdesc thermostat coolant\n",
"category thermostat\n",
"catlevel0 sparepart\n",
"catlevel1 cooling system\n",
"catlevel2 thermostat\n",
"catlevel3 NaN\n",
"catlevel4 NaN\n",
"catlevel5 NaN\n",
"Name: 0, dtype: object"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"df_eng.iloc[0]"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
"def cleanStr(text):\n",
" \n",
" # remove numbers\n",
" # no_number_string = re.sub(r'\\d+','',lower_string)\n",
"\n",
" # remove all punctuation except words and space\n",
" # text = re.sub(r'[^\\w\\s]','', lower_string)\n",
"\n",
" # clean = re.compile('<.*?>')\n",
"\n",
" # text = re.sub(clean,'',text)\n",
" text = re.sub('<[^>]*>', '', text)\n",
" emoticons = re.findall('(?::|;|=)(?:-)?(?:\\)|\\(|D|P)', text)\n",
" text = (re.sub('[\\W]+', ' ', text.lower()) + ' ' .join(emoticons).replace('-', ''))\n",
"\n",
" return text\n"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [],
"source": [
"def readHtml(html):\n",
" dftable = pd.read_html(html)\n",
" return dftable"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [],
"source": [
"name_en=[]\n",
"name_de=[]\n",
"\n",
"sdesc_en=[]\n",
"sdesc_de=[]\n",
"\n",
"desc_en=[]\n",
"desc_de=[]\n",
"\n",
"cat_en=[]\n",
"cat_de=[]\n",
"\n",
"catpath_en=[]\n",
"catpath_de=[]\n",
"\n",
"for hit in resp['hits']['hits']:\n",
" list_row =[]\n",
" for name in hit['_source']['nameSource']:\n",
" if (name[\"language\"]==\"en\"):\n",
" list_row.append(cleanStr(name[\"value\"]))\n",
" else:\n",
" name_de.append(name[\"value\"])\n",
" \n",
" for sdesc in hit['_source']['shortDescriptionSource']:\n",
" if (sdesc[\"language\"]==\"en\"):\n",
" list_row.append(cleanStr(sdesc[\"value\"]))\n",
" else:\n",
" sdesc_de.append(sdesc[\"value\"])\n",
"\n",
" # for desc in hit['_source']['descriptionsSource']:\n",
" # if (desc[\"language\"]==\"en\"):\n",
" # desc_en.append(readHtml(desc[\"value\"]))\n",
" # else:\n",
" # desc_de.append(desc[\"value\"])\n",
" \n",
" for cats in hit['_source']['categoriesSource']:\n",
" if (cats[\"language\"]==\"en\"):\n",
" list_row.append(cleanStr(cats[\"label\"]))\n",
" else:\n",
" desc_de.append(cats[\"label\"])\n",
"\n",
" if (cats[\"language\"]==\"en\"):\n",
" categories =cats[\"path\"].split('/')\n",
" i =0\n",
" catls=[]\n",
" for category in categories:\n",
"\n",
" list_row.append(cleanStr(category))\n",
" i= i+1\n",
" \n",
" else:\n",
" catpath_de.append(cats[\"path\"])\n",
" \n",
" # new_row = pd.DataFrame({'name':_name, 'sdesc':_sdesc, 'category':_cat_en }, index=[0])\n",
"\n",
" # pd.concat([new_row,df_eng.loc[:]]).reset_index(drop=True)\n",
"\n",
" for i in range (0,9-len(list_row)):\n",
" list_row.append(np.nan)\n",
"\n",
" df_eng.loc[len(df_eng)] = list_row\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# df_en = pd.DataFrame({'name':name_en,\n",
"# 'sdesc':sdesc_en,\n",
"# # 'desc':desc_en,\n",
"# 'category':cat_en,\n",
"# 'categorypath':catpath_en})\n",
"\n",
"\n",
"# df_de = pd.DataFrame({'name':name_de,\n",
"# 'sdesc':sdesc_de,\n",
"# 'desc':desc_de,\n",
"# 'category':cat_de,\n",
"# 'categorypath':catpath_de})"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print (df_eng.to_latex())"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"df_eng.isna().sum()"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(10, 9)"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"df_eng.shape"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"df_eng = df_eng.dropna()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"df_eng.shape"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"df_eng.head()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"df_eng.describe()"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"One hot encoding "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# df_eng = pd.get_dummies(df_eng,columns=[\"category\"])\n",
"# df_eng.head()"
]
},
{
"cell_type": "code",
"execution_count": 59,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"name vaico v10 2660 mounting automatic transmission\n",
"sdesc mounting automatic transmission\n",
"category mounting\n",
"catlevel0 sparepart\n",
"catlevel1 transmission\n",
"catlevel2 automatic transmission\n",
"catlevel3 mounting\n",
"catlevel4 NaN\n",
"catlevel5 NaN\n",
"Name: 7, dtype: object"
]
},
"execution_count": 59,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"df_eng.iloc[7]"
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {},
"outputs": [],
"source": [
"from sklearn.feature_extraction.text import CountVectorizer\n",
"n_gram_vectorizer = CountVectorizer(ngram_range=(1, 1))\n",
"n_gram_vectorizer.fit(df_eng['name'] + df_eng['category'] )\n",
"transformed_vector_name = n_gram_vectorizer.transform(df_eng['name'])\n",
"transformed_vector_sdesc = n_gram_vectorizer.transform(df_eng['sdesc'])\n",
"transformed_vector_category = n_gram_vectorizer.transform(df_eng['category'])\n",
"\n",
"# vocabulary\n"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'denso': 22,\n",
" 'dtm82363': 23,\n",
" 'thermostat': 33,\n",
" 'coolantthermostat': 21,\n",
" 'zf': 45,\n",
" '1043': 7,\n",
" '010': 1,\n",
" '297': 11,\n",
" 'automatic': 17,\n",
" 'transmissionautomatic': 37,\n",
" 'transmission': 36,\n",
" '1060': 8,\n",
" '040': 4,\n",
" '003': 0,\n",
" 'vaico': 43,\n",
" 'v10': 39,\n",
" '0131': 2,\n",
" 'camshaftcamshaft': 19,\n",
" 'v26': 41,\n",
" '0302': 3,\n",
" 'track': 35,\n",
" 'control': 20,\n",
" 'armtrack': 16,\n",
" 'arm': 15,\n",
" 'v30': 42,\n",
" '1250': 9,\n",
" 'suspension': 31,\n",
" 'kitsuspension': 27,\n",
" 'kit': 26,\n",
" '0474': 5,\n",
" 'tensioner': 32,\n",
" 'pulley': 29,\n",
" 'timing': 34,\n",
" 'belttensioner': 18,\n",
" '2660': 10,\n",
" 'mounting': 28,\n",
" 'transmissionmounting': 38,\n",
" '4245': 12,\n",
" 'shock': 30,\n",
" 'absorbershock': 14,\n",
" 'absorber': 13,\n",
" 'v24': 40,\n",
" '0908': 6,\n",
" 'wheel': 44,\n",
" 'hubwheel': 25,\n",
" 'hub': 24}"
]
},
"execution_count": 33,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"n_gram_vectorizer.vocabulary_"
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(10, 46)"
]
},
"execution_count": 34,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"transformed_vector_name.shape"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
" 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
" 0, 0],\n",
" [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,\n",
" 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,\n",
" 0, 1],\n",
" [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,\n",
" 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,\n",
" 0, 1],\n",
" [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
" 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1,\n",
" 0, 0],\n",
" [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0,\n",
" 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1,\n",
" 0, 0],\n",
" [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
" 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1,\n",
" 0, 0],\n",
" [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
" 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1,\n",
" 0, 0],\n",
" [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,\n",
" 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1,\n",
" 0, 0],\n",
" [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0,\n",
" 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1,\n",
" 0, 0],\n",
" [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
" 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1,\n",
" 1, 0]])"
]
},
"execution_count": 35,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"transformed_vector_name.toarray()"
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"17"
]
},
"execution_count": 37,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"n_gram_vectorizer.vocabulary_.get('automatic')"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"ename": "NameError",
"evalue": "name 'vocabulary' is not defined",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[0;32mIn[18], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m vocabulary\u001b[39m.\u001b[39mitems()\n",
"\u001b[0;31mNameError\u001b[0m: name 'vocabulary' is not defined"
]
}
],
"source": [
"vocabulary.items()"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [],
"source": [
"from sklearn.model_selection import train_test_split\n",
"\n",
"X_train, x_test, Y_train, y_test = train_test_split(transformed_vector_sdesc,\n",
" transformed_vector_category,\n",
" test_size=0.2,\n",
" random_state=0)"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"((8, 19), (8, 16))"
]
},
"execution_count": 20,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"X_train.shape, Y_train.shape"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [],
"source": [
"import torch\n",
"import torch.nn as nn\n",
"import torch.nn.functional as F\n",
"import numpy as np"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"ename": "AttributeError",
"evalue": "values not found",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[0;32mIn[21], line 3\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[39mimport\u001b[39;00m \u001b[39mtorch\u001b[39;00m\n\u001b[1;32m 2\u001b[0m \u001b[39mimport\u001b[39;00m \u001b[39mnumpy\u001b[39;00m \u001b[39mas\u001b[39;00m \u001b[39mnp\u001b[39;00m\n\u001b[0;32m----> 3\u001b[0m Xtrain_ \u001b[39m=\u001b[39m torch\u001b[39m.\u001b[39mfrom_numpy(X_train\u001b[39m.\u001b[39;49mvalues)\u001b[39m.\u001b[39mfloat()\n\u001b[1;32m 4\u001b[0m Xtest_ \u001b[39m=\u001b[39m torch\u001b[39m.\u001b[39mfrom_numpy(x_test\u001b[39m.\u001b[39mvalues)\u001b[39m.\u001b[39mfloat()\n\u001b[1;32m 5\u001b[0m Xtrain_\u001b[39m.\u001b[39mshape\n",
"File \u001b[0;32m~/dev/.venv/lib/python3.10/site-packages/scipy/sparse/_base.py:771\u001b[0m, in \u001b[0;36mspmatrix.__getattr__\u001b[0;34m(self, attr)\u001b[0m\n\u001b[1;32m 769\u001b[0m \u001b[39mreturn\u001b[39;00m \u001b[39mself\u001b[39m\u001b[39m.\u001b[39mgetnnz()\n\u001b[1;32m 770\u001b[0m \u001b[39melse\u001b[39;00m:\n\u001b[0;32m--> 771\u001b[0m \u001b[39mraise\u001b[39;00m \u001b[39mAttributeError\u001b[39;00m(attr \u001b[39m+\u001b[39m \u001b[39m\"\u001b[39m\u001b[39m not found\u001b[39m\u001b[39m\"\u001b[39m)\n",
"\u001b[0;31mAttributeError\u001b[0m: values not found"
]
}
],
"source": [
"\n",
"Xtrain_ = torch.from_numpy(X_train).float()\n",
"Xtest_ = torch.from_numpy(x_test).float()\n",
"Xtrain_.shape\n",
"Ytrain_ = torch.from_numpy(Y_train).view(1,-1)[0]\n",
"Ytest_ = torch.from_numpy(y_test).view(1,-1)[0]\n",
"Ytrain_.shape"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"ename": "NameError",
"evalue": "name 'nn' is not defined",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
"Cell \u001b[0;32mIn[22], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[39mclass\u001b[39;00m \u001b[39mNet\u001b[39;00m(nn\u001b[39m.\u001b[39mModule):\n\u001b[1;32m 3\u001b[0m \u001b[39mdef\u001b[39;00m \u001b[39m__init__\u001b[39m(\u001b[39mself\u001b[39m):\n\u001b[1;32m 4\u001b[0m \u001b[39msuper\u001b[39m(Net, \u001b[39mself\u001b[39m)\u001b[39m.\u001b[39m\u001b[39m__init__\u001b[39m()\n",
"\u001b[0;31mNameError\u001b[0m: name 'nn' is not defined"
]
}
],
"source": [
"class Net(nn.Module):\n",
" \n",
" def __init__(self):\n",
" super(Net, self).__init__()\n",
" self.fc1 = nn.Linear(input_size, hidden_size) \n",
" self.fc2 = nn.Linear(hidden_size, hidden_size) \n",
" self.fc3 = nn.Linear(hidden_size, output_size) \n",
" \n",
" def forward(self, x):\n",
" x = F.sigmoid(self.fc1(x))\n",
" x = F.sigmoid(self.fc2(x)) \n",
" x = self.fc3(x)\n",
" \n",
" return F.log_softmax(x, dim=-1)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"model = Net()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import torch.optim as optim\n",
"\n",
"optimizer = optim.Adam(model.parameters())\n",
"\n",
"loss_fn = nn.NLLLoss()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"epoch_data = []\n",
"epochs = 1001\n",
"\n",
"for epoch in range(1, epochs):\n",
"\n",
" optimizer.zero_grad()\n",
" Ypred = model(Xtrain_)\n",
"\n",
" loss = loss_fn(Ypred , Ytrain_)\n",
" loss.backward()\n",
"\n",
" optimizer.step()\n",
" \n",
" Ypred_test = model(Xtest_)\n",
" loss_test = loss_fn(Ypred_test, Ytest_)\n",
" \n",
" _,pred = Ypred_test.data.max(1)\n",
" \n",
" accuracy = pred.eq(Ytest_.data).sum().item() / y_test.values.size\n",
" epoch_data.append([epoch, loss.data.item(), loss_test.data.item(), accuracy])\n",
" \n",
" if epoch % 100 == 0:\n",
" print ('epoch - %d (%d%%) train loss - %.2f test loss - %.2f accuracy - %.4f'\\\n",
" % (epoch, epoch/150 * 10 , loss.data.item(), loss_test.data.item(), accuracy))"
]
}
],
"metadata": {
"kernelspec": {
"display_name": ".venv",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.12"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}