Last active
January 21, 2022 12:10
-
-
Save tiagodavi/a905abeaf4d1f92c21f9df9043d196fe to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule NxDiabetes do | |
@moduledoc """ | |
Documentation for `NxDiabetes`. | |
DataSet: | |
https://www.kaggle.com/uciml/pima-indians-diabetes-database | |
""" | |
alias NimbleCSV.RFC4180, as: CSV | |
require Axon | |
@doc """ | |
Hello world. | |
## Examples | |
iex> NxDiabetes.run() | |
""" | |
def run do | |
data = load_data() | |
features = 8 | |
test_size = 20 | |
%{x: x, y: y} = build_x_y(data, features) | |
{x_train, x_test, y_train, y_test} = train_test_split(x, y, test_size) | |
input = Axon.input({nil, features}) | |
model = | |
input | |
|> Axon.dense(features, activation: :relu) | |
|> Axon.dense(features, activation: :relu) | |
|> Axon.dense(1, activation: :sigmoid) | |
trained_model = | |
model | |
|> Axon.Loop.trainer(:binary_cross_entropy, :adam) | |
|> Axon.Loop.run([{x_train, y_train}], epochs: 10, compiler: EXLA) | |
result = | |
model | |
|> Axon.predict(trained_model, x_test, compiler: EXLA) | |
|> Axon.Metrics.accuracy(y_test) | |
IO.inspect result | |
end | |
defp load_data do | |
"diabetes.csv" | |
|> File.stream! | |
|> CSV.parse_stream() | |
|> Stream.map(fn [pregnancies, glucose, blood_pressure, skin_thickness, insulin, bmi, dpf, age, outcome] -> | |
[ | |
String.to_integer(pregnancies), | |
String.to_integer(glucose), | |
String.to_integer(blood_pressure), | |
String.to_integer(skin_thickness), | |
String.to_integer(insulin), | |
Float.parse(bmi) |> elem(0), | |
Float.parse(dpf) |> elem(0), | |
String.to_integer(age), | |
String.to_integer(outcome) | |
] | |
end) | |
|> Enum.to_list() | |
end | |
defp train_test_split(x, y, size) do | |
x_total = length(x) | |
y_total = length(y) | |
x_perc = div((size * x_total), 100) | |
y_perc = div((size * y_total), 100) | |
{x_test, x_train} = | |
x | |
|> Enum.shuffle() | |
|> Enum.split(x_perc) | |
{y_test, y_train} = | |
y | |
|> Enum.shuffle() | |
|> Enum.split(y_perc) | |
{ | |
Nx.tensor(x_train), | |
Nx.tensor(x_test), | |
Nx.tensor(y_train) |> Nx.new_axis(-1), | |
Nx.tensor(y_test) |> Nx.new_axis(-1) | |
} | |
end | |
defp build_x_y(data, pop_at) do | |
Enum.reduce(data, %{x: [], y: []}, fn row, acc -> | |
{y, x} = List.pop_at(row, pop_at) | |
%{ acc | x: [x | acc.x], y: [y | acc.y] } | |
end) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment