# -*- coding: utf-8 -*-
"""cropNN.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1e-5E0x8UEGT_3np2iVaiqdDZ3u8kpiV-
"""

from google.colab import drive
drive.mount('/content/drive')

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

df= pd.read_csv('/content/drive/My Drive/Datasets/crop.csv')

df.head()

labelss= df['Crop'].unique()
dummy_class = []
mapper = {}
for i, cl in enumerate(labelss):
    mapper[cl] = i
    dummy_class.append(f"Crop_{i}")

df = df.replace(mapper)
df = pd.get_dummies(df, columns=['Crop'])

df.head()

train_df = df.sample(frac=0.85, random_state=1)
valid_df = df.drop(train_df.index)
train_df.head()

valid_df

train_labels_df = train_df.iloc[:,3:]
valid_labels_df = valid_df.iloc[:,3:]

stats = train_df.describe().transpose()
train_df = (train_df-stats['mean'])/stats['std']
valid_df = (valid_df-stats['mean'])/stats['std']

train_data = train_df.to_numpy()
valid_data = valid_df.to_numpy()

train_labels = train_labels_df.to_numpy()
valid_labels = valid_labels_df.to_numpy()

prediction_data = train_df.iloc[0]
result = train_labels_df.iloc[0]
prediction_data

def prepare_dataset(data, labels, batch, shuffle_buffer):
    dataset = tf.data.Dataset.from_tensor_slices((data, labels))
    dataset = dataset.shuffle(shuffle_buffer)
    dataset = dataset.batch(batch).prefetch(1)
    return dataset

batch_size = 15
buffer = 15
train_dataset = prepare_dataset(train_data, train_labels, batch_size, buffer)
valid_dataset = prepare_dataset(valid_data, valid_labels, batch_size, buffer)

tf.keras.backend.set_floatx('float64')

model = tf.keras.Sequential([
    tf.keras.layers.Dense(512, activation='relu'),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(3, activation='softmax')
])

model.compile(
    loss=tf.keras.losses.categorical_crossentropy,
    optimizer=tf.keras.optimizers.SGD(),
    metrics=['accuracy', 'mae']
)

history = model.fit(
    train_dataset,
    epochs=40,
    validation_data=valid_dataset
)

plots = ['accuracy', 'mae', 'loss']
for plot in plots:
    metric = history.history[plot]
    val_metric = history.history[f"val_{plot}"]
    epochs = range(len(metric))

    plt.figure(figsize=(15, 10))
    plt.plot(epochs, metric, label=f"Training {plot}")
    plt.plot(epochs, val_metric, label=f"Validation {plot}")
    plt.legend()
    plt.title(f"Training and Validation for {plot}")
    plt.show()

prediction_data = prediction_data.values[np.newaxis]
prediction = model.predict(prediction_data)
print(f"Expected Result: {np.argmax(result)}, Prediction Result: {np.argmax(prediction)}")

model.save('crop_prediction.h5')



tflite_model = tf.keras.models.load_model('/content/crop_prediction.h5')
converter = tf.lite.TFLiteConverter.from_keras_model(tflite_model)

converter.allow_custom_ops = True

tflite_models = converter.convert()

open("cropNN.tflite","wb").write(tflite_models)
07888072bf18fd34f3eecadb572603a4bef6a34c
<mask token>


def prepare_dataset(data, labels, batch, shuffle_buffer):
    dataset = tf.data.Dataset.from_tensor_slices((data, labels))
    dataset = dataset.shuffle(shuffle_buffer)
    dataset = dataset.batch(batch).prefetch(1)
    return dataset


<mask token>

<mask token>
drive.mount('/content/drive')
<mask token>
df.head()
<mask token>
for i, cl in enumerate(labelss):
    mapper[cl] = i
    dummy_class.append(f'Crop_{i}')
<mask token>
df.head()
<mask token>
train_df.head()
valid_df
<mask token>
prediction_data


def prepare_dataset(data, labels, batch, shuffle_buffer):
    dataset = tf.data.Dataset.from_tensor_slices((data, labels))
    dataset = dataset.shuffle(shuffle_buffer)
    dataset = dataset.batch(batch).prefetch(1)
    return dataset


<mask token>
tf.keras.backend.set_floatx('float64')
<mask token>
model.compile(loss=tf.keras.losses.categorical_crossentropy, optimizer=tf.
    keras.optimizers.SGD(), metrics=['accuracy', 'mae'])
<mask token>
for plot in plots:
    metric = history.history[plot]
    val_metric = history.history[f'val_{plot}']
    epochs = range(len(metric))
    plt.figure(figsize=(15, 10))
    plt.plot(epochs, metric, label=f'Training {plot}')
    plt.plot(epochs, val_metric, label=f'Validation {plot}')
    plt.legend()
    plt.title(f'Training and Validation for {plot}')
    plt.show()
