Compare commits

...

16 Commits

Author SHA1 Message Date
Trygve
352173995f Exercise 6 2024-10-28 12:27:14 +01:00
Trygve
bb9f20981a uke4 2024-10-01 14:15:03 +02:00
Trygve
16ced51fa8 uke3 2024 2024-09-29 18:45:21 +02:00
Trygve
366fe4df73 uke2 2024 2024-09-20 21:08:35 +02:00
Trygve
081483ed4f csv 2024-09-12 08:27:31 +02:00
Trygve
20bed45e10 Samla uke 1 i en fil 2024-09-12 08:26:47 +02:00
82e193a278 Fjerna en lock fil 2023-11-15 10:15:19 +00:00
9961df1c90 La til requirements.txt 2023-10-30 14:17:09 +01:00
fa9f0faf62 Ferdig med oppgave 6: MNIST modell 2023-10-30 14:11:48 +01:00
29bbee4165 Ferdig med deloppgave 2 uke 6. Nettverket funker 🥳 2023-10-26 09:28:10 +02:00
ea9bf70eaa Vet ikke hva jeg gjør 2023-10-26 09:04:31 +02:00
d5c072ba3f starta på uke6 2023-10-25 14:12:43 +02:00
dbd0506e4c uke5 2023-10-25 14:12:34 +02:00
001702b010 Ferdig uke 3 2023-09-29 12:32:02 +02:00
12530126dc Uke 3 #2 utkast Trygve 2023-09-28 14:59:11 +02:00
27b4466948 Uke 3 #1 utkast 2023-09-28 14:58:25 +02:00
23 changed files with 1792 additions and 117 deletions

512
MNIST/W_1.txt Normal file

File diff suppressed because one or more lines are too long

256
MNIST/W_2.txt Normal file

File diff suppressed because one or more lines are too long

10
MNIST/W_3.txt Normal file

File diff suppressed because one or more lines are too long

1
MNIST/b_1.txt Normal file

File diff suppressed because one or more lines are too long

1
MNIST/b_2.txt Normal file

File diff suppressed because one or more lines are too long

1
MNIST/b_3.txt Normal file
View File

@@ -0,0 +1 @@
-0.3120380938053131 0.057060789316892624 0.5383008718490601 -0.4334142804145813 0.20545503497123718 0.8229865431785583 0.26446419954299927 1.3929160833358765 0.40466466546058655 -0.06923668831586838

108
MNIST/main.py Normal file
View File

