import numpy as np
import matplotlib.pyplot as plt
a = [1,2,3]
b = [4,5,6]
c = a + b
print(c)
try:
c = a*b
print(c)
except:
print("Operasi perkalian 2 list tidak memiliki arti")
a = np.array([1,2,3])
b = np.array([4,5,6])
u = a+b
print(u)
v = a*b
print(v)
def kuadrat(x):
return x**2
#numpy array dengan 7 anggota
x = np.array([-3,-2,-1,0,1,2,3])
y1 = kuadrat(x)
print(y1)
def relU(x):
return np.maximum(0,x)
y2 = relU(x)
print(y2)
def turunan(fungsi, x, delta = 0.01):
df = fungsi(x + delta) - fungsi(x - delta)
dx = 2 * delta
return df/dx
x = np.arange(-2,2,0.01)
y = kuadrat(x)
dydx = turunan(kuadrat, x)
plt.title("Grafik fungsi kuadrat dan turunannya")
plt.plot(x, y, label="f(x)")
plt.plot(x,dydx, label="df(x)/dx")
plt.legend()
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def dsigmoid(x):
return sigmoid(x)*(1 - sigmoid(x))
x = np.arange(-5,5,0.1)
dydx = turunan(sigmoid, x)
plt.figure(figsize=(8, 6))
plt.plot(x, sigmoid(x), label="sigmoid")
plt.plot(x, dsigmoid(x), label="turunan (analitik) sigmoid")
plt.plot(x,dydx, "--", label="turunan numerik sigmoid")
plt.legend()
plt.title("Kurva Sigmoid dan Turunannya")
def komposisi(funs,x):
fun2, fun1 = funs
y = fun1(x)
f2 = fun2(y)
return f2
kuad_sig = komposisi([kuadrat, sigmoid], x)
sig_kuad = komposisi([sigmoid, kuadrat], x)
fig, ax = plt.subplots(1, 2, sharex='col', sharey='row', figsize=(14,4))
ax[0].plot(x, kuad_sig)
ax[0].set_title("Komposisi sigma(x)^2 ")
ax[1].plot(x, sig_kuad)
ax[1].set_title("Komposisi sigma(x^2) ")
def turunan_rantai(funs, x, delta = 0.01):
fun2, fun1 = funs
df1dx = turunan(fun1, x)
df2du = turunan(fun2, fun1(x))
return df2du * df1dx
kuad_sig = komposisi([kuadrat, sigmoid], x)
turunan_kuad_sig = turunan_rantai([kuadrat, sigmoid], x)
sig_kuad = komposisi([sigmoid, kuadrat], x)
turunan_sig_kuad = turunan_rantai([sigmoid, kuadrat], x)
fig, ax = plt.subplots(1, 2, sharex='col', sharey='row', figsize=(14,4))
ax[0].plot(x, kuad_sig, label="f(x)")
ax[0].plot(x, turunan_kuad_sig, label=r"$df/dx$")
ax[0].legend()
ax[0].set_title("Komposisi sigma(x)^2 ")
ax[1].plot(x, sig_kuad, label="f(x)")
ax[1].plot(x, turunan_sig_kuad, label="f(x)")
ax[1].set_title("Komposisi sigma(x^2) ")
ax[1].legend()
def aktivasi(u):
if u < 0:
return 0
else:
return 1
x = np.array(
[[0.3, 0.7],
[-0.6, 0.3],
[-0.1, -0.8],
[0.1, -0.45]]
)
t = np.array([1,0,0,1])
#bobot awal
w = np.array([0.8,-0.5])
beta = 0.5
E = np.zeros_like(t) #ukuran matriks nol sama dengan ukuran t
for j in range(4):
print("Iterasi-"+str(j+1)+" untuk")
u = x[j].dot(w)
print(x[j])
y = aktivasi(u)
print("u = ",u)
print("y = ",y)
E = t[j] - y
print("E = ", E)
w = w + beta*x[j]*E
print("Bobot hasil perbaikan:")
print(w)
print("\n")