Advertisement
MK7265

Untitled

Mar 8th, 2023 (edited)
275
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 18.32 KB | None | 0 0
  1. #Practical 1 (Write a program in python to display the execution of Lists - Demo the use of append(), insert(),extend(), remove(), pop().)
  2.  
  3. A=[1,23,"Learning","Python"]
  4. print("All Elements in the list : ", A)
  5.  
  6. #Append Function
  7. A.append(6)
  8. print("Appended List : ",A)
  9.  
  10. #Insert Function
  11. A.insert(2,"Practical 1")
  12. print("Inserted Element : ",A)
  13.  
  14. #Remove Function
  15. A.remove(23)
  16. print("Updated list after removal : ",A)
  17.  
  18. #Pop Function (Delete value from specified index)
  19. A.pop(0)
  20. print("Updated list after pop : ",A)
  21.  
  22. #Extend Function
  23. B=["Class","Sybsc A"]
  24. A.extend(B)
  25. print("Extended list : ",A)
  26.  
  27.  
  28.  
  29. #Practical 2 (Write a program in python to display the execution of Tuples. Create a student attendance table to demo the use of tuples.)
  30.  
  31. tup=()
  32. start=1
  33. while(start):
  34.   name=input("Enter your Name : ")
  35.   rollno=input("Enter your Roll No. : ")
  36.   lec_attended=input("Enter Total Lectures Attended : ")
  37.   student=("Name : "+name,"Roll No. : "+rollno,"Lec Attented : "+lec_attended)
  38.   tup+=student
  39.   req=int(input("To continue press 1,To view details press 2 : "))
  40.   if(req==1):
  41.     start=1
  42.   else:
  43.     print(tup)
  44.     start=0
  45.  
  46.  
  47. #Practical 3.1 (Write a program in python to display the execution of Sets.)
  48. print("Mohit.K 1129\n")
  49. set1=set()
  50. set2=set()
  51.  
  52. #To add values in set1 in the range of 5
  53. for i in range(5):
  54.   set1.add(i)
  55. print("set1 : ",set1)
  56.  
  57. #To add(insert) elements in set2 in range between 3 to 9
  58. for i in range(3,9):
  59.   set2.add(i)
  60. print("set2 : ",set2)
  61.  
  62. # Intersection of set1 and set2
  63. set3 = set1.intersection(set2)
  64. print("\nIntersection using intersection() function of set1 & set2")
  65. print("set3 : ",set3)
  66.  
  67. # Intersection using "&" operator
  68. set4 = set1 & set2
  69. print("\nIntersection using '&' operator")
  70. print("set 4 : ",set4)
  71.  
  72. #Union Function
  73. print("\nUnion of set1 & set2")
  74. set5 = set1.union(set2)
  75. print("set5 : ",set5)
  76.  
  77. #Differnece between set1 & set2
  78. print("\nDiffernce between set1 & set2")
  79. set6 = set1.difference(set2)
  80. print("set6 : ",set6)
  81.  
  82. #Difference using "-(minus)" operator
  83. print("\nDiffference using - operator")
  84. set7 = set1-set2
  85. print("set7 : ",set7)
  86.  
  87. #Clearing the values
  88. print("\nClearing set1 & set2")
  89. set1.clear()
  90. print(set1)
  91. set2.clear()
  92. print(set2)
  93.    
  94.    
  95.    
  96. #Practical 3.2 (Demo the use of sets to display employee records of a company.)
  97.  
  98. start=1
  99. employeedetails = {"""  """}
  100. while(start):
  101.     empid = input("Enter Employee ID : ")
  102.     name = input("Enter Employee Name : ")
  103.     joiningdate = input("Enter joining date in dd/mm/yy formaat : ")
  104.     dept = input("Enter Hiring department : ")
  105.     annualsalary = input("Enter annual salary : ")
  106.     employee = ("Empid  "+empid,"Name "+name, "Joing Date  "+joiningdate, " Department "+dept, "Annual salary " +annualsalary)
  107.     print(employee)
  108.     employeedetails.add(employee)
  109.     req = int(input("Enter 1 to add more employee details else Enter 2 to display the info"))
  110.     if(req == 1):
  111.         start = 1
  112.     else:
  113.         print("All Employee details are \n")
  114.         print(employeedetails)
  115.         start = 0
  116.        
  117.        
  118.        
  119. #Practical 4 (Write a program in python to display the execution of Dictionary. Create a dictionary set of and find the employee having highest and lowest salary.)
  120.  
  121.  
  122. dict1 = {"Name" : "Mohit","Age" : "20","Location" : "Mumbai"}
  123. dict2 = {"Height" : "5'11"}
  124. print("dict1 : ",dict1)
  125. print("dict2 : ",dict2)
  126.  
  127. #To print keys
  128. print("\nPrinting Keys of dict1")
  129. print(dict1.keys())
  130.  
  131. #To print values of key-value pair
  132. print("\nPrinting values of dict1")
  133. print(dict1.values())
  134.  
  135. #To update data of values
  136. print("\n Updated Height of dict2")
  137. dict2["Height"]="6'0"
  138. print(dict2)
  139.  
  140. #To append dict2 in dict1
  141. print("\nAppending dict2 in dict1")
  142. dict1.update(dict2)
  143. print(dict1)
  144.  
  145. #To remove any data from dictonary
  146. print("\nRemoved Location")
  147. dict1.pop("Location")
  148. print(dict1)
  149.  
  150. #To print min and max salary of an employee
  151. salary = {"Mohit" : 850000,"Hardik" : 780000,"Kaushik" : 650000}
  152.  
  153. #To print Highest & Lowest Salary of an employee
  154. print("\nEmployee with Highest Salary : ",max(salary,key=salary.get))
  155. max_sal = max(salary,key=salary.get)
  156. print(salary.get(max_sal))
  157. print("\nEmployee with Lowest Salary : ",min(salary,key=salary.get))
  158. min_sal = min(salary,key=salary.get)
  159. print(salary.get(min_sal))
  160.    
  161.    
  162.    
  163. #Practical 5 (Write a program in python to display the execution of Strings. Perform concat, iteration,membership and methods like upper(), join(), split(), find(), replace().)
  164.  
  165.  
  166.  
  167. s0 = "Orange"
  168. s1 = "Hello this is python language"
  169. s2 = "Lets learn about strings in python"
  170. #CONCATENATING --> Adding two strings together
  171. print("----THIS IS CONCATENATION----")
  172. print(s1 + s2)       #this is simply concatenating using + operator
  173. print(s1 + ',' + s2) #to make it look good
  174. #ITERAING --> Going through the string character by character
  175. print("----THIS IS ITERATING----")
  176. for i in s0:
  177.   print(i)
  178. #upper() --> It will turn string to uppercase
  179. print("----UPPERCASE----")
  180. print(s0.upper())
  181. #lower() --> It will turn string to lowercase
  182. print("----LOWERCASE----")
  183. print(s0.lower())
  184. #len() --> To find length of string
  185. print("----LENGTH----")
  186. print("Length of s1 : ",len(s1))
  187. #join() --> It will join the other string
  188. str1 = '->'
  189. str2 = 'Hello'
  190. print("----JOINING----")
  191. print(str1.join(str2))
  192. string = 'Mohit'
  193. print( '' + '.'.join(string))
  194. #split() --> It will split the string word by word
  195. print("----SPLITING----")
  196. print(s1.split())
  197. print(s1.split(" ",2))
  198. #find() --> It will find the character or word and return its index
  199. print("----FINDING----")
  200. print(s1.find('python'))
  201. #replace() --> It will replace string with new string
  202. print("----REPLACING learn----")
  203. print(s2.replace('learn','study'))
  204.  
  205.  
  206.  
  207.  
  208. #Practical 6 (Compute a program in python using Matploitlib usage.)
  209.  
  210. from google.colab import files
  211. import pandas as pd
  212. import numpy as np
  213. import matplotlib.pyplot as plt
  214. df = files.upload()
  215. df = pd.read_csv(r'Pokemon.csv') #usage of pandas
  216. df.head()
  217. df.drop('#', inplace=True, axis=1)
  218. df.head()
  219. df.shape #usage of numpy
  220. df.info()
  221. newdf = pd.DataFrame(df, columns=['Name','HP'])
  222. newdf.head()
  223. newdf.shape
  224. plt.rcParams["figure.figsize"] = (10, 4)
  225. plt.bar(newdf['Name'].head(), newdf['HP'].head())
  226. plt.show()
  227.    
  228.  
  229.  # Line Plot
  230.  
  231. import numpy as np
  232. import matplotlib.pyplot as plt
  233.  
  234. x = np.arange(11)
  235. print(x)
  236. y = 2*x
  237. print(y)
  238. plt.plot(x,y)
  239. plt.title("Line Plot")
  240. plt.xlabel("X Label")
  241. plt.ylabel("Y Label")
  242.  
  243. # Adding two line in same plot
  244.  
  245. import numpy as np
  246. import matplotlib.pyplot as plt
  247.  
  248. x = np.arange(11)
  249. y1 = 2*x
  250. y2 = 3*x
  251.  
  252. print("\n","x  : ",x,"\n\n","y1 : ",y1,"\n","y2 : ",y2)
  253. plt.plot(x,y1,color="g")
  254. plt.plot(x,y2,color="r")
  255. plt.title("Two Line Plot")
  256. plt.xlabel("X Label")
  257. plt.ylabel("Y Label")
  258. plt.grid("True")
  259.  
  260. # Adding multiple plot in same screen
  261.  
  262. import numpy as np
  263. import matplotlib.pyplot as plt
  264.  
  265. x = np.arange(11)
  266. y1 = 2*x
  267. y2 = 3*x
  268.  
  269. plt.subplot(3,3,1)  #Subplot syntax (row,col,index of graph)
  270. plt.plot(x,y1,color='g',linestyle=':')
  271. plt.subplot(3,3,7)
  272. plt.plot(x,y2,color='b')
  273.  
  274. #Bar Plot
  275.  
  276. import numpy as np
  277. import matplotlib.pyplot as plt
  278.  
  279. #define a dictionary for student marks
  280. student = {"Bob":87,"Matt":56,"Arpit":18}
  281. names = list(student.keys())
  282. marks = list(student.values())
  283. plt.bar(names,marks)  #For Horizontal bar graph type "plt.barh(names,marks)"
  284. plt.title("Students Mark Graph")
  285. plt.xlabel("Student Names")
  286. plt.ylabel("Student Marks")
  287.  
  288.  
  289. #Scatter Plot
  290.  
  291. import numpy as np
  292. import matplotlib.pyplot as plt
  293.  
  294. x = np.arange(1,21)
  295. y = np.arange(6,26)
  296. y2 = np.arange(10,30)
  297.  
  298. plt.scatter(x,y,marker="*",c="g",s=100)  #marker means can add any symbol to show on graph,c=color,s=size
  299. plt.scatter(x,y2,marker="^",c="r",s=50)
  300.  
  301. plt.plot()  
  302.  
  303.  
  304. #hist graph
  305. import matplotlib.pyplot as plt
  306. data=[1,2,2,2,3,3,3,3,9,9,4,8,4]
  307. plt.hist(data,color='orange')
  308.  
  309. #pie chart with numbers
  310. import matplotlib.pyplot as plt
  311. fruit=["Apple","Mango","Banana","Guava"]
  312. quantity=[64,66,22,78]
  313. plt.pie(quantity,labels=fruit)
  314.  
  315. # with percentage
  316. import matplotlib.pyplot as plt
  317. quantity=[55,34,22,78,21]
  318. vegetable=["Potatu","Tomatu","Tindi","Lauki","Bindi 12 rupey"]
  319. plt.pie(quantity,labels=vegetable,autopct='%0.1f',colors=['Yellow','Green','Orange','Red','Blue'])
  320. plt.pie([1],colors=['black'],radius=0.4)
  321.  
  322.  
  323.  
  324.  
  325. import matplotlib.pyplot as plt
  326. x = [5,2,9,4,7]
  327. y = [10,6,8,4,2]
  328. plt.xlabel("x value")
  329. plt.ylabel("y value")
  330.  
  331. # Bar Graph
  332. plt.bar(x,y)
  333.  
  334. # Scatter Graph
  335. plt.scatter(x,y,marker="*",c="r",s=100)
  336.  
  337. # Histogram Graph
  338. plt.hist(x,color="green")
  339.  
  340.  
  341. import matplotlib.pyplot as plt
  342. import pandas as pd
  343. import numpy as np
  344. df=pd.DataFrame(np.random.rand(10,5))
  345. Columns = ['A','B','C','D','E']
  346. df.plot.area()
  347. plt.legend(["A","B","C","D","E"])
  348. plt.show()
  349.  
  350.  
  351.  
  352. # Practical 7 (Compute a program in python using Numpy usage.)
  353.  
  354. import numpy as np
  355.  
  356. # 1 Dimensional Array
  357. l = [1,9,8,5,3]
  358. npl = np.array(l)
  359. print("1 Dimensional Array :\n",npl)
  360. print("Matrix : ",npl.shape)
  361. print("Type of Datatype : ",npl.dtype)
  362.  
  363. #Arthimetic Operations
  364. print("Addition       : ",npl+10)
  365. print("Multiplication : ",npl*10)
  366. print("Subtraction    : ",npl-10)
  367. print("Division       : ",npl/10)
  368. print()
  369.  
  370. # 2 Dimensional Array
  371. c = np.array([(1,2,3),(4,5,6)])
  372. print("2 Dimensional Array : \n",c)
  373. print("Matrix : ",c.shape)
  374. print()
  375.  
  376. # 3 Dimensional Array
  377. d = np.array([(1,2,3),(4,5,6),(7,8,9),(10,11,12)])
  378. print("3 Dimensional Array : \n",d)
  379. print("Matrix : ",d.shape)
  380. print()
  381. print("Reshape into (3,4) : \n",d.reshape(3,4))
  382. print()
  383.  
  384. # Horizontal Stack
  385. f = np.array([1,2,3])
  386. g = np.array([4,5,6])
  387. print("Horizontal Stack :\n",np.hstack(f))
  388. print()
  389.  
  390. # Vertical Stack
  391. print("Vertical Stack :\n",np.vstack(g))
  392. print()
  393.  
  394. # Random
  395. normal_array = np.random.normal(5,0.5,10)
  396. print("Random :\n",normal_array)
  397. print("Min : ",np.min(normal_array))
  398. print("Max : ",np.max(normal_array))
  399. print("Median : ",np.median(normal_array))
  400. print("std : ",np.std(normal_array))
  401. print()
  402.  
  403. # Arrange
  404. print("Arrange :")
  405. print(np.arange(1,11))
  406. print(np.arange(1,14,4))
  407. print()
  408.  
  409. # Slicing
  410. e = np.array([[1,2,3],[4,5,6]])
  411. print("Array :\n",e)
  412. print("\nPrinting 0th Index Element :\n",e[0])
  413. print("\nPrinting 1st Index Element :\n",e[1])
  414.  
  415.  
  416.  
  417. #Practical 8 (Compute a program in python using Pandas usage.)
  418. import pandas as pd
  419. S = pd.Series([11, 28, 72, 3, 5, 8])
  420. S
  421. print(S.index)
  422. print(S.values)
  423. print("\n")
  424.  
  425. #defining Series objects with individual indices:
  426. fruits = ['apples', 'oranges', 'cherries', 'pears']
  427. quantities = [20, 33, 52, 10]
  428. fruitdetails = pd.Series(quantities, index=fruits)
  429. print(fruitdetails)
  430. print("\n")
  431.  
  432. #Creating Series Objects from Dictionaries
  433. cities = {"London":    12000,
  434.           "Berlin":    14000,
  435.           "Madrid":    45000,
  436.           "Rome":      78050,
  437.           "Paris":     46520,
  438.           "Vienna":    78963,
  439.           "Bucharest": 15302,
  440.           "Hamburg":   78569,
  441.           "Budapest":  25896,
  442.           "Warsaw":    36584,
  443.           "Barcelona": 45300,
  444.           "Munich":    74500,
  445.           "Milan":     62000}
  446.  
  447. city_series = pd.Series(cities)
  448. print(city_series)
  449. my_cities = ["London", "Paris", "Zurich", "Berlin","Stuttgart", "Hamburg"]
  450. my_city_series = pd.Series(cities,index=my_cities)
  451. print("\n")
  452. print(my_city_series)
  453. print("\n")
  454. print(my_city_series.isnull())
  455. print("\n")
  456. print(my_city_series.notnull())
  457. print("\n")
  458.  
  459. #Filtering out Missing Data
  460. print(my_city_series.dropna())
  461. print("\n")
  462.  
  463. #Filling in Missing Data
  464. print(my_city_series.fillna(0))
  465. print("\n")
  466.  
  467. #Fill some appropriate values for missng Cities
  468. missing_cities = {"Stuttgart":50939, "Zurich":38884}
  469. print(my_city_series.fillna(missing_cities))
  470. print("\n")
  471.  
  472.  
  473. #Since we had nan values integers are converted into float
  474. my_city_series = my_city_series.fillna(0).astype(float)
  475. print(my_city_series)
  476.  
  477.  
  478. import pandas as pd
  479.  
  480. years = range(2014, 2018)
  481. shop1 = pd.Series([2409.14, 2941.01, 3496.83, 3119.55], index=years)
  482. shop2 = pd.Series([1203.45, 3441.62, 3007.83, 3619.53], index=years)
  483. shop3 = pd.Series([3412.12, 3491.16, 3457.19, 1963.10], index=years)
  484. shops_df = pd.concat([shop1, shop2, shop3], axis=1)
  485. shops_df
  486.  
  487. #update column names
  488. cities = ["Mumbai", "Pune", "Nashik"]
  489. shops_df.columns = cities
  490. shops_df
  491. print("\n")
  492.  
  493. # alternative way: give names to series:
  494. shop1.name = "Mumbai"
  495. shop2.name = "Pune"
  496. shop3.name = "Nashik"
  497. print(shops_df)
  498. print("\n")
  499.  
  500. shops_df2 = pd.concat([shop1, shop2, shop3], axis=1)
  501. print(shops_df2)
  502. print("\n")
  503. print(type(shops_df))
  504.  
  505. #DataFrames from Dictionaries
  506. cities2 = {"name": ["London", "Berlin", "Madrid", "Rome",
  507.                    "Paris", "Vienna", "Bucharest", "Hamburg",
  508.                    "Budapest", "Warsaw", "Barcelona",
  509.                    "Munich", "Milan"],
  510.           "population": [8615246, 3562166, 3165235, 2874038,
  511.                          2273305, 1805681, 1803425, 1760433,
  512.                          1754000, 1740119, 1602386, 1493900,
  513.                          1350680],
  514.           "country": ["England", "Germany", "Spain", "Italy",
  515.                       "France", "Austria", "Romania",
  516.                       "Germany", "Hungary", "Poland", "Spain",
  517.                       "Germany", "Italy"]}
  518.  
  519. city_frame = pd.DataFrame(cities2)
  520. city_frame
  521.  
  522. #Retrieving the Column Names
  523. city_frame.columns.values
  524.  
  525. #Providing custom index
  526. ordinals = ["first", "second", "third", "fourth",
  527.             "fifth", "sixth", "seventh", "eigth",
  528.             "ninth", "tenth", "eleventh", "twelvth",
  529.             "thirteenth"]
  530. city_frame = pd.DataFrame(cities2, index=ordinals)
  531. city_frame
  532.  
  533. #Rearranging the Order of Columns
  534. city_frame = pd.DataFrame(cities2,columns=["name","country","population"])
  535. city_frame
  536.  
  537. #making Existing Column as the Index of a DataFrame
  538. city_frame = pd.DataFrame(cities2,columns=["name", "population"],index=cities2["country"])
  539. city_frame
  540.  
  541. #Accessing Rows via Index Values
  542. city_frame = pd.DataFrame(cities2,columns=("name", "population"),index=cities2["country"])
  543. print(city_frame.loc["Germany"])
  544.  
  545. #extracting rows by chosen more than on index labels
  546. print(city_frame.loc[["Germany", "France"]])
  547.  
  548. #select pandas DataFrame rows based on conditions
  549. condition = city_frame.population>2000000
  550. condition
  551. print(city_frame.loc[condition])
  552. condition1 = (city_frame.population>1500000)
  553. condition2 = (city_frame['name'].str.contains("m"))
  554. print(city_frame.loc[condition1 & condition2])
  555.  
  556. #Adding Rows to a DataFrame
  557. milan = ['Milan', 1399860]
  558. city_frame.iloc[-1] = milan
  559. city_frame.loc['Switzerland'] = ['Zurich', 415215]
  560. city_frame
  561.  
  562.  
  563. #Practical 9 (Implement the PCA using Python.)
  564.  
  565. import pandas as pd
  566. import matplotlib.pyplot as plt
  567. from sklearn.datasets import load_breast_cancer
  568. Cancer = load_breast_cancer()
  569. Cancer.keys()
  570. #print(Cancer['DESCR'])
  571. df = pd.DataFrame(Cancer['data'],columns=Cancer['feature_names'])
  572. print(df)
  573. from sklearn.preprocessing import StandardScaler
  574. Scaler = StandardScaler()
  575. Scaler.fit(df)
  576. Scaled_data = Scaler.transform(df)
  577. print(Scaled_data)
  578. from sklearn.decomposition import PCA
  579. pca = PCA(n_components=3)
  580. pca.fit(Scaled_data)
  581. x_pca=pca.transform(Scaled_data)
  582. x_pca.shape
  583. print(x_pca)
  584.  
  585. #2D
  586. plt.figure(figsize=(8,6))
  587. plt.scatter(x_pca[:,0],x_pca[:,1])
  588. c=Cancer['target']
  589. plt.xlabel("1st Principle Component")
  590. plt.ylabel("2nd Principle Component")
  591.  
  592. #3D
  593. from mpl_toolkits.mplot3d import Axes3D
  594. fig = plt.figure(figsize=(10,10))
  595. axis = fig.add_subplot(111,projection='3d')
  596. axis.scatter(x_pca[:,0],x_pca[:,1],x_pca[:,2],c=Cancer['target'],cmap='plasma')
  597. axis.set_xlabel("1st PC",fontsize=10)
  598. axis.set_ylabel("2st PC",fontsize=10)
  599. axis.set_zlabel("3st PC",fontsize=10)
  600.  
  601. #Check Variance Ratio
  602. print(pca.explained_variance_ratio_)
  603.  
  604.  
  605. #Practical 10 (Consider a set of data points and train your model in python. The model should have 80% training data and 20% of test data.)
  606.  
  607. import pandas as pd
  608. from sklearn.datasets import load_iris
  609. from sklearn.model_selection import train_test_split
  610. iris_data = load_iris()
  611. iris_data
  612. iris_data.keys()
  613. df = pd.DataFrame(iris_data.data, columns = iris_data.feature_names)
  614. df
  615. training_data, testing_data = train_test_split(df, test_size=0.2)
  616. print(training_data)
  617. print(testing_data)
  618. print(f"No. of training examples : {training_data.shape[0]}")
  619. print(f"No. of testing examples : {testing_data.shape[0]}")
  620. training_data.head()
  621.  
  622.  
  623.  
  624. #Practical 11 (Implement the Regression algorithm: Linear Regression in python.)
  625. from google.colab import files
  626. import pandas as pd
  627. import matplotlib.pyplot as plt
  628. from sklearn.model_selection import train_test_split
  629. #df = files.upload()
  630. df = pd.read_csv('Salary_Data.csv')
  631. df
  632. x = df.iloc[:,0].values  #input
  633. y = df.iloc[:,1].values  #output
  634. print(x.shape)
  635. print(y.shape)
  636. x = x.reshape(-1,1)
  637. y = y.reshape(-1,1)
  638. print(x.shape)
  639. print(y.shape)
  640. x_train, x_test, y_train, y_test = train_test_split(x,y,test_size=0.2,random_state = 0)
  641. print("x Training:",x_train)
  642. print(x_train.shape)
  643. print("\nx Testing:",x_test)
  644. print(x_test.shape)
  645. print("y Training:",y_train)
  646. print(y_train.shape)
  647. print("\ny Testing:",y_test)
  648. print(y_test.shape)
  649. plt.scatter(x_train,y_train,color = 'r',marker = '+')
  650. plt.xlabel("Years Experience")
  651. plt.ylabel('Salary')
  652. plt.title('Employee Details')
  653. plt.show()
  654. from sklearn.linear_model import LinearRegression
  655. reg = LinearRegression()
  656. reg.fit(x_train,y_train)
  657. reg.coef_
  658. reg.intercept_
  659. y_pred = reg.predict(x_test)
  660. print(y_pred)
  661. print(y_test)
  662. print(y_pred)
  663. print(y_test)
  664. plt.scatter(x_train,y_train,color = 'r',marker = '+')
  665. plt.xlabel("Years Experience")
  666. plt.ylabel('Salary')
  667. plt.plot(x_train,reg.predict(x_train))
  668. plt.title('Employee Details')
  669. plt.show()
  670.  
  671.  
  672.  
  673. import matplotlib.pyplot as plt
  674. import numpy as np
  675. from sklearn import datasets, linear_model
  676. from sklearn.model_selection import train_test_split
  677. boston = datasets.load_boston()
  678. x = boston.data
  679. y = boston.target
  680. x_train, x_test, y_train, y_test = train_test_split(x,y,test_size=0.4,random_state = 0)
  681. reg = linear_model.LinearRegression()
  682. reg.fit(x_train, y_train)
  683. print("Coefficient : ",reg.coef_)
  684. print("Variance Score :",format(reg.score(x_test,y_test)))
  685.  
  686.  
  687. plt.scatter(reg.predict(x_train),reg.predict(x_train) - y_train, color = "red", s =10, label = 'train data')
  688. plt.scatter(reg.predict(x_test),reg.predict(x_test) - y_test, color = "green", s =10, label = 'test data')
  689. plt.hlines(y = 0,xmin = 0,xmax = 50, linewidth = 2)
  690. plt.legend(loc = 'upper right')
  691. plt.title('Residual Errors')
  692. plt.show()
  693.  
  694.  
  695.    
  696.  
  697.    
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement