-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinear_function_ml.py
More file actions
67 lines (54 loc) · 1.7 KB
/
linear_function_ml.py
File metadata and controls
67 lines (54 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt
import random
class LinearFunction:
def __init__(self, m, n):
self.m = float(m)
self.n = float(n)
def create_training_data(self, size):
if size < 1:
raise ValueError
else:
x = np.arange(-size // 2, size // 2 + 1)
return x, self.m * x + self.n
def create_testing_data(self, size):
if size < 1:
raise ValueError
else:
x = np.arange(-size // 2, size // 2)
return x, self.m * x + self.n
def plot(self, start=-10, end=10):
x = np.arange(start, end+1)
y = self.m * x + self.n
plt.figure(1, figsize=(10, 10))
plt.title(f'Graph of {self}')
plt.plot(x, y)
plt.show()
def __str__(self):
if self.n < 0:
return f'y={self.m}x {self.n}'
return f'y={self.m}x+{self.n}'
model = keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])])
model.compile(optimizer='sgd', loss='mean_squared_error')
my_function = LinearFunction(2, -1)
x, y = my_function.create_training_data(10)
model.fit(x, y, epochs=500)
size = random.randint(1, 100)
x_test, y_test = my_function.create_testing_data(size)
y_prediction = model.predict(x_test)
y_prediction.reshape(1, size)
plt.figure(figsize=(10, 10))
plt.title(f'{my_function} Graph Machine Learning')
plt.subplot(2, 1, 1)
plt.title('Training')
plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('y')
plt.subplot(2, 1, 2)
plt.title(f'Test Data and Real Function is -> {my_function}')
plt.plot(x_test, y_prediction, 'c-', x_test, y_test, 'r:')
plt.xlabel('x')
plt.ylabel('y')
plt.legend(['Model', 'Given'])
plt.show()