In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
GaussianNB()
"
576 | ],
577 | "text/plain": [
578 | "GaussianNB()"
579 | ]
580 | },
581 | "execution_count": 15,
582 | "metadata": {},
583 | "output_type": "execute_result"
584 | }
585 | ],
586 | "source": [
587 | "from sklearn.model_selection import train_test_split\n",
588 | "x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.20)\n",
589 | "classifier = GaussianNB()\n",
590 | "classifier.fit(x_train, y_train)"
591 | ]
592 | },
593 | {
594 | "cell_type": "code",
595 | "execution_count": 16,
596 | "metadata": {},
597 | "outputs": [
598 | {
599 | "name": "stdout",
600 | "output_type": "stream",
601 | "text": [
602 | "Accuracy is: 0.6666666666666666\n"
603 | ]
604 | }
605 | ],
606 | "source": [
607 | "from sklearn.metrics import accuracy_score\n",
608 | "print(\"Accuracy is:\", accuracy_score(classifier.predict(x_test), y_test))"
609 | ]
610 | },
611 | {
612 | "cell_type": "code",
613 | "execution_count": null,
614 | "metadata": {},
615 | "outputs": [],
616 | "source": []
617 | }
618 | ],
619 | "metadata": {
620 | "kernelspec": {
621 | "display_name": "Python 3",
622 | "language": "python",
623 | "name": "python3"
624 | },
625 | "language_info": {
626 | "codemirror_mode": {
627 | "name": "ipython",
628 | "version": 3
629 | },
630 | "file_extension": ".py",
631 | "mimetype": "text/x-python",
632 | "name": "python",
633 | "nbconvert_exporter": "python",
634 | "pygments_lexer": "ipython3",
635 | "version": "3.12.4"
636 | }
637 | },
638 | "nbformat": 4,
639 | "nbformat_minor": 2
640 | }
641 |
--------------------------------------------------------------------------------
/ML lab/program6.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {
6 | "colab_type": "text",
7 | "id": "view-in-github"
8 | },
9 | "source": [
10 | ""
11 | ]
12 | },
13 | {
14 | "cell_type": "markdown",
15 | "metadata": {},
16 | "source": [
17 | "### Assuming a set of documents that need to be classified, use the naïve Bayesian Classifier model to perform this task. Built-in Java classes/API can be used to write the program. Calculate the accuracy, precision, and recall for your data set."
18 | ]
19 | },
20 | {
21 | "cell_type": "code",
22 | "execution_count": null,
23 | "metadata": {
24 | "colab": {
25 | "base_uri": "https://localhost:8080/"
26 | },
27 | "id": "jLAz6hwLrk04",
28 | "outputId": "852dbb98-1468-4e60-d78f-103a4cc29c7e"
29 | },
30 | "outputs": [
31 | {
32 | "name": "stdout",
33 | "output_type": "stream",
34 | "text": [
35 | "The dimmension of the dataset (18, 2)\n",
36 | "0 I love this sandwich\n",
37 | "1 This is an amazing place\n",
38 | "2 I feel very good about these beers\n",
39 | "3 This is my best work\n",
40 | "4 What an awesome view\n",
41 | "5 I do not like this restaurant\n",
42 | "6 I am tired of this stuff\n",
43 | "7 I can't deal with this\n",
44 | "8 He is my sworn enemy\n",
45 | "9 My boss is horrible\n",
46 | "10 This is an awesome place\n",
47 | "11 I do not like the taste of this juice\n",
48 | "12 I love to dance\n",
49 | "13 I am sick and tired of this place\n",
50 | "14 What a great holiday\n",
51 | "15 That is a bad locality to stay\n",
52 | "16 We will have good fun tomorrow\n",
53 | "17 I went to my enemy's house today\n",
54 | "Name: message, dtype: object\n",
55 | "0 1\n",
56 | "1 1\n",
57 | "2 1\n",
58 | "3 1\n",
59 | "4 1\n",
60 | "5 0\n",
61 | "6 0\n",
62 | "7 0\n",
63 | "8 0\n",
64 | "9 0\n",
65 | "10 1\n",
66 | "11 0\n",
67 | "12 1\n",
68 | "13 0\n",
69 | "14 1\n",
70 | "15 0\n",
71 | "16 1\n",
72 | "17 0\n",
73 | "Name: labelnum, dtype: int64\n"
74 | ]
75 | }
76 | ],
77 | "source": [
78 | "import pandas as pd\n",
79 | "msg = pd.read_csv(\"naivetext.csv\", names = ['message','label'])\n",
80 | "print('The dimmension of the dataset ', msg.shape)\n",
81 | "msg['labelnum'] = msg.label.map({'pos':1, 'neg':0})\n",
82 | "X = msg.message\n",
83 | "y = msg.labelnum\n",
84 | "print(X)\n",
85 | "print(y)"
86 | ]
87 | },
88 | {
89 | "cell_type": "code",
90 | "execution_count": null,
91 | "metadata": {
92 | "colab": {
93 | "base_uri": "https://localhost:8080/"
94 | },
95 | "id": "pc4LmH0rvR-Q",
96 | "outputId": "8e80f21c-2478-4f46-a9e0-a97db5426676"
97 | },
98 | "outputs": [
99 | {
100 | "name": "stdout",
101 | "output_type": "stream",
102 | "text": [
103 | "\n",
104 | " the total number of training data (14,)\n",
105 | "\n",
106 | " the total number of testing data (4,)\n"
107 | ]
108 | }
109 | ],
110 | "source": [
111 | "# splitting the data set into train and test data set\n",
112 | "from sklearn.model_selection import train_test_split\n",
113 | "xtrain, xtest, ytrain, ytest = train_test_split(X, y,test_size=0.20)\n",
114 | "\n",
115 | "print('\\n the total number of training data ',ytrain.shape)\n",
116 | "print('\\n the total number of testing data ',ytest.shape)"
117 | ]
118 | },
119 | {
120 | "cell_type": "code",
121 | "execution_count": null,
122 | "metadata": {
123 | "colab": {
124 | "base_uri": "https://localhost:8080/"
125 | },
126 | "id": "Q_djbAkswkdE",
127 | "outputId": "6d836d87-99cc-49e6-8ff8-fd724866c75d"
128 | },
129 | "outputs": [
130 | {
131 | "name": "stdout",
132 | "output_type": "stream",
133 | "text": [
134 | "\n",
135 | " The words or Tokens in the text documents \n",
136 | "\n",
137 | "['about' 'am' 'amazing' 'an' 'and' 'awesome' 'beers' 'best' 'boss' 'can'\n",
138 | " 'dance' 'deal' 'do' 'enemy' 'feel' 'fun' 'good' 'have' 'he' 'horrible'\n",
139 | " 'house' 'is' 'like' 'love' 'my' 'not' 'of' 'place' 'restaurant'\n",
140 | " 'sandwich' 'sick' 'sworn' 'these' 'this' 'tired' 'to' 'today' 'tomorrow'\n",
141 | " 'very' 'view' 'we' 'went' 'what' 'will' 'with' 'work']\n"
142 | ]
143 | }
144 | ],
145 | "source": [
146 | "# output of the words or token in the text document\n",
147 | "import numpy as np\n",
148 | "from sklearn.feature_extraction.text import CountVectorizer\n",
149 | "count_vect = CountVectorizer()\n",
150 | "xtrain_dtm = count_vect.fit_transform(xtrain)\n",
151 | "xtest_dtm = count_vect.transform(xtest)\n",
152 | "index = count_vect.get_feature_names_out()\n",
153 | "print('\\n The words or Tokens in the text documents \\n')\n",
154 | "print(count_vect.get_feature_names_out())\n",
155 | "df = pd.DataFrame(xtrain_dtm.toarray(), columns = count_vect.get_feature_names_out())\n",
156 | "\n"
157 | ]
158 | },
159 | {
160 | "cell_type": "code",
161 | "execution_count": null,
162 | "metadata": {
163 | "id": "44_Jf596xe5P"
164 | },
165 | "outputs": [],
166 | "source": [
167 | "from sklearn.naive_bayes import MultinomialNB\n",
168 | "clf = MultinomialNB()\n",
169 | "clf.fit(xtrain_dtm,ytrain)\n",
170 | "predicted = clf.predict(xtest_dtm)"
171 | ]
172 | },
173 | {
174 | "cell_type": "code",
175 | "execution_count": null,
176 | "metadata": {
177 | "colab": {
178 | "base_uri": "https://localhost:8080/"
179 | },
180 | "id": "0-on1MEGyEmi",
181 | "outputId": "be3bddba-1013-4773-e40d-256dd608eca2"
182 | },
183 | "outputs": [
184 | {
185 | "name": "stdout",
186 | "output_type": "stream",
187 | "text": [
188 | "\n",
189 | " Accuracy of the classifier is 0.75\n",
190 | "\n",
191 | " confusion matrix\n",
192 | "[[2 1]\n",
193 | " [0 1]]\n",
194 | "\n",
195 | " The value of Precision 0.5\n",
196 | "\n",
197 | " The value of Recall 1.0\n"
198 | ]
199 | }
200 | ],
201 | "source": [
202 | "from sklearn import metrics\n",
203 | "print('\\n Accuracy of the classifier is ', metrics.accuracy_score(ytest, predicted))\n",
204 | "print('\\n confusion matrix')\n",
205 | "print(metrics.confusion_matrix(ytest, predicted))\n",
206 | "print('\\n The value of Precision', metrics.precision_score(ytest, predicted))\n",
207 | "print('\\n The value of Recall', metrics.recall_score(ytest, predicted))"
208 | ]
209 | }
210 | ],
211 | "metadata": {
212 | "colab": {
213 | "authorship_tag": "ABX9TyPCyT4YhsJ6FUkq0PzeV/yY",
214 | "include_colab_link": true,
215 | "mount_file_id": "1Kv3AyABmnWyNtCSZGAXQlmP8UgG0VajC",
216 | "provenance": []
217 | },
218 | "kernelspec": {
219 | "display_name": "Python 3",
220 | "name": "python3"
221 | },
222 | "language_info": {
223 | "name": "python"
224 | }
225 | },
226 | "nbformat": 4,
227 | "nbformat_minor": 0
228 | }
229 |
--------------------------------------------------------------------------------
/ML lab/program7.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {
6 | "id": "view-in-github",
7 | "colab_type": "text"
8 | },
9 | "source": [
10 | ""
11 | ]
12 | },
13 | {
14 | "cell_type": "markdown",
15 | "metadata": {
16 | "id": "qHpdG_H0Su6f"
17 | },
18 | "source": [
19 | "### Write a program to demonstrate the working of the decision tree based ID3 algorithm. Use an appropriate data set for building the decision tree and apply this knowledge toclassify a new sample"
20 | ]
21 | },
22 | {
23 | "cell_type": "code",
24 | "execution_count": null,
25 | "metadata": {
26 | "id": "EmRROYJJ6a5u"
27 | },
28 | "outputs": [],
29 | "source": [
30 | "import pandas as pd\n",
31 | "import numpy as np\n",
32 | "df_tennis = pd.read_csv('tennis.csv')\n",
33 | "print(df_tennis)"
34 | ]
35 | },
36 | {
37 | "cell_type": "code",
38 | "execution_count": null,
39 | "metadata": {
40 | "colab": {
41 | "base_uri": "https://localhost:8080/",
42 | "height": 36
43 | },
44 | "id": "8mVt2Hd48FxL",
45 | "outputId": "82913713-2b1b-4eeb-e28b-7c70d12c3e1f"
46 | },
47 | "outputs": [
48 | {
49 | "data": {
50 | "application/vnd.google.colaboratory.intrinsic+json": {
51 | "type": "string"
52 | },
53 | "text/plain": [
54 | "'Outlook'"
55 | ]
56 | },
57 | "execution_count": 9,
58 | "metadata": {},
59 | "output_type": "execute_result"
60 | }
61 | ],
62 | "source": [
63 | "df_tennis.keys()[0]"
64 | ]
65 | },
66 | {
67 | "cell_type": "code",
68 | "execution_count": null,
69 | "metadata": {
70 | "id": "4SGbEj_A8WCS"
71 | },
72 | "outputs": [],
73 | "source": [
74 | "# Entropy of the training data set\n",
75 | "from collections import Counter\n",
76 | "def entropy_list(a_list):\n",
77 | " cnt = Counter(x for x in a_list)\n",
78 | "import math\n",
79 | "def entropy_list(a_list):\n",
80 | " cnt = Counter(x for x in a_list)\n",
81 | " num_instances = len(a_list)*1.0\n",
82 | " probs = [x/num_instances for x in cnt.values()]\n",
83 | " # Function to calculate the entropy of the probablity of observation\n",
84 | " return entropy(probs)\n",
85 | "def entropy(probs):\n",
86 | " return -sum(p*math.log(p,2) for p in probs if p>0)\n"
87 | ]
88 | },
89 | {
90 | "cell_type": "code",
91 | "execution_count": null,
92 | "metadata": {
93 | "id": "7YPIpvaF9C52"
94 | },
95 | "outputs": [],
96 | "source": [
97 | "\n",
98 | "# import math\n",
99 | "# def entropy(probs)\n",
100 | "# return sum ([-prob*math.log(prob,2) for prob in probs])"
101 | ]
102 | },
103 | {
104 | "cell_type": "code",
105 | "execution_count": null,
106 | "metadata": {
107 | "id": "HEYY7FYs-G9w"
108 | },
109 | "outputs": [],
110 | "source": [
111 | "def entropy_of_list(a_list):\n",
112 | " print(\"A_list\",a_list)\n",
113 | " from collections import Counter\n",
114 | " cnt = Counter(x for x in a_list)\n",
115 | " print(\"\\n Class : \" , cnt)\n",
116 | " print(\"No and Yes Classes : \",a_list.name,cnt)\n",
117 | " num_instances = len(a_list)*1.0\n",
118 | " print(\"\\n Number of Instances of the Current Sub Class is {0}:\".format(num_instances))\n",
119 | " probs = [x/num_instances for x in cnt.values()]\n",
120 | " print(\"\\n Class : \", min(cnt),max(cnt))\n",
121 | " print(\"\\n Probablities of class {0} is {1} :\" .format(min(cnt),min(probs)))\n",
122 | " print(\"\\n Probablities of class {0} is {1} :\" .format(max(cnt),max(probs)))\n",
123 | " return entropy(probs)\n",
124 | "\n",
125 | " print(\"\\n INPUT DATA SET FOR ENTROPY CALCULATION :\\n \", df_tennis['PlayTennis'])\n",
126 | " total_entropy = entropy_of_list(df_tennis['PlayTennis'])\n",
127 | " print(\"\\n Total Entropy of PlayTennis Data Set : \",total_entropy)"
128 | ]
129 | },
130 | {
131 | "cell_type": "code",
132 | "execution_count": null,
133 | "metadata": {
134 | "colab": {
135 | "base_uri": "https://localhost:8080/"
136 | },
137 | "id": "YLyjq6uZewkK",
138 | "outputId": "6a468621-58d1-4a45-aefe-4bcf1c93943e"
139 | },
140 | "outputs": [
141 | {
142 | "name": "stdout",
143 | "output_type": "stream",
144 | "text": [
145 | "Information Gain Calculation of Outlook\n",
146 | "Name: overcast\n",
147 | "Group: Outlook Temperature Humidity Wind Answer\n",
148 | "2 overcast hot high weak yes\n",
149 | "6 overcast cool normal strong yes\n",
150 | "11 overcast mild high strong yes\n",
151 | "12 overcast hot normal weak yes\n",
152 | "Name: rain\n",
153 | "Group: Outlook Temperature Humidity Wind Answer\n",
154 | "3 rain mild high weak yes\n",
155 | "4 rain cool normal weak yes\n",
156 | "5 rain cool normal strong no\n",
157 | "9 rain mild normal weak yes\n",
158 | "13 rain mild high strong no\n",
159 | "Name: sunny\n",
160 | "Group: Outlook Temperature Humidity Wind Answer\n",
161 | "0 sunny hot high weak no\n",
162 | "1 sunny hot high strong no\n",
163 | "7 sunny mild high weak no\n",
164 | "8 sunny cool normal weak yes\n",
165 | "10 sunny mild normal strong yes\n",
166 | "['Answer']\n",
167 | "Entropy List \n",
168 | "DFAGGENT entropy_of_list \n",
169 | "Outlook \n",
170 | "overcast -0.000000 0.285714\n",
171 | "rain 0.970951 0.357143\n",
172 | "sunny 0.970951 0.357143\n",
173 | "Info-gain for Outlook is :0.2467498197744391 \n",
174 | "\n",
175 | "Information Gain Calculation of Humidity\n",
176 | "Name: high\n",
177 | "Group: Outlook Temperature Humidity Wind Answer\n",
178 | "0 sunny hot high weak no\n",
179 | "1 sunny hot high strong no\n",
180 | "2 overcast hot high weak yes\n",
181 | "3 rain mild high weak yes\n",
182 | "7 sunny mild high weak no\n",
183 | "11 overcast mild high strong yes\n",
184 | "13 rain mild high strong no\n",
185 | "Name: normal\n",
186 | "Group: Outlook Temperature Humidity Wind Answer\n",
187 | "4 rain cool normal weak yes\n",
188 | "5 rain cool normal strong no\n",
189 | "6 overcast cool normal strong yes\n",
190 | "8 sunny cool normal weak yes\n",
191 | "9 rain mild normal weak yes\n",
192 | "10 sunny mild normal strong yes\n",
193 | "12 overcast hot normal weak yes\n",
194 | "['Answer']\n",
195 | "Entropy List \n",
196 | "DFAGGENT entropy_of_list \n",
197 | "Humidity \n",
198 | "high 0.985228 0.5\n",
199 | "normal 0.591673 0.5\n",
200 | "Info-gain for Humidity is :0.15183550136234136 \n",
201 | "\n",
202 | "Information Gain Calculation of Wind\n",
203 | "Name: strong\n",
204 | "Group: Outlook Temperature Humidity Wind Answer\n",
205 | "1 sunny hot high strong no\n",
206 | "5 rain cool normal strong no\n",
207 | "6 overcast cool normal strong yes\n",
208 | "10 sunny mild normal strong yes\n",
209 | "11 overcast mild high strong yes\n",
210 | "13 rain mild high strong no\n",
211 | "Name: weak\n",
212 | "Group: Outlook Temperature Humidity Wind Answer\n",
213 | "0 sunny hot high weak no\n",
214 | "2 overcast hot high weak yes\n",
215 | "3 rain mild high weak yes\n",
216 | "4 rain cool normal weak yes\n",
217 | "7 sunny mild high weak no\n",
218 | "8 sunny cool normal weak yes\n",
219 | "9 rain mild normal weak yes\n",
220 | "12 overcast hot normal weak yes\n",
221 | "['Answer']\n",
222 | "Entropy List \n",
223 | "DFAGGENT entropy_of_list \n",
224 | "Wind \n",
225 | "strong 1.000000 0.428571\n",
226 | "weak 0.811278 0.571429\n",
227 | "Info-gain for Wind is :0.04812703040826927 \n",
228 | "\n"
229 | ]
230 | }
231 | ],
232 | "source": [
233 | "def information_gain(df,split_attribute_name,target_attribute_name,trace=0):\n",
234 | " print(\"Information Gain Calculation of \",split_attribute_name)\n",
235 | " df_split = df.groupby(split_attribute_name)\n",
236 | " for name,group in df_split:\n",
237 | " print(\"Name: \",name)\n",
238 | " print(\"Group: \",group)\n",
239 | "\n",
240 | " nobs = len(df.index)*1.0\n",
241 | " df_agg_ent = df_split.agg({target_attribute_name:[entropy_of_list,lambda x:len(x)/nobs]})[target_attribute_name]\n",
242 | " print([target_attribute_name])\n",
243 | " print(\"Entropy List\",entroy_of_list)\n",
244 | " print(\"DFAGGENT\",df_agg_ent)\n",
245 | " df_agg_ent.columns = ['Entropy','PropObservations']\n",
246 | " new_entropy = sum(df_agg_ent['Entropy']*df_agg_ent['PropObservations'])\n",
247 | " old_entropy = entropy_of_list(df[target_attribute_name])\n",
248 | " return old_entropy - new_entropy\n",
249 | "print(\"Info-gain for Outlook is :\"+str(information_gain(df_tennis,'Outlook','Answer',trace=0)),\"\\n\")\n",
250 | "print(\"Info-gain for Humidity is :\"+str(information_gain(df_tennis,'Humidity','Answer',trace=0)),\"\\n\")\n",
251 | "print(\"Info-gain for Wind is :\"+str(information_gain(df_tennis,'Wind','Answer',trace=0)),\"\\n\")\n"
252 | ]
253 | }
254 | ],
255 | "metadata": {
256 | "colab": {
257 | "provenance": [],
258 | "include_colab_link": true
259 | },
260 | "kernelspec": {
261 | "display_name": "Python 3",
262 | "name": "python3"
263 | },
264 | "language_info": {
265 | "codemirror_mode": {
266 | "name": "ipython",
267 | "version": 3
268 | },
269 | "file_extension": ".py",
270 | "mimetype": "text/x-python",
271 | "name": "python",
272 | "nbconvert_exporter": "python",
273 | "pygments_lexer": "ipython3",
274 | "version": "3.12.4"
275 | }
276 | },
277 | "nbformat": 4,
278 | "nbformat_minor": 0
279 | }
--------------------------------------------------------------------------------
/ML lab/program8.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "nbformat": 4,
3 | "nbformat_minor": 0,
4 | "metadata": {
5 | "colab": {
6 | "provenance": [],
7 | "authorship_tag": "ABX9TyOL68SWyMU1c7cFx1OWONDO",
8 | "include_colab_link": true
9 | },
10 | "kernelspec": {
11 | "name": "python3",
12 | "display_name": "Python 3"
13 | },
14 | "language_info": {
15 | "name": "python"
16 | }
17 | },
18 | "cells": [
19 | {
20 | "cell_type": "markdown",
21 | "metadata": {
22 | "id": "view-in-github",
23 | "colab_type": "text"
24 | },
25 | "source": [
26 | ""
27 | ]
28 | },
29 | {
30 | "cell_type": "code",
31 | "execution_count": 1,
32 | "metadata": {
33 | "id": "-YxwPv-v5Bxm"
34 | },
35 | "outputs": [],
36 | "source": [
37 | "from google.colab import drive"
38 | ]
39 | },
40 | {
41 | "cell_type": "code",
42 | "source": [
43 | "drive.mount('/content/drive')"
44 | ],
45 | "metadata": {
46 | "colab": {
47 | "base_uri": "https://localhost:8080/"
48 | },
49 | "id": "r7C5E6wq5Fec",
50 | "outputId": "b15143df-e3ff-4210-f1bf-1c49d6faaa2a"
51 | },
52 | "execution_count": 4,
53 | "outputs": [
54 | {
55 | "output_type": "stream",
56 | "name": "stdout",
57 | "text": [
58 | "Mounted at /content/drive\n"
59 | ]
60 | }
61 | ]
62 | },
63 | {
64 | "cell_type": "code",
65 | "source": [
66 | "%cd /content/drive/MyDrive/"
67 | ],
68 | "metadata": {
69 | "colab": {
70 | "base_uri": "https://localhost:8080/"
71 | },
72 | "id": "wDJGpHpB5KCM",
73 | "outputId": "d7fbf53d-c950-49c7-a343-69036e48560b"
74 | },
75 | "execution_count": 5,
76 | "outputs": [
77 | {
78 | "output_type": "stream",
79 | "name": "stdout",
80 | "text": [
81 | "/content/drive/MyDrive\n"
82 | ]
83 | }
84 | ]
85 | },
86 | {
87 | "cell_type": "markdown",
88 | "source": [
89 | "##Write a program to construct aBayesian network considering medical data. Use this model to demonstrate the diagnosis of heart patients using standard Heart Disease Data Set. You can use Java/Python ML library classes/API."
90 | ],
91 | "metadata": {
92 | "id": "OOlAVBXl561C"
93 | }
94 | },
95 | {
96 | "cell_type": "code",
97 | "source": [
98 | "import pandas as pd\n",
99 | "data = pd.read_csv('/content/drive/MyDrive/mydata/heartdisease .csv')\n",
100 | "heart_disease = pd.DataFrame(data)\n",
101 | "print(heart_disease)"
102 | ],
103 | "metadata": {
104 | "colab": {
105 | "base_uri": "https://localhost:8080/"
106 | },
107 | "id": "I3lpNJcS5YXT",
108 | "outputId": "668686ce-8b7a-4323-ba1e-0d798217ff80"
109 | },
110 | "execution_count": 15,
111 | "outputs": [
112 | {
113 | "output_type": "stream",
114 | "name": "stdout",
115 | "text": [
116 | " age Gender Family diet Lifestyle cholestrol heartdisease\n",
117 | "0 0 0 1 1 3 0 1\n",
118 | "1 0 1 1 1 3 0 1\n",
119 | "2 1 0 0 0 2 1 1\n",
120 | "3 4 0 1 1 3 2 0\n",
121 | "4 3 1 1 0 0 2 0\n",
122 | "5 2 0 1 1 1 0 1\n",
123 | "6 4 0 1 0 2 0 1\n",
124 | "7 0 0 1 1 3 0 1\n",
125 | "8 3 1 1 0 0 2 0\n",
126 | "9 1 1 0 0 0 2 1\n",
127 | "10 4 1 0 1 2 0 1\n",
128 | "11 4 0 1 1 3 2 0\n",
129 | "12 2 1 0 0 0 0 0\n",
130 | "13 2 0 1 1 1 0 1\n",
131 | "14 3 1 1 0 0 1 0\n",
132 | "15 0 0 1 0 0 2 1\n",
133 | "16 1 1 0 1 2 1 1\n",
134 | "17 3 1 1 1 0 1 0\n",
135 | "18 4 0 1 1 3 2 0\n"
136 | ]
137 | }
138 | ]
139 | },
140 | {
141 | "cell_type": "code",
142 | "source": [
143 | "import pgmpy.models\n",
144 | "from pgmpy.models import BayesianNetwork\n",
145 | "model = BayesianNetwork([\n",
146 | "('age' , 'Lifestyle'),\n",
147 | "('Gender' , 'Lifestyle'),\n",
148 | "('Family' , 'heartdisease'),\n",
149 | "('diet' , 'cholestrol'),\n",
150 | "('Lifestyle' , 'diet'),\n",
151 | "('cholestrol' , 'heartdisease'),\n",
152 | "('diet' , 'cholestrol')\n",
153 | "\n",
154 | "])\n",
155 | "\n",
156 | "from pgmpy.estimators import MaximumLikelihoodEstimator\n",
157 | "model.fit(heart_disease , estimator=MaximumLikelihoodEstimator)\n",
158 | "\n",
159 | "from pgmpy.inference import VariableElimination\n",
160 | "HeartDisease_infer = VariableElimination(model)"
161 | ],
162 | "metadata": {
163 | "id": "NZz7Wj6w6s7c"
164 | },
165 | "execution_count": 18,
166 | "outputs": []
167 | },
168 | {
169 | "cell_type": "code",
170 | "source": [
171 | "print('For age Enter { SuperSeniorCitizen:0, SeniorCitizen:1, MiddleAged:2, Youth:3, Teen:4 } ')\n",
172 | "print('For Gender Enter { Male:0, Female:1 }')\n",
173 | "print('For Family History Enter { yes:1, No:0 }')\n",
174 | "print('For diet Enter { High:0, Medium:1 }')\n",
175 | "print('For LifeStyle Enter { Athlete:0, Active:1, Moderate:2, Sedentary:3 }')\n",
176 | "print('For cholesterol Enter { High:0, BorderLine:1, Normal:2 }')\n",
177 | "\n",
178 | "q = HeartDisease_infer.query(variables=['heartdisease'], evidence={\n",
179 | " 'age':int(input('Enter age: ')),\n",
180 | " 'Gender':int(input('Enter Gender: ')),\n",
181 | " 'Family':int(input('Enter Family History: ')),\n",
182 | " 'diet':int(input('Enter diet: ')),\n",
183 | " 'Lifestyle':int(input('Enter Lifestyle: ')),\n",
184 | " 'cholestrol':int(input('Enter cholestrol: '))\n",
185 | "\n",
186 | "})\n",
187 | "\n",
188 | "heart_disease_prob = q.values[1]\n",
189 | "print(f\"Probability of heart disease (heartdisease = 1): {heart_disease_prob}\")"
190 | ],
191 | "metadata": {
192 | "colab": {
193 | "base_uri": "https://localhost:8080/"
194 | },
195 | "id": "kCtRPq4k88yR",
196 | "outputId": "8654dc99-4802-45bb-988c-8b3b5fa6dde2"
197 | },
198 | "execution_count": 23,
199 | "outputs": [
200 | {
201 | "output_type": "stream",
202 | "name": "stdout",
203 | "text": [
204 | "For age Enter { SuperSeniorCitizen:0, SeniorCitizen:1, MiddleAged:2, Youth:3, Teen:4 } \n",
205 | "For Gender Enter { Male:0, Female:1 }\n",
206 | "For Family History Enter { yes:1, No:0 }\n",
207 | "For diet Enter { High:0, Medium:1 }\n",
208 | "For LifeStyle Enter { Athlete:0, Active:1, Moderate:2, Sedentary:3 }\n",
209 | "For cholesterol Enter { High:0, BorderLine:1, Normal:2 }\n",
210 | "Enter age: 1\n",
211 | "Enter Gender: 1\n",
212 | "Enter Family History: 1\n",
213 | "Enter diet: 1\n",
214 | "Enter Lifestyle: 1\n",
215 | "Enter cholestrol: 1\n",
216 | "Query result: \n",
217 | "+-----------------+---------------------+\n",
218 | "| heartdisease | phi(heartdisease) |\n",
219 | "+=================+=====================+\n",
220 | "| heartdisease(0) | 1.0000 |\n",
221 | "+-----------------+---------------------+\n",
222 | "| heartdisease(1) | 0.0000 |\n",
223 | "+-----------------+---------------------+\n",
224 | "Probability of heart disease (heartdisease = 1): 0.0\n"
225 | ]
226 | }
227 | ]
228 | },
229 | {
230 | "cell_type": "code",
231 | "source": [],
232 | "metadata": {
233 | "id": "9tHNofbM-ib8"
234 | },
235 | "execution_count": null,
236 | "outputs": []
237 | }
238 | ]
239 | }
--------------------------------------------------------------------------------
/Python lab/new.c:
--------------------------------------------------------------------------------
1 | printf("hello")
--------------------------------------------------------------------------------
/Python lab/program01.py:
--------------------------------------------------------------------------------
1 | # AIM : Write a program to demonstratebasic data type in python.
2 | a = 5
3 | print("value of a is " , a ," it is type of " , type(a))
4 | b = 5.5
5 | print("value of a is " , b ," it is type of " , type(b))
6 | c = "messi"
7 | print("value of c is " , c ," it is type of " , type(c))
8 | d = True
9 | print("value of d is " , d ," it is type of " , type(d))
10 | e = (1,2,3)
11 | print("value of e is " , e ," it is type of " , type(e))
12 | f = [4,5,6]
13 | print("value of f is " , f ," it is type of " , type(f))
14 | g = {"name":"messi", "age":37}
15 | print("value of g is " , g ," it is type of " , type(g))
16 | h = {1,1,4,2}
17 | print("value of h is " , h ," it is type of " , type(h))
18 |
19 |
--------------------------------------------------------------------------------
/Python lab/program02-a.py:
--------------------------------------------------------------------------------
1 | # Aim : Write a program to compute distance between two points taking input from the user
2 | import math as m
3 | print("For first point enter the values for the x and y cordinate")
4 | x1 = float(input())
5 | y1 = float(input())
6 | print("For second point enter the values for the x and y cordinate")
7 | x2 = float(input())
8 | y2 = float(input())
9 | res = m.sqrt((x2 - x1)**2 + (y2 -y1)**2)
10 | print("Distance between the two point is " , res)
--------------------------------------------------------------------------------
/Python lab/program02-b.py:
--------------------------------------------------------------------------------
1 | # Aim : Write a program add.py that takes 2 numbers as command line arguments and prints its sum.
2 | import sys
3 | num1 = int(sys.argv[1])
4 | num2 = int(sys.argv[2])
5 | print("Sum of num1 and num2 is " , (num1 + num2))
--------------------------------------------------------------------------------
/Python lab/program03-a.py:
--------------------------------------------------------------------------------
1 | # Write a Program for checking whether the givennumber is an even number or not.
2 | num = int(input("Enter a number "))
3 | if(num % 2 == 0):
4 | print("Given number is an even number ")
5 | else:
6 | print("Given number is a odd number ")
--------------------------------------------------------------------------------
/Python lab/program03-b.py:
--------------------------------------------------------------------------------
1 | # Aim : Using a for loop, write a program that prints out the decimal equivalents of 1/2, 1/3, 1/4, . . . , 1/10
2 | for i in range (2,11) :
3 | num = 1/i
4 | print(f"1/{i} = {num:.2f}")
--------------------------------------------------------------------------------
/Python lab/program04-a.py:
--------------------------------------------------------------------------------
1 | # Write a Program to demonstrate list and tuple in python.
2 | list = [1,2,2,3]
3 | list.append(4)
4 | list.remove(2)
5 | print("Values in list are : " ,list)
6 | tuple = (1,2,3)
7 | print("First element of the tuple is ",tuple[0])
8 | print("Values in tuple are : " , tuple)
--------------------------------------------------------------------------------
/Python lab/program04-b.py:
--------------------------------------------------------------------------------
1 | # Aim : Write a program using a for loop that loops over a sequence.
2 | s = (1,2,3,4,5)
3 | for it in s:
4 | print(it)
--------------------------------------------------------------------------------
/Python lab/program04-c.py:
--------------------------------------------------------------------------------
1 | # Aim : Write a program using a while loop that asks the user for a number, and prints a countdown from that number to zero.
2 | num = int(input("Enter the number for the countdown "))
3 | while(num>=0):
4 | print(num)
5 | num -=1
--------------------------------------------------------------------------------
/Python lab/program05-a.py:
--------------------------------------------------------------------------------
1 | # Aim : Find the sum of all the primes below two million
2 | sum = 0
3 | for i in range (2,2000000):
4 | is_prime = True
5 | for j in range (2,int((i**0.5))+1):
6 | if(i%j==0):
7 | is_prime = False
8 | break
9 | if(is_prime):
10 | sum = sum + i
11 | print("sum of all the primes below two million ",sum)
12 |
--------------------------------------------------------------------------------
/Python lab/program05-b.py:
--------------------------------------------------------------------------------
1 | # Aim : By considering the terms in the Fibonacci sequence whose values do not exceed four million, WAP to find the sum of the even-valued terms.
2 | a,b = 0,1
3 | sum = 0
4 | while(b<=4000000):
5 | if(b%2==0):
6 | sum += b
7 | c = a+ b
8 | a = b
9 | b = c
10 | print("Sum of even sequence below four million in fibonacci sequence " , sum )
--------------------------------------------------------------------------------
/Python lab/program06-a.py:
--------------------------------------------------------------------------------
1 | # AIM : Write a program to count the numbers of characters in the string and store them in a dictionary data structure
2 | string = input("Enter a String : ")
3 | char_count = {}
4 | for char in string:
5 | if char in char_count:
6 | char_count[char]+=1
7 | else:
8 | char_count[char] = 1
9 | print("count of the characters for the string " , char_count)
--------------------------------------------------------------------------------
/Python lab/program06-b.py:
--------------------------------------------------------------------------------
1 | # AIM : Write a program to use split and join methods in the string and trace a birthday of a person with a dictionary data structure
2 | b_day = input ("Enter your birth day (dd mm yy) : ")
3 | string = b_day.split()
4 | dict = {
5 | "date": string[0],
6 | "month" : string[1],
7 | "year" : string[2]
8 | }
9 |
10 | it = []
11 | for key , value in dict.items():
12 | it = it + [key +" " + value]
13 | res = ", ".join(it)
14 |
15 | print(res)
16 |
--------------------------------------------------------------------------------
/Python lab/program07.py:
--------------------------------------------------------------------------------
1 | # Write a program to count frequency of characters in a given file. Can you use character frequency to tell whether the given file is a Python program file, C program file or a text file?
2 |
3 | char_freq = {}
4 |
5 |
6 | filepath = input("Enter file path: ")
7 |
8 | with open(filepath, 'r') as file:
9 | for line in file:
10 | for char in line:
11 | if char in char_freq: char_freq[char] += 1
12 | else: char_freq[char] = 1
13 |
14 | for ch, cnt in char_freq.items():
15 | print(ch, ":", cnt)
16 |
17 | python_keywords = ['def', 'import', 'self', 'print', 'and', 'class']
18 | c_keywords = ['#include', 'int', 'void', 'printf', 'scanf', 'main']
19 |
20 | with open(filepath, 'r') as file:
21 | content = file.read().lower()
22 |
23 |
24 | python_count = sum(1 for word in python_keywords if word in content)
25 | c_count = sum(1 for word in c_keywords if word in content)
26 | if python_count > c_count :
27 | print("It is a Python file")
28 | elif c_count > python_count : print("It is a C file")
29 | else: print("it is a text file")
--------------------------------------------------------------------------------
/Python lab/program08-a.py:
--------------------------------------------------------------------------------
1 | filepath = input("Enter file path: ")
2 |
3 | with open(filepath, 'r') as file:
4 | for line in file:
5 | rev_line = line.rstrip()[::-1]
6 | print("original : " + line.rstrip())
7 | print("reverse : "+ rev_line)
--------------------------------------------------------------------------------
/Python lab/program08-b.py:
--------------------------------------------------------------------------------
1 | filepath = input("Enter file path: ")
2 |
3 |
4 | char_count = 0
5 | word_count = 0
6 | line_count = 0
7 |
8 |
9 | with open(filepath, 'r' ) as file:
10 | for line in file:
11 | line_count += 1
12 | char_count += len(line)
13 | word_count += len(line.split())
14 |
15 |
16 | print("Number of lines :", line_count)
17 | print("Number of words :", word_count)
18 | print("Number of characters:", char_count)
19 |
--------------------------------------------------------------------------------
/Python lab/program09-a.py:
--------------------------------------------------------------------------------
1 | # Write a function nearly equal to test whether two strings are nearly equal. Two strings a andb are nearly equal when a can be generated by a single mutation on.
2 | def str_equal(str1, str2):
3 | if abs(len(str1) - len(str2)) > 1:
4 | return False
5 |
6 | i = j = 0
7 | count = 0
8 |
9 | while i < len(str1) and j < len(str2):
10 | if str1[i] != str2[j]:
11 | count += 1
12 | if count > 1:
13 | return False
14 | if len(str1) == len(str2):
15 | i += 1
16 | j += 1
17 | elif len(str1) > len(str2):
18 | i += 1
19 | else:
20 | j += 1
21 | else:
22 | i += 1
23 | j += 1
24 |
25 |
26 |
27 | return count <= 1
28 |
29 | str1 = input("Enter first string: ")
30 | str2 = input("Enter second string: ")
31 |
32 | if str_equal(str1, str2):
33 | print("Strings are nearly equal.")
34 | else:
35 | print("Strings are not equal.")
36 |
--------------------------------------------------------------------------------
/Python lab/program09-b.py:
--------------------------------------------------------------------------------
1 | # Write function to compute gcd, lcm of two numbers. Each function shouldn’t exceed one line.
2 | import math
3 | gcd = lambda a, b: math.gcd(a, b)
4 | lcm = lambda a, b: abs(a * b) // math.gcd(a, b)
5 | a = int(input("Enter first number: "))
6 | b = int(input("Enter second number: "))
7 | print("GCD of", a, "and", b, "is:", gcd(a, b))
8 | print("LCM of", a, "and", b, "is:", lcm(a, b))
9 |
--------------------------------------------------------------------------------
/Python lab/program10-a.py:
--------------------------------------------------------------------------------
1 | # Write a program to implement Merge sort.
2 | def merge_sort(arr):
3 | if len(arr) <= 1:
4 | return arr
5 | mid = len(arr) // 2
6 | left_half = merge_sort(arr[:mid])
7 | right_half = merge_sort(arr[mid:])
8 | return merge(left_half, right_half)
9 |
10 |
11 | def merge(left, right):
12 | res = []
13 | i = j = 0
14 | while i < len(left) and j < len(right):
15 | if left[i] < right[j]:
16 | res.append(left[i])
17 | i += 1
18 | else:
19 | res.append(right[j])
20 | j += 1
21 | res.extend(left[i:])
22 | res.extend(right[j:])
23 | return res
24 | n = int (input("Enter number of elements: "))
25 | arr = []
26 | print("Enter elements:")
27 | for i in range(n):
28 | arr.append(int(input()))
29 | print("Unsorted array:", arr)
30 | arr = merge_sort(arr)
31 | print("Sorted array:", arr)
--------------------------------------------------------------------------------
/Python lab/program10-b.py:
--------------------------------------------------------------------------------
1 | #Write a program to implement Selection sort, Insertion sort
2 | def selection_sort(arr):
3 | n = len(arr)
4 | for i in range (n):
5 | min = i
6 | for j in range (i +1 , n):
7 | if arr[j] < arr[min]:
8 | min = j
9 | arr[i],arr[min] = arr[min],arr[i]
10 | return arr
11 | def insertion_sort(arr):
12 | n = len(arr)
13 | for i in range (1,n):
14 | key = arr[i]
15 | j = i-1
16 | while j>=0 and arr[j]> key:
17 | arr[j+1] = arr[j]
18 | j -= 1
19 | arr[j+1] = key
20 | return arr
21 | n = int(input("Enter number of elements "))
22 | print("Enter the elements of the array ")
23 | arr = []
24 | for i in range (n):
25 | arr.append(int(input()))
26 | print("Unsorted array " , arr)
27 | s_arr = selection_sort(arr)
28 | print("array after selction sort " , s_arr)
29 | i_arr = insertion_sort(arr)
30 | print("array after selction sort " , i_arr)
--------------------------------------------------------------------------------
/Python lab/pythonlab.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Niraj-Ramnani/Lab-Record-6th-sem/333ed742d31d32b8c3e384d6dd4875e6c204ee81/Python lab/pythonlab.pdf
--------------------------------------------------------------------------------
/Python lab/test.txt:
--------------------------------------------------------------------------------
1 | he is a boy
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | # Lab Record - 6th Semester (ACEIT)
3 |
4 | Welcome to the **6th Semester Lab Record** repository! This repository contains all the lab records and assignments for the 6th semester of the **ACEIT (Arya College Of Engineering and I.T.)** program.
5 |
6 | ## 🧑💻 About This Repository
7 |
8 | This repository serves as a collection of all the work, code, and lab assignments I’ve completed during the 6th semester. Each lab corresponds to a particular subject, and you can find detailed reports, code files, and explanations for each experiment. The aim is to keep track of my progress, share my work with peers, and build a strong foundation for the next steps in my academic and professional journey.
9 |
10 |
11 | Feel free to explore the folders, dive into the details, and get insights into my approach to problem-solving, coding, and practical implementations.
12 |
13 | ## 🌐 Connect with Me
14 |
15 | I’d love to connect with you! Whether you’re a fellow student, professional, or enthusiast, feel free to reach out to me on **LinkedIn**:
16 |
17 | [Connect with Niraj Ramnani on LinkedIn](https://www.linkedin.com/in/niraj-ramnani/)
18 |
19 | ## 🚀 Future Plans
20 |
21 | This repository is constantly evolving, and I plan to continue updating it with:
22 |
23 | - Additional lab records
24 | - Personal projects related to ML, and programming
25 | - Research and academic papers
26 | - Code snippets and tutorials
27 |
28 | Stay tuned for more! 👨💻
29 |
30 | ## 📍 License
31 |
32 | This repository is licensed under the **MIT License**. Feel free to use the code and content for educational purposes, but please give appropriate credit.
33 |
34 | ---
35 |
36 |
--------------------------------------------------------------------------------