<mask token>
print(
    f'Expected Result: {np.argmax(result)}, Prediction Result: {np.argmax(prediction)}'
    )
model.save('crop_prediction.h5')
<mask token>
open('cropNN.tflite', 'wb').write(tflite_models)

<mask token>
drive.mount('/content/drive')
<mask token>
df = pd.read_csv('/content/drive/My Drive/Datasets/crop.csv')
df.head()
labelss = df['Crop'].unique()
dummy_class = []
mapper = {}
for i, cl in enumerate(labelss):
    mapper[cl] = i
    dummy_class.append(f'Crop_{i}')
df = df.replace(mapper)
df = pd.get_dummies(df, columns=['Crop'])
df.head()
train_df = df.sample(frac=0.85, random_state=1)
valid_df = df.drop(train_df.index)
train_df.head()
valid_df
train_labels_df = train_df.iloc[:, 3:]
valid_labels_df = valid_df.iloc[:, 3:]
stats = train_df.describe().transpose()
train_df = (train_df - stats['mean']) / stats['std']
valid_df = (valid_df - stats['mean']) / stats['std']
train_data = train_df.to_numpy()
valid_data = valid_df.to_numpy()
train_labels = train_labels_df.to_numpy()
valid_labels = valid_labels_df.to_numpy()
prediction_data = train_df.iloc[0]
result = train_labels_df.iloc[0]
prediction_data


def prepare_dataset(data, labels, batch, shuffle_buffer):
    dataset = tf.data.Dataset.from_tensor_slices((data, labels))
    dataset = dataset.shuffle(shuffle_buffer)
    dataset = dataset.batch(batch).prefetch(1)
    return dataset


batch_size = 15
buffer = 15
train_dataset = prepare_dataset(train_data, train_labels, batch_size, buffer)
valid_dataset = prepare_dataset(valid_data, valid_labels, batch_size, buffer)
tf.keras.backend.set_floatx('float64')
model = tf.keras.Sequential([tf.keras.layers.Dense(512, activation='relu'),
    tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(3,
    activation='softmax')])
model.compile(loss=tf.keras.losses.categorical_crossentropy, optimizer=tf.
    keras.optimizers.SGD(), metrics=['accuracy', 'mae'])
history = model.fit(train_dataset, epochs=40, validation_data=valid_dataset)
plots = ['accuracy', 'mae', 'loss']
for plot in plots:
    metric = history.history[plot]
    val_metric = history.history[f'val_{plot}']
    epochs = range(len(metric))
    plt.figure(figsize=(15, 10))
    plt.plot(epochs, metric, label=f'Training {plot}')
    plt.plot(epochs, val_metric, label=f'Validation {plot}')
    plt.legend()
    plt.title(f'Training and Validation for {plot}')
    plt.show()
prediction_data = prediction_data.values[np.newaxis]
prediction = model.predict(prediction_data)
print(
    f'Expected Result: {np.argmax(result)}, Prediction Result: {np.argmax(prediction)}'
    )
model.save('crop_prediction.h5')
tflite_model = tf.keras.models.load_model('/content/crop_prediction.h5')
converter = tf.lite.TFLiteConverter.from_keras_model(tflite_model)
converter.allow_custom_ops = True
tflite_models = converter.convert()
open('cropNN.tflite', 'wb').write(tflite_models)

<mask token>
from google.colab import drive
drive.mount('/content/drive')
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
df = pd.read_csv('/content/drive/My Drive/Datasets/crop.csv')
df.head()
labelss = df['Crop'].unique()
dummy_class = []
mapper = {}
for i, cl in enumerate(labelss):
    mapper[cl] = i
    dummy_class.append(f'Crop_{i}')
df = df.replace(mapper)
df = pd.get_dummies(df, columns=['Crop'])
df.head()
train_df = df.sample(frac=0.85, random_state=1)
valid_df = df.drop(train_df.index)
train_df.head()
valid_df
train_labels_df = train_df.iloc[:, 3:]
valid_labels_df = valid_df.iloc[:, 3:]
stats = train_df.describe().transpose()
train_df = (train_df - stats['mean']) / stats['std']
valid_df = (valid_df - stats['mean']) / stats['std']
train_data = train_df.to_numpy()
valid_data = valid_df.to_numpy()
train_labels = train_labels_df.to_numpy()
valid_labels = valid_labels_df.to_numpy()
prediction_data = train_df.iloc[0]
result = train_labels_df.iloc[0]
prediction_data


def prepare_dataset(data, labels, batch, shuffle_buffer):
    dataset = tf.data.Dataset.from_tensor_slices((data, labels))
    dataset = dataset.shuffle(shuffle_buffer)
    dataset = dataset.batch(batch).prefetch(1)
    return dataset


