Jump to content

Perceptron: Difference between revisions

Add Julia language
(Add Julia language)
Line 388:
 
Well, it seems I cannot upload an image :(
 
=={{header|Julia}}==
<lang julia># file module.jl
 
module SimplePerceptrons
 
# default activation function
step(x) = x > 0 ? 1 : -1
 
mutable struct Perceptron{T, F}
weights::Vector{T}
lr::T
activate::F
end
 
Perceptron{T}(n::Integer, lr = 0.01, f::Function = step) where T =
Perceptron{T, typeof(f)}(2 .* rand(n + 1) .- 1, lr, f)
Perceptron(args...) = Perceptron{Float64}(args...)
 
@views predict(p::Perceptron, x::AbstractVector) = p.activate(p.weights[1] + x' * p.weights[2:end])
@views predict(p::Perceptron, X::AbstractMatrix) = p.activate.(p.weights[1] .+ X * p.weights[2:end])
 
function train!(p::Perceptron, X::AbstractMatrix, y::AbstractVector; epochs::Integer = 100)
for _ in Base.OneTo(epochs)
yhat = predict(p, X)
err = y .- yhat
ΔX = p.lr .* err .* X
for ind in axes(ΔX, 1)
p.weights[1] += err[ind]
p.weights[2:end] .+= ΔX[ind, :]
end
end
return p
end
 
accuracy(p, X::AbstractMatrix, y::AbstractVector) = count(y .== predict(p, X)) / length(y)
 
end # module SimplePerceptrons
</lang>
 
<lang julia># file _.jl
 
const SP = include("module.jl")
 
p = SP.Perceptron(2, 0.1)
 
a, b = 0.5, 1
X = rand(1000, 2)
y = map(x -> x[2] > a + b * x[1] ? 1 : -1, eachrow(X))
 
# Accuracy
@show SP.accuracy(p, X, y)
 
# Train
SP.train!(p, X, y, epochs = 1000)
 
ahat, bhat = p.weights[1] / p.weights[2], -p.weights[3] / p.weights[2]
 
using Plots
 
scatter(X[:, 1], X[:, 2], markercolor = map(x -> x == 1 ? :red : :blue, y))
Plots.abline!(b, a, label = "real line", linecolor = :red, linewidth = 2)
 
SP.train!(p, X, y, epochs = 1000)
ahat, bhat = p.weights[1] / p.weights[2], -p.weights[3] / p.weights[2]
Plots.abline!(bhat, ahat, label = "predicted line")
</lang>
 
=={{header|Kotlin}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.