0% found this document useful (0 votes)
42 views9 pages

AI Lab Final - 2

The document contains 11 code snippets on various Python programming topics like data processing, machine learning algorithms, conditional statements, input/output, string operations etc. Each code snippet is self-contained and addresses a different programming concept or task. The document appears to be a collection of Python code examples for learning purposes.

Uploaded by

Smk Nabil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views9 pages

AI Lab Final - 2

The document contains 11 code snippets on various Python programming topics like data processing, machine learning algorithms, conditional statements, input/output, string operations etc. Each code snippet is self-contained and addresses a different programming concept or task. The document appears to be a collection of Python code examples for learning purposes.

Uploaded by

Smk Nabil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

GROUP- 6

1.Mahmudul Karim Nabil ----- 171-15-1256

2.Shahriar Kobir ------ 171-15-1252


3. A.M. Rakib Hasnat ------ 173-15-1632
4. Foysal Ahamed ------- 171-15-1268

5.Abdullah Al Faysal -------- 171-15-1185

1.

from datetime import datetime

from sklearn.linear_model import LogisticRegression, LinearRegression, SGDRegressor

from sklearn.model_selection import train_test_split

import pandas as pd

import numpy as np

# Enter your code here. Read input from STDIN. Print output to STDOUT

temp=[]

sample_input = input()

try:

while (sample_input != ''):

temp.append(sample_input)

sample_input = input()

except:

pass

inputs = temp

db_len = inputs[0]

del inputs[0]
dates = []

stockprices = []

for x in inputs:

temp = x.split('\t')

float_days = datetime.strptime(temp[0], '%m/%d/%Y %H:%M:%S')

dates.append(float_days)

try:

stockprices.append(float(temp[1]))

except:

stockprices.append(np.nan)

pass

stockdf = pd.Series(stockprices, index=dates)

stockdf.index.name = 'Date'

stockdf = stockdf.reset_index(name='Price')

missing_price_dates = stockdf[stockdf['Price'].isnull()]['Date'].values

missing_price_dates = missing_price_dates.astype('datetime64[D]').astype(int)

missing_price_dates = [[x] for x in missing_price_dates]

missing_price_dates = np.asarray(missing_price_dates)

stockdf = stockdf.dropna()

dates, prices = [[x] for x in stockdf['Date'].values], stockdf['Price'].values

X_train, X_test, y_train, y_test = train_test_split(dates, prices, test_size=0.05, shuffle=False)

X_train, y_train = np.asarray(X_train), np.asarray(y_train)


mdl = SGDRegressor(shuffle=False, max_iter=5000, learning_rate='optimal', random_state=0,
n_iter_no_change=30, fit_intercept=False, epsilon=0.01)

mdl.fit(X_train, y_train)

y_pred = mdl.predict(missing_price_dates)

for pred in y_pred:

print(pred)

2.

from sklearn.svm import SVR

import numpy as np

import pandas as pd

def getData():

# Getting training data

train_dir = 'trainingdata.txt'

f = open(train_dir, "r")

data = []

for x in f:

a = x.replace('\n', '')

data.append(a.split(','))

return data

if _name_ == '_main_':

timeCharged = float(input())

data = getData()

df = pd.DataFrame(data, columns=['time', 'last'])


X = np.array([df['time'].values])

X = np.reshape(X, (100, 1))

y = np.array(df['last'].values)

model = SVR(kernel='rbf', C=5000, epsilon=0.0001, tol=1e-3, gamma='scale')

model.fit(X,y)

lasting = model.predict([[3.76]])[0]

print(round(lasting,2))

3.

import sys

from scipy.interpolate import UnivariateSpline

import numpy as np

n = int(sys.stdin.readline())

raw_prices = []

for i in range(0, n):

line = sys.stdin.readline()

timestamp, price = line.split("\t")

raw_prices.append(price)

prices_ind = []

missing_prices_ind = []

prices = []
for i in range(0, n):

if 'Missing' in raw_prices[i]:

missing_prices_ind.append(i)

else:

prices_ind.append(i)

prices.append(float(raw_prices[i]))

spline = UnivariateSpline(np.array(prices_ind), np.array(prices), s=2)

for i in missing_prices_ind:

print(spline(i))

4.

from sklearn.svm import SVR

import numpy as np

import pandas as pd

def getData():

# Getting training data

train_dir = 'trainingdata.txt'

f = open(train_dir, "r")

data = []

for x in f:

a = x.replace('\n', '')

data.append(a.split(','))

return data

if _name_ == '_main_':

timeCharged = float(input())
data = getData()

df = pd.DataFrame(data, columns=['time', 'last'])

X = np.array([df['time'].values])

X = np.reshape(X, (100, 1))

y = np.array(df['last'].values)

model = SVR(kernel='rbf', C=5000, epsilon=0.0001, tol=1e-3, gamma='scale')

model.fit(X,y)

lasting = model.predict([[3.76]])[0]

print(round(lasting,2))

5.

from sklearn.svm import SVR

import numpy as np

import pandas as pd

def getData():

# Getting training data

train_dir = 'trainingdata.txt'

f = open(train_dir, "r")

data = []

for x in f:

a = x.replace('\n', '')

data.append(a.split(','))

return data

if name == 'main':

timeCharged = float(input())
data = getData()

df = pd.DataFrame(data, columns=['time', 'last'])

X = np.array([df['time'].values])

X = np.reshape(X, (100, 1))

y = np.array(df['last'].values)

model = SVR(kernel='rbf', C=5000, epsilon=0.0001, tol=1e-3, gamma='scale')

model.fit(X,y)

lasting = model.predict([[3.76]])[0]

print(round(lasting,2))

6.

def is_leap(year):

leap = False

# Write your logic here

return leap

7.

for _ in range(int(raw_input())):

name = raw_input()

score = float(raw_input())

8.

a = int (input())

b = int (input())
c=a+b

d=a-b

e=a*b

print(c)

print(d)

print(e)

9.

n = int(input())

if (n % 2 ) == 0:

if int in range (2, 5):

print("Not wired")

elif int in range (6, 20):

print("Weird")

elif n >= 20:

print("Not weird")

else:

print("The number is odd.")

10.

value1 = int (input("Enter the first number from user: "))

value2 = int (input("Enter the second number form user: "))

value3 = value1//value2

value4 = value1 / value2

print(value3)
print(value4)

11.

A = input("Enter the first string: ").strip()

x = input("Enter the second string: ").strip()

count = 0

for i in range(len(A) - len(x) + 1):

if A[i:i+len(x)] == x:

count += 1

print (count)

You might also like