@@ -0,0 +1,108 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 28 08:23:56 2023
@author: Mohamad Mohannad al Kawadri (mohamad.mohannad.al.kawadri@nmbu.no), Trygve Børte Nomeland (trygve.borte.nomeland@nmbu.no)
"""
from abc import ABC, abstractmethod
import numpy as np
from copy import deepcopy
from torchvision import datasets, transforms
class Network:
def __init__(self, layers, W_file_list, b_file_list):
self.layers = layers
self.W_file_list = W_file_list
self.b_file_list = b_file_list
self.x = input
def run(self, x):
result = x
for n, W_file, b_file in zip(self.layers, self.W_file_list, self.b_file_list):
y = deepcopy(result)
l = n(y, W_file = W_file, b_file = b_file)
result = l.run()
return result
def evaluate(self, x, expected_value):
result = list(self.run(x))
max_value_index = result.index(max(result))
return int(max_value_index) == expected_value
class Layer:
def __init__(self, x, W_file, b_file):
self.x = x
files = read(W_file, b_file)
self.W = files.get('W')
self.b = files.get('b')
@abstractmethod
def run(self):
pass
class SigmaLayer(Layer):
def run(self):
return layer(self.W, self.x, self.b)
class ReluLayer(Layer):
def run(self):
return relu_layer(self.W, self.x, self.b)
def read(W_file, b_file):
return {'W': np.loadtxt(W_file), 'b': np.loadtxt(b_file)}
# define activation function
def sigma(y):
if y > 0:
return y
else:
return 0
sigma_vec = np.vectorize(sigma)
def relu_scalar(x):
if x > 0:
return x
else:
return 0
relu = np.vectorize(relu_scalar)
# define layer function for given weight matrix, input and bias
def layer(W, x, b):
return sigma_vec(W @ x + b)
def relu_layer(W, x, b):
return sigma_vec(W @ x + b)
# Function from example file "read.py"
def get_mnist():
return datasets.MNIST(root='./data', train=True, transform=transforms.ToTensor(), download=True)
# Function from example file "read.py"
def return_image(image_index, mnist_dataset):
image, label = mnist_dataset[image_index]
image_matrix = image[0].detach().numpy() # Grayscale image, so we select the first channel (index 0)
return image_matrix.reshape(image_matrix.size), image_matrix, label
def evalualte_on_mnist(image_index, expected_value):
mnist_dataset = get_mnist()
x, image, label = return_image(image_index, mnist_dataset)
network = Network([ReluLayer, ReluLayer, ReluLayer], ['W_1.txt', 'W_2.txt', 'W_3.txt'], ['b_1.txt', 'b_2.txt', 'b_3.txt'])
return network.evaluate(x, expected_value)
def run_on_mnist(image_index):
mnist_dataset = get_mnist()
x, image, label = return_image(image_index, mnist_dataset)
network = Network([ReluLayer, ReluLayer, ReluLayer], ['W_1.txt', 'W_2.txt', 'W_3.txt'], ['b_1.txt', 'b_2.txt', 'b_3.txt'])
return network.run(x)
def main():
print(f'Check if network works on image 19961 (number 4): {evalualte_on_mnist(19961, 4)}')
print(f'Check if network works on image 10003 (number 9): {evalualte_on_mnist(10003, 9)}')
print(f'Check if network works on image 117 (number 2): {evalualte_on_mnist(117, 2)}')
print(f'Check if network works on image 1145 (number 3): {evalualte_on_mnist(1145, 3)}')
print(f'Values image 19961 (number 4): {run_on_mnist(19961)}')
if __name__ == '__main__':
main()

3
MNIST/requirements.txt Normal file
View File

@@ -0,0 +1,3 @@
numpy
setuptools
torchvision

512
W_1.txt Normal file

File diff suppressed because one or more lines are too long

1
b_1.txt Normal file

File diff suppressed because one or more lines are too long

83
ex6.py Normal file
View File

@@ -0,0 +1,83 @@
class Person:
def __init__(self, name: str, age: int, email: str) -> None:
self._name: str = name
self._age: int = age
self._email: str = email
def get_details(self) -> str:
return f"Name: {self._name}, Age: {self._age}, Email: {self._email}"
class Student(Person):
def __init__(self, name: str, age: int, email: str, student_id: int) -> None:
super().__init__(name, age, email)
self._student_id: int = student_id
self._courses: list = []
self._grades: dict[str, str] = {}
def enroll_in_course(self, course: 'Course') -> None:
self._courses.append(course)
def assign_grade(self, course_name: str, grade: str) -> None:
self._grades[course_name] = grade
def get_grades(self) -> dict[str, str]:
return self._grades
class Teacher(Person):
def __init__(self, name: str, age: int, email: str, subject: str) -> None:
super().__init__(name, age, email)
self._subject: str = subject
def assign_grade(self, student: Student, course: 'Course', grade: str) -> None:
student.assign_grade(course._course_name, grade)
class Course:
def __init__(self, course_name: str, course_code: str) -> None:
self._course_name: str = course_name
self._course_code: str = course_code
self._enrolled_students: list[Student] = []
def add_student(self, student: Student) -> None:
self._enrolled_students.append(student)
student.enroll_in_course(self)
def list_students(self) -> list[str]:
return [x.get_details() for x in self._enrolled_students]
def main() -> None:
thorvald = Student("Thorvald", 28, "thorvald@example.com", 456)
johannes = Student("Johannes", 19, "Johannes@example.com", 35198)
tora = Student("Tora", 21, "Tora@example.com", 984555)
ola = Teacher("Ola Normann", 56, "ola_normann@example.com", "FYS101")
kari = Teacher("Kari Normann", 104, "kari.normann@example.com", "MATH999")
FYS101 = Course("Mekanikk", "FYS101")
MATH999 = Course("Matte", "MATH999")
students = [thorvald, johannes, tora]
for student in students:
FYS101.add_student(student)
MATH999.add_student(student)
ola.assign_grade(thorvald, FYS101, "F")
ola.assign_grade(johannes, FYS101, "E")
ola.assign_grade(tora, FYS101, "A")
kari.assign_grade(thorvald, MATH999, "B")
kari.assign_grade(johannes, MATH999, "D")
kari.assign_grade(tora, MATH999, "A+")
print(f"{thorvald._name}'s grades: {thorvald.get_grades()}")
print(f"{thorvald._name}'s grades: {johannes.get_grades()}")
print(f"{tora._name}'s grades: {tora.get_grades()}")
print("Students in FYS101:")
for student in FYS101.list_students():
print(student)
if __name__ == "__main__":
main()

110
uke1.py Normal file
View File

@@ -0,0 +1,110 @@
# Task 1
def task1():
name = input("Enter your name here:")
print(f"What's up {name}!")
# Task 2
def putinframe(text):
l = len(text)
print("-"*(l+6))
print(""+" "*(l+4) + "")
print(""+ " " + text + " "+ "")
print(""+" "*(l+4) + "")
print("-"*(l+6))
def task2():
name = input("Type your name:")
putinframe(f"Have a lovely day {name}!")
# Task 3
def square_table(c1, c2, c3):
t = "{:^10}|{:^10}|{:^10}|\n".format(c1[0],c2[0],c3[0])
t += ("-"*len(t)+"\n")
for n in range(1, len(c1)):
t += ("{:^10}|{:^10}|{:^10}|\n".format(c1[n],c2[n],c3[n]))
return(t)
def task3():
n_list = ["x"]
sq_list = [""]
cube_list = [""]
for n in range(11):
n_list.append(n)
sq_list.append(n**2)
cube_list.append(n**3)
print(square_table(n_list, sq_list, cube_list))
# task 4
def district_table(data, head):
# Formats the data into a nice table in a string
t = "{:^25}|{:^10}|\n".format(head[0],head[1])
t += ("-"*len(t)+"\n")
for n,p in data.items():
t += ("{:^25}|{:^10}|\n".format(n, p))
return(t)
def task4():
with open('norway_municipalities_2017.csv') as f:
# we will make a dict where the the kei is the district and the value the population
d = {}
# assume the csv file always has a header
l_iter = iter(f)
l_iter.__next__()
for l in l_iter:
# we get a list where 0 is the kommune name, 1 is what fylke it is in and 2 is the population
ll = l.strip("\n").split(',')
name = ll[1]
if name in d.keys():
d.update({name: d.get(name) + int(ll[2])})
else:
d.update({name: int(ll[2])})
head = ["District", "Population"]
res = {key: val for key, val in sorted(d.items(), key = lambda ele: ele[1], reverse=True)}
print(district_table(res, head))
# Task 5
import matplotlib.pyplot as plt
import numpy as np
def task5():
with open('norway_municipalities_2017.csv') as f:
# we will make a dict where the the kei is the district and the value the population
d = {}
# assume the csv file always has a header
l_iter = iter(f)
l_iter.__next__()
for l in l_iter:
# we get a list where 0 is the kommune name, 1 is what fylke it is in and 2 is the population
ll = l.strip("\n").split(',')
name = ll[1]
if name in d.keys():
d.update({name: d.get(name) + int(ll[2])})
else:
d.update({name: int(ll[2])})
head = ["District", "Population"]
res = {key: val for key, val in sorted(d.items(), key = lambda ele: ele[1], reverse=True)}
n = len(res.keys())
x = 0.5 + np.arange(n)
y = res.values()
fig, ax = plt.subplots()
ax.bar(res.keys(), y, edgecolor="white", linewidth=0.7)
ax.set(xlabel=head[0], ylabel=head[1])
plt.xticks(rotation = 90)
plt.show()
if __name__ == "__main__":
print("Task 1:")
task1()
print("\nTask 2:")
task2()
print("\nTask 3:")
task3()
print("\nTask 4:")
task4()
print("\nTask 5:")
task5()

View File

@@ -1,2 +0,0 @@
name = input("Enter your name here:")
print(f"What's up {name}!")

View File

@@ -1,15 +0,0 @@
def putinframe(text):
l = len(text)
print(l)
print(""*(l+6))
print(""+" "*(l+4) + "")
print(""+ " " + text + " "+ "")
print(""+" "*(l+4) + "")
print(""*(l+6))
def main():
name = input("Type yo name:")
putinframe(f"What's up {name}!")
if __name__ == "__main__":
main()

View File

@@ -1,18 +0,0 @@
def table(c1, c2, c3):
t = "{:^10}|{:^10}|{:^10}|\n".format(c1[0],c2[0],c3[0])
t += ("-"*len(t)+"\n")
for n in range(1, len(c1)):
t += ("{:^10}|{:^10}|{:^10}|\n".format(c1[n],c2[n],c3[n]))
return(t)
def main():
n_list = ["x"]
sq_list = [""]
cube_list = [""]
for n in range(11):
n_list.append(n)
sq_list.append(n**2)
cube_list.append(n**3)
print(table(n_list, sq_list, cube_list))
if __name__ == "__main__":
main()

View File

@@ -1,30 +0,0 @@
def table(data, head):
# Formats the data into a nice table in a string
t = "{:^25}|{:^10}|\n".format(head[0],head[1])
t += ("-"*len(t)+"\n")
for n,p in data.items():
t += ("{:^25}|{:^10}|\n".format(n, p))
return(t)
def main():
with open('norway_municipalities_2017.csv') as f:
# we will make a dict where the the kei is the district and the value the population
d = {}
# assume the csv file always has a header
l_iter = iter(f)
l_iter.__next__()
for l in l_iter:
# we get a list where 0 is the kommune name, 1 is what fylke it is in and 2 is the population
ll = l.strip("\n").split(',')
name = ll[1]
if name in d.keys():
d.update({name: d.get(name) + int(ll[2])})
else:
d.update({name: int(ll[2])})
head = ["District", "Population"]
res = {key: val for key, val in sorted(d.items(), key = lambda ele: ele[1], reverse=True)}
print(table(res, head))
if __name__ == "__main__":
main()

View File

@@ -1,33 +0,0 @@
import matplotlib.pyplot as plt
import numpy as np
def main():
with open('norway_municipalities_2017.csv') as f:
# we will make a dict where the the kei is the district and the value the population
d = {}
# assume the csv file always has a header
l_iter = iter(f)
l_iter.__next__()
for l in l_iter:
# we get a list where 0 is the kommune name, 1 is what fylke it is in and 2 is the population
ll = l.strip("\n").split(',')
name = ll[1]
if name in d.keys():
d.update({name: d.get(name) + int(ll[2])})
else:
d.update({name: int(ll[2])})
head = ["District", "Population"]
res = {key: val for key, val in sorted(d.items(), key = lambda ele: ele[1], reverse=True)}
n = len(res.keys())
x = 0.5 + np.arange(n)
y = res.values()
fig, ax = plt.subplots()
ax.bar(res.keys(), y, edgecolor="white", linewidth=0.7)
ax.set(xlabel=head[0], ylabel=head[1])
plt.xticks(rotation = 90)
plt.show()
if __name__ == "__main__":
main()

33
uke2.py
View File

@@ -57,30 +57,27 @@ def table_from_votes(file_path, num=None):
return(t) return(t)
# Task 2 # Task 2
def get_friends(text):
friends = []
for s in text:
names = re.findall(r'[A-Z]\w*', s)
if len(names) != 2:
raise ValueError('String does not contain excactly two capitalized words')
friends.append(names)
t = '{:^20}\n'.format('Venner') def print_encoding_info(char):
t += ("-"*len(t)+"\n") char_int = int.from_bytes(bytes(char, 'utf-8'))
for n in friends: print(f"Character: '{char}'")
t += (f'{n[0]:^10}-{n[1]:^10}\n') if char_int < 129:
return(t) print(f"- ASCII representation: {format(char_int, 'b')}")
else:
print("- Not in ASCII range")
print(f"- UTF-8: {' '.join(format(x, 'b') for x in bytearray(char, 'utf-8'))}", end='')
print(f' ({len(bytearray(char, "utf-8"))} bytes)')
print('\n')
def print_encoding_info_list(char_list):
for char in char_list:
print_encoding_info(char)
def main(): def main():
print(table_from_votes('2021-09-14_party distribution_1_st_2021.csv')) print(table_from_votes('2021-09-14_party distribution_1_st_2021.csv'))
print(table_from_votes('2021-09-14_party distribution_1_st_2021.csv', 3)) print(table_from_votes('2021-09-14_party distribution_1_st_2021.csv', 3))
text = [ print_encoding_info_list(["2", "$", "å"])
'Ali and Per and friends.',
'Kari and Joe know each other.',
'James has known Peter since school days.'
]
print(get_friends(text))
if __name__ == '__main__': if __name__ == '__main__':
main() main()

77
uke3.py Normal file
View File

@@ -0,0 +1,77 @@
import re
# Task 1
"""
Assume that we have sentences of the form
- Ali and Per are friends.
- Kari and Joe know each other.
- James has known Peter since school days.
The common structure here is that each sentence contains two names and that the names are the only words beginning with capital letters. Create a regular expression that
- matches these sentences (one sentence at a time)
- collects the names in groups
"""
def get_friends(text):
friends = []
for s in text:
names = re.findall(r'[A-Z]\w*', s)
if len(names) != 2:
raise ValueError('String does not contain excactly two capitalized words')
friends.append(names)
t = '{:^20}\n'.format('Venner')
t += ("-"*len(t)+"\n")
for n in friends:
t += (f'{n[0]:^10}-{n[1]:^10}\n')
return(t)
# Task 2
"""
Write a Python function validate_password that checks if a given password string is valid based on the following rules:
Starts with an uppercase letter from I to Z.
Contains at least one word character (a-z, A-Z, 0-9, or underscore).
Has exactly 4 to 5 characters in length.
Ends with a digit.
May contain spaces between the characters but cannot start or end with a space.
The password must end at the string's end.
"""
def validate_password(password):
if re.match('[I-Z]', password) == None:
return False
if re.match('[a-zA-Z0-9|_]', password) == None:
return False
if len(password) < 4 or len(password) > 5:
return False
if re.search('[0-9]$', password) == None:
return False
# Rules 5 and 6 are already fulfilled
return True
def main():
print('Test task 1:')
text = [
'Ali and Per and friends.',
'Kari and Joe know each other.',
'James has known Peter since school days.'
]
print(get_friends(text))
print('Test task 1:')
print('Valid:')
print(f'J1234: {validate_password("J1234")}')
print(f'I_ab5: {validate_password("I_ab5")}')
print(f'Z9_w4: {validate_password("Z9_w4")}')
print('\n')
print('Invalid:')
print(f'A1234: {validate_password("A1234")}')
print(f'J12345: {validate_password("J12345")}')
print(f'I__: {validate_password("I__")}')
print(f'?=?=)(=)/&__: {validate_password("?=?=)(=)/&")}')
print(f' J1234: {validate_password(" J1234")}')
if __name__ == '__main__':
main()

24
uke4.py Normal file
View File

@@ -0,0 +1,24 @@
from pathlib import Path
def generate_exercise_list(project_assignments_start, total_exercises):
return [str(i) for i in range(1, project_assignments_start)] + [f'{i}{part}' for i in range(project_assignments_start, total_exercises + 1) for part in ['a', 'b']]
def create_directories(directory, exercises, students):
parent_directory = Path.cwd() / directory
for exercise in exercises:
exercise_path = parent_directory / Path('exercise_' + exercise)
for student in students:
student_path = exercise_path / student
studentstudent_path.mkdir(parents=True, exist_ok=True)
for directory in parent_directory.glob('**/*'):
print(directory)
def main():
exercises = generate_exercise_list(5, 12)
students = ['Ole', 'Sarah', 'Ferdinand', 'Mattis']
create_directories('projects', exercises, students)
if __name__ == '__main__':
main()

25
uke5.py Normal file
View File

@@ -0,0 +1,25 @@
import numpy as np
def relu(y):
return np.maximum(0, y)
def layer(W, x, b):
return relu(W @ x + b)
n = [64,128,128,128,10]
print(f"Dimensions: {n}")
# First layer
x = np.random.rand(n[0])
b = np.random.rand(n[1])
y = np.random.rand(128,64)
y = layer(y, x, b)
for i in range(2, len(n)):
W = np.random.rand(n[i], n[i - 1])
b = np.random.rand(n[i])
y = layer(W, y, b)
print(y)

52
uke6.py Normal file
View File

@@ -0,0 +1,52 @@
import numpy as np
from copy import deepcopy
class Network:
def __init__(self, layers, W_file_list, b_file_list):
self.layers = layers
self.W_file_list = W_file_list
self.b_file_list = b_file_list
self.n_layers = 4
self.n_inputs = 784
self.n_outputs = 10
self.n = [self.n_inputs, 512, 256, self.n_outputs]
self.x = np.random.rand(self.n_inputs)
def run(self):
result = self.x
for n, W_file, b_file in zip(self.layers, self.W_file_list, self.b_file_list):
y = deepcopy(result)
l = n(y, W_file = W_file, b_file = b_file)
result = l.run()
return result
class Layer:
def __init__(self, x, W_file, b_file):
self.x = x
files = read(W_file, b_file)
self.W = files.get('W')
self.b = files.get('b')
def run(self):
return layer(self.W, self.x, self.b)
def read(W_file, b_file):
return {'W': np.loadtxt(W_file), 'b': np.loadtxt(b_file)}
# define activation function
def sigma(y):
if y > 0:
return y
else:
return 0
sigma_vec = np.vectorize(sigma)
# define layer function for given weight matrix, input and bias
def layer(W, x, b):
return sigma_vec(W @ x + b)
def main():
network = Network([Layer, Layer, Layer], ['W_1.txt', 'W_2.txt', 'W_3.txt'], ['b_1.txt', 'b_2.txt', 'b_3.txt'])
print(network.run())
if __name__ == '__main__':
main()