Programs
Programs
Hello, world!
Python Program to Add Two Numbers
[2]: num1 = 1.5
num2 = 6.3
# Add two numbers
sum = num1 + num2
# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
1
[5]: import cmath
num = 1+2j
# To take input from the user
#num = eval(input('Enter a number: '))
num_sqrt = cmath.sqrt(num)
print('The square root of {0} is {1:0.3f}+{2:0.3f}j'.format(num ,num_sqrt.
↪real,num_sqrt.imag))
2
# create a temporary variable and swap the values
temp = x
x = y
y = temp
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))
6
Python Program to Convert Kilometers to Miles
[11]: kilometers = float(input("Enter value in kilometers: "))
# conversion factor
conv_fac = 0.621371
# calculate miles
miles = kilometers * conv_fac
print('%0.2f kilometers is equal to %0.2f miles' %(kilometers,miles))
1 EXPERIMENT 2
1.1 Arrays, lists - Slicing, reshaping, matrix operations,etc
[13]: import numpy as np
array a is: [1 2 3]
the shape of numpy array a is : (3,)
Combining numpy arrays
[14]: a=np.array([1,2,3,4])
b=np.array([5,6,7,8])
x=np.vstack((a,b))
y=np.hstack((a,b))
3
print('vertically stacked: ',x)
print('horizontally stacked: ',y)
[17 11 19]
3
y is : [20 14 22]
Slicing
[34]: a = np.array([[17, 11, 19],[20, 15, 8],[1, 12, 49],[42, 15, 78]]) #a's shape is␣
↪(4x3)
rows sliced
[[17 11 19]
[20 15 8]]
columns sliced
[[17 11]
[20 15]
[ 1 12]
[42 15]]
reshaping
[99]: a = np.array([[17, 11, 19],[20, 15, 8],[1, 12, 49],[42, 15, 78]]) #a's shape is␣
↪(4x3)
print(a.shape)
a=np.reshape(a,(3,4))
print(a.shape)
(4, 3)
(3, 4)
4
2 Linear regression
[103]: import numpy as np
from sklearn import datasets
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
for i in range(n_iters):
y_pred = np.dot(X, weights) + bias
dw = (1 / num_samples) * np.dot(X.T, y_pred - y) #derivative of Loss␣
↪with respect to weights w
return weights,bias
def predict(X):
return np.dot(X,weights) + bias
x_train,x_test,y_train,y_test=train_test_split(X,y)
weights,bias=fit(x_train,y_train)
print('weights are:\n',weights,'\n\nBias is :\n',bias)
predictions=predict(x_test)
loss=np.mean(np.abs(predictions-y_test)) #mean absolute error
print('\nMAE is ',loss)
plt.scatter(x_test,y_test,color='m')
plt.plot(x_test,predictions)
5
weights are:
[67.17516321]
Bias is :
0.00336403250300076
MAE is 0.008391426389049123
3 Logistic Regression
[138]: import numpy as np
from sklearn import datasets
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
def sigmoid(z):
return 1 / (1 + np.exp(-z))
6
def fit(X, y):
# weights initialization
m = np.zeros(X.shape[1])
num_iter=1000
lr=0.01
for i in range(num_iter):
z = np.dot(X, m)
y_pred = sigmoid(z)
gradient = np.dot(X.T, (y_pred - y)) / y.size
m -= lr * gradient
return m
def predict(X):
prdns=sigmoid(np.dot(X,weights)) >= 0.5
return (prdns).astype(int)
X, y = datasets.make_classification(n_samples=500,␣
↪n_features=1,n_informative=1,n_redundant=0,n_repeated=0,n_clusters_per_class=1,␣
↪n_classes=2,random_state=4)
x_train,x_test,y_train,y_test=train_test_split(X,y)
weights=fit(x_train,y_train)
print('weights are:\n',weights)
predictions=predict(x_test)
acc=np.mean(predictions==y_test)
print('\naccuracy is ',acc)
plt.scatter(x_test,y_test,color='blue')
plt.scatter(x_test,predictions,color='red')
x=np.linspace(min(x_test),max(x_test),125)
y=sigmoid(np.dot(x,weights))
plt.plot(x,y)
weights are:
[1.91348263]
accuracy is 0.984
7
8