-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlab17.py
63 lines (50 loc) · 1.99 KB
/
lab17.py
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
import tensorflow as tf
import numpy as np
import pandas as pd
df = pd.read_csv("iris.data", usecols=[0, 1, 2, 3],
names=["1", "2", "3", "4"])
averages = []
data = []
for x in range(100):
data.append([df.iloc[x, 0], df.iloc[x, 1], df.iloc[x, 2], df.iloc[x, 3]])
for j in range(100):
np.random.shuffle(data)
w = tf.Variable(tf.random.normal([4, 1]))
b = tf.Variable(tf.random.normal([1, 1]))
alpha = 0.05
x = tf.constant(data[10:100], dtype=tf.float32)
y = tf.constant([
[0.], [0.], [0.], [0.], [0.], [0.], [0.], [0.], [0.],
[0.], [0.], [0.], [0.], [0.], [0.], [0.], [0.], [0.],
[0.], [0.], [0.], [0.], [0.], [0.], [0.], [0.], [0.],
[0.], [0.], [0.], [0.], [0.], [0.], [0.], [0.], [0.],
[0.], [0.], [0.], [0.], [0.], [0.], [0.], [0.], [0.],
[1.], [1.], [1.], [1.], [1.], [1.], [1.], [1.], [1.],
[1.], [1.], [1.], [1.], [1.], [1.], [1.], [1.], [1.],
[1.], [1.], [1.], [1.], [1.], [1.], [1.], [1.], [1.],
[1.], [1.], [1.], [1.], [1.], [1.], [1.], [1.], [1.],
[1.], [1.], [1.], [1.], [1.], [1.], [1.], [1.], [1.]],
dtype=tf.float32)
testx = tf.constant(data[0:10], dtype=tf.float32)
testy = tf.constant([[0.], [1.], [0.], [1.], [0.],
[1.], [0.], [1.], [0.], [1.]],
dtype=tf.float32)
def predict(x):
# forward propagation
out = tf.matmul(x, w)
out = tf.add(out, b)
out = tf.nn.sigmoid(out)
return out
def loss(y_predict, y):
return tf.reduce_mean(tf.square(y_predict - y))
for i in range(10000):
with tf.GradientTape() as t:
current_loss = loss(predict(x), y)
dW, db = t.gradient(current_loss, [w, b])
w.assign_sub(alpha * dW)
b.assign_sub(alpha * db)
#print(w.numpy(), b.numpy())
avg = tf.round(predict(testx)).numpy()
averages.append(avg)
#print(j, " of 99")
print("total average: ", np.average(averages))