M0 13 Linear Regression Pendulumn
M0 13 Linear Regression Pendulumn
M0 13 Linear Regression Pendulumn
{"name":"M0_13_Linear_Regression_Pendulumn.ipynb","provenance":
[],"collapsed_sections":[]},"kernelspec":{"name":"python3","display_name":"Python
3"},"accelerator":"GPU"},"cells":[{"cell_type":"markdown","metadata":
{"id":"tao2w0W4IwEO","colab_type":"text"},"source":["# Advanced Certification in
AIML\n","## A Program by IIIT-H and TalentSprint\n","\n"]},
{"cell_type":"markdown","metadata":
{"id":"KH3dYFZzzyJ6","colab_type":"text"},"source":["## Learning Objectives"]},
{"cell_type":"markdown","metadata":
{"id":"XLweV3uoz1qQ","colab_type":"text"},"source":["At the end of the experiment,
you will be able to :\n","\n","* Understand Linear Regression"]},
{"cell_type":"markdown","metadata":
{"id":"Nh70dVHx0G_B","colab_type":"text"},"source":["## Dataset"]},
{"cell_type":"markdown","metadata":
{"id":"0AUjpyII06yk","colab_type":"text"},"source":["### Description"]},
{"cell_type":"markdown","metadata":{"id":"y-
GMJTRb0Iyy","colab_type":"text"},"source":["The dataset consists of two columns and
89 rows. Each column represents a characteristic of a simple pendulum i.e **l**
(length) and **t** (time period). The dataset describes the relationship between
the **l** and **t** which is $𝐿∝𝑇^2$."]},{"cell_type":"markdown","metadata":
{"id":"a3fJnELiIwES","colab_type":"text"},"source":["### Expected time : 60
mins"]},{"cell_type":"markdown","metadata":
{"id":"j1b476ZK6U74","colab_type":"text"},"source":["#### Setup Steps"]},
{"cell_type":"code","metadata":{"id":"AQylO_MO6SUK","colab_type":"code","colab":
{}},"source":["#@title Please enter your registration id to start: (e.g.
P181900101) { run: \"auto\", display-mode: \"form\" }\n","Id = \"\" #@param
{type:\"string\"}\n"],"execution_count":0,"outputs":[]},
{"cell_type":"code","metadata":{"id":"GnQgepji6Zaa","colab_type":"code","colab":
{}},"source":["#@title Please enter your password (normally your phone number) to
continue: { run: \"auto\", display-mode: \"form\" }\n","password = \"\" #@param
{type:\"string\"}\n"],"execution_count":0,"outputs":[]},
{"cell_type":"code","metadata":
{"id":"OfGUUFWT5FXW","colab_type":"code","cellView":"form","colab":{}},"source":
["#@title Run this cell to complete the setup for this Notebook\n","from IPython
import get_ipython\n","\n","ipython = get_ipython()\n"," \n","notebook=\"M0_014\"
#name of the notebook\n","Answer = \"Ungraded\"\n","def setup():\n","#
ipython.magic(\"sx pip3 install torch\")\n"," ipython.magic(\"sx wget
https://www.dropbox.com/s/vu7xkf6j3v9p5np/AIML_DS_REGR01_SIMPLEPENDULUMOSCILLATIOND
ATA.txt.zip?dl=1\")\n"," ipython.magic(\"sx unzip
AIML_DS_REGR01_SIMPLEPENDULUMOSCILLATIONDATA.txt.zip?dl=1\")\n"," # print
(\"Setup completed successfully\")\n"," from IPython.display import HTML,
display\n"," display(HTML('<script
src=\"https://dashboard.talentsprint.com/aiml/record_ip.html?
traineeId={0}&recordId={1}\"></script>'.format(getId(),submission_id)))\n","
print(\"Setup completed successfully\")\n"," return\n","\n","def
submit_notebook():\n"," \n"," ipython.magic(\"notebook -e \"+ notebook
+ \".ipynb\")\n"," \n"," import requests, json, base64, datetime\n","\n","
url = \"https://dashboard.talentsprint.com/xp/app/save_notebook_attempts\"\n","
if not submission_id:\n"," data = {\"id\" : getId(), \"notebook\" :
notebook, \"mobile\" : getPassword()}\n"," r = requests.post(url, data =
data)\n"," r = json.loads(r.text)\n","\n"," if r[\"status\"]
== \"Success\":\n"," return r[\"record_id\"]\n"," elif \"err\" in r:
\n"," print(r[\"err\"])\n"," return None \n"," else:\n","
print (\"Something is wrong, the notebook will not be submitted for grading\")\n","
return None\n","\n"," elif getAnswer() and getComplexity() and getAdditional()
and getConcepts():\n"," f = open(notebook + \".ipynb\", \"rb\")\n","
file_hash = base64.b64encode(f.read())\n","\n"," data = {\"complexity\" :
Complexity, \"additional\" :Additional, \n"," \"concepts\" : Concepts,
\"record_id\" : submission_id, \n"," \"answer\" : Answer, \"id\" : Id,
\"file_hash\" : file_hash,\n"," \"notebook\" : notebook}\n","\n","
r = requests.post(url, data = data)\n"," r = json.loads(r.text)\n","
print(\"Your submission is successful.\")\n"," print(\"Ref Id:\",
submission_id)\n"," print(\"Date of submission: \", r[\"date\"])\n","
print(\"Time of submission: \", r[\"time\"])\n"," print(\"View your
submissions: https://iiith-aiml.talentsprint.com/notebook_submissions\")\n","
#print(\"For any queries/discrepancies, please connect with mentors through the
chat icon in LMS dashboard.\")\n"," return submission_id\n"," else:
submission_id\n","\n","\n","\n","def getAdditional():\n"," try:\n"," if
Additional: return Additional \n"," else: raise NameError('')\n"," except
NameError:\n"," print (\"Please answer Additional Question\")\n"," return
None\n","\n","def getComplexity():\n"," try:\n"," return Complexity\n","
except NameError:\n"," print (\"Please answer Complexity Question\")\n","
return None\n"," \n","def getConcepts():\n"," try:\n"," return Concepts\n","
except NameError:\n"," print (\"Please answer Concepts Question\")\n","
return None\n","\n","def getAnswer():\n"," try:\n"," return Answer\n"," except
NameError:\n"," print (\"Please answer Question\")\n"," return
None\n","\n","def getId():\n"," try: \n"," return Id if Id else None\n","
except NameError:\n"," return None\n","\n","def getPassword():\n"," try:\n","
return password if password else None\n"," except NameError:\n"," return
None\n","\n","submission_id = None\n","### Setup \n","if getPassword() and
getId():\n"," submission_id = submit_notebook()\n"," if submission_id:\n","
setup()\n"," \n"," \n","else:\n"," print (\"Please complete Id and Password
cells before running setup\")\n","\n"],"execution_count":0,"outputs":[]},
{"cell_type":"markdown","metadata":
{"id":"_naOegVA5XUH","colab_type":"text"},"source":["#### Importing required
Packages"]},{"cell_type":"code","metadata":
{"id":"HxcZUqq5IwEY","colab_type":"code","colab":{}},"source":["import pandas as
pd\n","import matplotlib.pyplot as plt\n","from sklearn import
linear_model\n","from sklearn.metrics import mean_squared_error,
r2_score"],"execution_count":0,"outputs":[]},{"cell_type":"markdown","metadata":
{"id":"m80GNtm45c14","colab_type":"text"},"source":["#### Loading the data"]},
{"cell_type":"code","metadata":{"id":"5Ttnpu44IwEb","colab_type":"code","colab":
{}},"source":["data =
pd.read_csv(\"AIML_DS_REGR01_SIMPLEPENDULUMOSCILLATIONDATA.txt\", sep=\" \",
header=None, names=['l', 't'])"],"execution_count":0,"outputs":[]},
{"cell_type":"markdown","metadata":
{"id":"OiuP5H435gqY","colab_type":"text"},"source":["To understand the design of
the data, let us print first five rows and last five rows from the dataset"]},
{"cell_type":"code","metadata":{"id":"bC9DOfG55vs6","colab_type":"code","colab":
{}},"source":["# First five rows from the
dataset\n","data.head()"],"execution_count":0,"outputs":[]},
{"cell_type":"code","metadata":{"id":"EAlmOwER51Nk","colab_type":"code","colab":
{}},"source":["# Last five rows from the
dataset\n","data.tail()"],"execution_count":0,"outputs":[]},
{"cell_type":"code","metadata":{"id":"ZGdRFp1LIwEd","colab_type":"code","colab":
{}},"source":["# Storing the l and t column values in two variables\n","l =
data['l'].values\n","t = data['t'].values"],"execution_count":0,"outputs":[]},
{"cell_type":"code","metadata":{"id":"848k50_e66Ed","colab_type":"code","colab":
{}},"source":["# Plotting l vs t\n","plt.figure(figsize=(12,10))\n","plt.plot(l,
t)\n","plt.show()"],"execution_count":0,"outputs":[]},
{"cell_type":"markdown","metadata":
{"id":"9xkPTlv_7AIj","colab_type":"text"},"source":["The above graph does not look
like a straightline which was obtained by connecting the points in the order of
their occurrence.; it may be easier to see if we only plot the points. "]},
{"cell_type":"code","metadata":{"id":"MjumQx9h7CMt","colab_type":"code","colab":
{}},"source":["plt.figure(figsize=(12, 10))\n","plt.plot(l, t,
'.k')\n","plt.show()"],"execution_count":0,"outputs":[]},
{"cell_type":"markdown","metadata":
{"id":"08SQLMPn7K6X","colab_type":"text"},"source":["The above graph is still not a
straightline. As we know from the domain information that $l∝t^2$. \n","\n","Let
us plot $ t^2 $ vs $ l $ instead of $l$ vs $t$:"]},
{"cell_type":"code","metadata":{"id":"zz9-nmyd705n","colab_type":"code","colab":
{}},"source":["tsq = t * t"],"execution_count":0,"outputs":[]},
{"cell_type":"code","metadata":{"id":"VRiR324x744V","colab_type":"code","colab":
{}},"source":["plt.figure(figsize=(16,10))\n","#plt.plot(x, Y)\n","plt.plot(l, tsq,
'.k')\n","plt.show()"],"execution_count":0,"outputs":[]},
{"cell_type":"markdown","metadata":
{"id":"w1obAywp6Td0","colab_type":"text"},"source":["**Note :** When using the
Sklearn libraries 2D or above inputs are expected. Hence reshaping $l$ and $t$ to a
2-D array.\n","\n","To know more about reshaping, you can refer to the below
link
:\n","\n","https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html"
]},{"cell_type":"code","metadata":{"id":"ClBhoZXI5LEV","colab_type":"code","colab":
{}},"source":["l = l.reshape(-1,1)"],"execution_count":0,"outputs":[]},
{"cell_type":"code","metadata":{"id":"LAhM6vsh5R43","colab_type":"code","colab":
{}},"source":["tsq = tsq.reshape(-1,1)"],"execution_count":0,"outputs":[]},
{"cell_type":"code","metadata":{"id":"OAfiS19k4ht0","colab_type":"code","colab":
{}},"source":["# Create linear regression object\n","regr =
linear_model.LinearRegression()\n","\n","# Training the model using the training
set\n","regr.fit(l, tsq)\n"],"execution_count":0,"outputs":[]},
{"cell_type":"code","metadata":{"id":"1JZ0WPEI5x-z","colab_type":"code","colab":
{}},"source":["pred_tsq
= regr.predict(l)"],"execution_count":0,"outputs":[]},
{"cell_type":"code","metadata":{"id":"zP_BL1vt5eZy","colab_type":"code","colab":
{}},"source":["# Plotting a scatter representing l vs tsq\n","plt.scatter(l, tsq,
color='black')\n","\n","# Plotting the line predicted using linear regression
model\n","plt.plot(l, pred_tsq, color='blue',
linewidth=3)\n","\n","plt.show()"],"execution_count":0,"outputs":[]},
{"cell_type":"markdown","metadata":
{"id":"Go5quY3c66w7","colab_type":"text"},"source":["### Please answer the
questions below to complete the experiment:"]},{"cell_type":"code","metadata":
{"id":"VbCaYb_01ciu","colab_type":"code","colab":{}},"source":["#@title How was the
experiment? { run: \"auto\", form-width: \"500px\", display-
mode: \"form\" }\n","Complexity = \"\" #@param [\"Too Simple, I am wasting
time\", \"Good, But Not Challenging for me\", \"Good and Challenging for
me\", \"Was Tough, but I did it\", \"Too Difficult for
me\"]\n"],"execution_count":0,"outputs":[]},{"cell_type":"code","metadata":
{"id":"OGMgioUMfp3F","colab_type":"code","colab":{}},"source":["#@title If it was
very easy, what more you would have liked to have been added? If it was very
difficult, what would you have liked to have been removed? { run: \"auto\",
display-mode: \"form\" }\n","Additional = \"\" #@param
{type:\"string\"}"],"execution_count":0,"outputs":[]},
{"cell_type":"code","metadata":{"id":"VnHug4dDfr1F","colab_type":"code","colab":
{}},"source":["#@title Can you identify the concepts from the lecture which this
experiment covered? { run: \"auto\", vertical-output: true, display-
mode: \"form\" }\n","Concepts = \" \" #@param
[\"Yes\", \"No\"]"],"execution_count":0,"outputs":[]},
{"cell_type":"code","metadata":{"id":"D1Hc_h7hioq3","colab_type":"code","colab":
{}},"source":["#@title Text and image description/explanation and code comments
within the experiment: { run: \"auto\", vertical-output: true, display-
mode: \"form\" }\n","Comments = \"\" #@param [\"Very Useful\", \"Somewhat Useful\",
\"Not Useful\", \"Didn't use\"]\n"],"execution_count":0,"outputs":[]},
{"cell_type":"code","metadata":{"id":"U2LbHakuiozE","colab_type":"code","colab":
{}},"source":["#@title In class Mentor Support: { run: \"auto\", vertical-output:
true, display-mode: \"form\" }\n","Inclass_support = \" \" #@param [\"Very
Useful\", \"Somewhat Useful\", \"Not Useful\", \"Didn't
use\"]\n"],"execution_count":0,"outputs":[]},{"cell_type":"code","metadata":
{"id":"DkvtwnHPio7z","colab_type":"code","colab":{}},"source":["#@title Online
Mentor Support: { run: \"auto\", vertical-output: true, display-
mode: \"form\" }\n","Online_support = \"\" #@param [\"Very Useful\", \"Somewhat
Useful\", \"Not Useful\", \"Didn't use\"]\n"],"execution_count":0,"outputs":[]},
{"cell_type":"code","metadata":
{"id":"ai38mALcft7o","colab_type":"code","cellView":"form","colab":{}},"source":
["#@title Run this cell to submit your notebook { vertical-output:
true }\n","try:\n"," if submission_id:\n"," return_id =
submit_notebook()\n"," if return_id : submission_id =return_id\n","
else:\n"," print(\"Please complete the setup first.\")\n","except
NameError:\n"," print (\"Please complete the setup
first.\")"],"execution_count":0,"outputs":[]}]}