batch_size = 15
buffer = 15
train_dataset = prepare_dataset(train_data, train_labels, batch_size, buffer)
valid_dataset = prepare_dataset(valid_data, valid_labels, batch_size, buffer)
tf.keras.backend.set_floatx('float64')
model = tf.keras.Sequential([tf.keras.layers.Dense(512, activation='relu'),
    tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(3,
    activation='softmax')])
model.compile(loss=tf.keras.losses.categorical_crossentropy, optimizer=tf.
    keras.optimizers.SGD(), metrics=['accuracy', 'mae'])
history = model.fit(train_dataset, epochs=40, validation_data=valid_dataset)
plots = ['accuracy', 'mae', 'loss']
for plot in plots:
    metric = history.history[plot]
    val_metric = history.history[f'val_{plot}']
    epochs = range(len(metric))
    plt.figure(figsize=(15, 10))
    plt.plot(epochs, metric, label=f'Training {plot}')
    plt.plot(epochs, val_metric, label=f'Validation {plot}')
    plt.legend()
    plt.title(f'Training and Validation for {plot}')
    plt.show()
prediction_data = prediction_data.values[np.newaxis]
prediction = model.predict(prediction_data)
print(
    f'Expected Result: {np.argmax(result)}, Prediction Result: {np.argmax(prediction)}'
    )
model.save('crop_prediction.h5')
tflite_model = tf.keras.models.load_model('/content/crop_prediction.h5')
converter = tf.lite.TFLiteConverter.from_keras_model(tflite_model)
converter.allow_custom_ops = True
tflite_models = converter.convert()
open('cropNN.tflite', 'wb').write(tflite_models)

# -*- coding: utf-8 -*-
"""cropNN.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1e-5E0x8UEGT_3np2iVaiqdDZ3u8kpiV-
"""

from google.colab import drive
drive.mount('/content/drive')

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

df= pd.read_csv('/content/drive/My Drive/Datasets/crop.csv')

df.head()

labelss= df['Crop'].unique()
dummy_class = []
mapper = {}
for i, cl in enumerate(labelss):
    mapper[cl] = i
    dummy_class.append(f"Crop_{i}")

df = df.replace(mapper)
df = pd.get_dummies(df, columns=['Crop'])

df.head()

train_df = df.sample(frac=0.85, random_state=1)
valid_df = df.drop(train_df.index)
train_df.head()

valid_df

train_labels_df = train_df.iloc[:,3:]
valid_labels_df = valid_df.iloc[:,3:]

stats = train_df.describe().transpose()
train_df = (train_df-stats['mean'])/stats['std']
valid_df = (valid_df-stats['mean'])/stats['std']

train_data = train_df.to_numpy()
valid_data = valid_df.to_numpy()

train_labels = train_labels_df.to_numpy()
valid_labels = valid_labels_df.to_numpy()

prediction_data = train_df.iloc[0]
result = train_labels_df.iloc[0]
prediction_data

def prepare_dataset(data, labels, batch, shuffle_buffer):
    dataset = tf.data.Dataset.from_tensor_slices((data, labels))
    dataset = dataset.shuffle(shuffle_buffer)
    dataset = dataset.batch(batch).prefetch(1)
    return dataset

batch_size = 15
buffer = 15
train_dataset = prepare_dataset(train_data, train_labels, batch_size, buffer)
valid_dataset = prepare_dataset(valid_data, valid_labels, batch_size, buffer)

tf.keras.backend.set_floatx('float64')

model = tf.keras.Sequential([
    tf.keras.layers.Dense(512, activation='relu'),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(3, activation='softmax')
])

model.compile(
    loss=tf.keras.losses.categorical_crossentropy,
    optimizer=tf.keras.optimizers.SGD(),
    metrics=['accuracy', 'mae']
)

history = model.fit(
    train_dataset,
    epochs=40,
    validation_data=valid_dataset
)

plots = ['accuracy', 'mae', 'loss']
for plot in plots:
    metric = history.history[plot]
    val_metric = history.history[f"val_{plot}"]
    epochs = range(len(metric))

    plt.figure(figsize=(15, 10))
    plt.plot(epochs, metric, label=f"Training {plot}")
    plt.plot(epochs, val_metric, label=f"Validation {plot}")
    plt.legend()
    plt.title(f"Training and Validation for {plot}")
    plt.show()

prediction_data = prediction_data.values[np.newaxis]
prediction = model.predict(prediction_data)
print(f"Expected Result: {np.argmax(result)}, Prediction Result: {np.argmax(prediction)}")

model.save('crop_prediction.h5')



tflite_model = tf.keras.models.load_model('/content/crop_prediction.h5')
converter = tf.lite.TFLiteConverter.from_keras_model(tflite_model)

converter.allow_custom_ops = True

tflite_models = converter.convert()

open("cropNN.tflite","wb").write(tflite_models)