AIML Record 56
AIML Record 56
AIML Record 56
program:
#area of triangle
import math
a=int(input('Enter 1st side'))
b=int(input('Enter 2nd side'))
c=int(input('Enter 3rd side'))
s=(a+b+c)/2
area=s*(s-a)*(s-b)*(s-c)
area=math.sqrt(area)
56
print('Area of triangle is : ',area)
OUTPUT:
Program:
temp=a
a=b
b=temp
print(a,b)
OUTPUT:
Enter 1st number: 3
Enter 2nd number: 5
5 3
3) program:
#program to convert kilometers into miles
a=int(input("Enter value in Kilometers: "))
b=0.621371*a
FILE HANDLING
File operations
03
1)
program:
#file operations
#reading a file
f=open("sample.txt",'r')
print(f.readline())
f.close()
Output:
In simple terms, coding is the process of giving computers instructions in a language that they understand. Why is it important
to learn to code? Coding is important to learn because it teaches you important skills such as criticalthinking, problem solving
and creativity.
2)
program:
#file operations
#writing on a file
f=open("sample.txt",'a')
56
f.write('This is the new text added in the file')
f.close()
f=open("sample.txt","r")
print(f.read())
03
Output:
In simple terms, coding is the process of giving computers instructions in a
language that they understand. Why is it important to learn to code? Coding
is important to learn because it teaches you important skills such as critical
thinking, problem solving and creativity.It helps in solving the complicated
real life problems.
EXPERIMENT-2
Matplotlib
1.simple ploting and markers
Program:
2.Line Style
56
Program:
import matplotlib.pyplot as plt
03
import numpy as np
ypoints = np.array([3, 8, 1, 10])
plt.plot(ypoints, linestyle = 'dotted')
plt.show()
output:
56
3.Matplotlib labels and title for plot
Program:
import numpy as np
import matplotlib.pyplot as plt
03
x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])
plt.plot(x, y)
plt.title("Sports Watch Data")
plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")
plt.show()
Output:
56
4.Grid and subplot
Program:
import matplotlib.pyplot as plt
03
import numpy as np
#plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(1, 2, 1)
plt.plot(x,y)
#plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(1, 2, 2)
plt.plot(x,y)
plt.grid()
plt.show()
Output:
56
03
5.Matplotlib scatter plot
Program:
import matplotlib.pyplot as plt
import numpy as np
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
plt.scatter(x, y)
x = np.array([2,2,8,1,15,8,12,9,7,3,11,4,7,14,12])
y = np.array([100,105,84,105,90,99,90,95,94,100,79,112,91,80,85])
plt.scatter(x, y)
plt.show()
output:
56
5. Matplotlib bar chart
03
Program:
import matplotlib.pyplot as plt
import numpy as np
x = np.array(["A", "B", "C", "D"])
y = np.array([3, 8, 1, 10])
plt.bar(x,y,width=0.5,color='green')
plt.show()
Output:
6.Matplotlib Histograms
Program:
56
import matplotlib.pyplot as plt
import numpy as np
x = np.random.normal(170, 10, 250)
plt.hist(x,color='blue')
03
plt.show()
Output:
6.Matplotlib Pie Charts
Program:
import matplotlib.pyplot as plt
import numpy as np
y = np.array([35, 25, 25, 15])
mylabels = ["Apples", "Bananas", "Cherries", "Dates"]
plt.legend()
plt.show()
Output:
56
plt.pie(y, labels = mylabels)
03
EXPERIMENT -3
Regression
Linear Regression:
Program: 56
#linear regression
import numpy as nm
import matplotlib.pyplot as mtp
import pandas as pd
data_set= pd.read_csv('Salary_Data.csv')
x= data_set.iloc[:, :-1].values
y= data_set.iloc[:, 1].values
03
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test= train_test_split(x, y, test_size= 1/3, random_state=0)
from sklearn.linear_model import LinearRegression
regressor= LinearRegression()
regressor.fit(x_train, y_train)
y_pred= regressor.predict(x_test)
x_pred= regressor.predict(x_train)
mtp.scatter(x_train, y_train, color="green")
mtp.plot(x_train, x_pred, color="red")
mtp.title("Salary vs Experience (Training Dataset)")
mtp.xlabel("Years of Experience")
mtp.ylabel("Salary(In Rupees)")
mtp.show()
mtp.show()
Output:
56
mtp.ylabel("Salary(In Rupees)")
03
Multiple Regression
Program:
#multiple regression
import pandas
from sklearn import linear_model
df = pandas.read_csv("data.csv")
X = df[['Weight', 'Volume']]
y = df['CO2'] 56
regr = linear_model.LinearRegression()
regr.fit(X, y)
#predict the CO2 emission of a car where the weight is 2300kg, and the volume is 1300cm3:
predictedCO2 = regr.predict([[2300, 1300]])
print('predictedCO2: ',predictedCO2)
03
Output:
predictedCO2: [107.2087328]
EXPERIMENT-4
CLASSIFICATION ALGORITHMS
K-NN Algorithm:
1)Predict on dataset which model has not seen before
Program:
#Knn -py
# Import necessary modules
56
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
# Loading data
irisData = load_iris()
knn = KNeighborsClassifier(n_neighbors=7)
knn.fit(X_train, y_train)
# Predict on dataset which model has not seen before
print(knn.predict(X_test))
Output:
[1 0 2 1 1 0 1 2 2 1 2 0 0 0 0 1 2 1 1 2 0 2 0 2 2 2 2 2 0 0]
Program:
#Knn social media
# Importing the libraries
import numpy as np
56
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
03
dataset = pd.read_csv('Social_Network_Ads.csv')
X = dataset.iloc[:, [2, 3]].values
y = dataset.iloc[:, 4].values
# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)
56
# Predicting the Test set results
y_pred = classifier.predict(X_test)
knn = KNeighborsClassifier(n_neighbors=7)
knn.fit(X_train, y_train)
03
# Calculate the accuracy of the model
print(knn.score(X_test, y_test))
Output:
0.9666666666666667
4)K-nn Graph
Program:
#k-nn graph
# Import necessary modules
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
import numpy as np
import matplotlib.pyplot as plt
irisData = load_iris()
X = irisData.data
y = irisData.target
56
# Create feature and target arrays
# Generate plot
plt.plot(neighbors, test_accuracy, label = 'Testing dataset Accuracy')
plt.plot(neighbors, train_accuracy, label = 'Training dataset Accuracy')
plt.legend()
plt.xlabel('n_neighbors')
plt.ylabel('Accuracy')
plt.show()
Output:
56
03
NAÏVE BAYS ALGORITHM:
56
Program:
# Importing library
import math
03
import random
import csv
# Calculating Mean
def mean(numbers):
56
return sum(numbers) / float(len(numbers))
def MeanAndStdDev(mydata):
info = [(mean(attribute), std_dev(attribute)) for attribute in zip(*mydata)]
# eg: list = [ [a, b, c], [m, n, o], [x, y, z]]
# here mean of 1st attribute =(a + m+x), mean of 2nd attribute = (b + n+y)/3
# delete summaries of last class
del info[-1]
return info
# find Mean and Standard Deviation under each class
def MeanAndStdDevForClass(mydata):
info = {}
dict = groupUnderClass(mydata)
for classValue, instances in dict.items():
return info
56
info[classValue] = MeanAndStdDev(instances)
# Accuracy score
def accuracy_rate(test, predictions):
correct = 0
for i in range(len(test)):
if test[i][-1] == predictions[i]:
correct += 1
return (correct / float(len(test))) * 100.0
# driver code 56
# add the data path in your system
filename = r'pima-indians-diabetes.csv'
# prepare model
info = MeanAndStdDevForClass(train_data)
# test model 56
predictions = getPredictions(info, test_data)
accuracy = accuracy_rate(test_data, predictions)
print("Accuracy of your model is: ", accuracy)
Output: