Esmaeilkiani commited on
Commit
b31d818
1 Parent(s): 494ed19

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -76
app.py CHANGED
@@ -1,89 +1,67 @@
1
- import streamlit as st
2
  import pandas as pd
3
- import matplotlib.pyplot as plt
4
- from datasets import load_dataset
 
 
 
 
 
 
5
 
6
- # Load the dataset from Hugging Face
7
- dataset = load_dataset('Esmaeilkianii/croplogdehkhoda', split='train')
8
- data = pd.DataFrame(dataset)
9
 
10
- # Split the data into different sections based on columns or logic
11
- # Assuming the dataset contains the combined information for all four files
 
 
12
 
13
- # Separate different sections of the data
14
- cleaned_data = data[['مزرعه', 'year', 'yield', 'age', 'variety', 'area']] # Example farm performance data
15
- veg_index_data = data[['مزرعه', 'date', 'mean_VH', 'mean_VV']] # Example vegetation index data
16
- weather_data = data[['سال', 'ماه', 'روز', 'تاریخ', 'درجه حرارت حداقل', 'درجه حرارت حداکثر', 'میانگین درجه حرارت',
17
- 'حداقل رطوبت نسبی (درصد)', 'حداکثر رطوبت نسبی (درصد)', 'میانگین رطوبت نسبی (درصد)',
18
- 'میزان تبخیر روزانه (میلیمتر)', 'میزان بارندگی (میلیمتر)', 'میزان ساعت افتابی']] # Weather data
19
- performance_estimation_data = data[['مزرعه', 'yield', 'tonnage']] # Example yield and tonnage prediction
20
 
21
- # Function to search for farm performance
22
- def search_farm(farm_name):
23
- # Filter the farm's data for recent years (1392-1402)
24
- farm_data = cleaned_data[cleaned_data['مزرعه'] == farm_name]
25
- farm_performance = farm_data[(farm_data['year'] >= 1392) & (farm_data['year'] <= 1402)]
26
-
27
- # Create a time-series chart for the vegetation index (mean_VH, mean_VV)
28
- veg_data = veg_index_data[veg_index_data['مزرعه'] == farm_name]
29
-
30
- # Plotting vegetation index trends
31
- fig, ax = plt.subplots(figsize=(10,5))
32
- ax.plot(veg_data['date'], veg_data['mean_VH'], label='mean_VH')
33
- ax.plot(veg_data['date'], veg_data['mean_VV'], label='mean_VV')
34
- ax.set_xlabel('Date')
35
- ax.set_ylabel('Vegetation Index')
36
- ax.set_title(f'Vegetation Index Trends for {farm_name}')
37
- ax.legend()
38
- plt.xticks(rotation=45)
39
-
40
- return farm_performance, fig
41
 
42
- # Function to display weather data
43
- def show_weather_data():
44
- st.dataframe(weather_data)
 
 
 
45
 
46
- # Function to predict farm performance (yield and tonnage)
47
- def predict_performance(farm_name):
48
- prediction_data = performance_estimation_data[performance_estimation_data['مزرعه'] == farm_name]
49
-
50
- if prediction_data.empty:
51
- st.write("مزرعه مورد نظر پیدا نشد.")
52
- else:
53
- yield_value = prediction_data['yield'].values[0]
54
- tonnage = prediction_data['tonnage'].values[0] # Adjust based on your actual column name
55
- st.write(f"تن در هکتار: {yield_value}")
56
- st.write(f"تناژ: {tonnage}")
57
 
58
- # Streamlit app
59
- st.title("Farm Performance Dashboard")
60
 
61
- # Sidebar menu
62
- menu = st.sidebar.selectbox("انتخاب منو", ["Farm Search", "دیتابیس هواشناسی", "پیش بینی عملکرد"])
63
 
64
- # Farm Search section
65
- if menu == "Farm Search":
66
- st.header("Search for Farm Performance")
67
- farm_name = st.text_input("نام مزرعه را وارد کنید")
68
-
69
- if st.button("Search"):
70
- farm_performance, veg_chart = search_farm(farm_name)
71
- st.write("Farm Performance (1392-1402):")
72
- st.dataframe(farm_performance)
73
- st.write("Vegetation Index Time Series:")
74
- st.pyplot(veg_chart)
75
 
76
- # Weather Database section
77
- elif menu == "دیتابیس هواشناسی":
78
- st.header("Weather Data")
79
- st.write("م��اهده داده‌های هواشناسی:")
80
- show_weather_data()
81
 
82
- # Performance Prediction section
83
- elif menu == "پیش بینی عملکرد":
84
- st.header("Predict Farm Performance")
85
- farm_name_prediction = st.text_input("نام مزرعه برای پیش بینی")
86
-
87
- if st.button("پیش بینی"):
88
- predict_performance(farm_name_prediction)
89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import pandas as pd
2
+ import numpy as np
3
+ from sklearn.model_selection import train_test_split
4
+ from sklearn.preprocessing import StandardScaler, OneHotEncoder
5
+ from sklearn.compose import ColumnTransformer
6
+ from sklearn.pipeline import Pipeline
7
+ from sklearn.ensemble import RandomForestRegressor
8
+ from sklearn.metrics import mean_squared_error, r2_score
9
+ import joblib
10
 
11
+ # Load the data
12
+ data = pd.read_csv('sugar_cane_data.csv')
 
13
 
14
+ # Data preprocessing
15
+ data['Farm'] = data['Farm'].astype(str)
16
+ data['Variety'] = data['Variety'].fillna('Unknown')
17
+ data['Age'] = data['Age'].fillna('Unknown')
18
 
19
+ # Split features and target variables
20
+ X = data[['Farm', 'Variety', 'Age']]
21
+ y = data[['Brix', 'Purity', 'Pol', 'RS']]
 
 
 
 
22
 
23
+ # Split the data into training and testing sets
24
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
+ # Create preprocessing steps
27
+ preprocessor = ColumnTransformer(
28
+ transformers=[
29
+ ('num', StandardScaler(), []),
30
+ ('cat', OneHotEncoder(handle_unknown='ignore'), ['Farm', 'Variety', 'Age'])
31
+ ])
32
 
33
+ # Create a pipeline with preprocessor and random forest regressor
34
+ model = Pipeline([
35
+ ('preprocessor', preprocessor),
36
+ ('regressor', RandomForestRegressor(n_estimators=100, random_state=42))
37
+ ])
 
 
 
 
 
 
38
 
39
+ # Fit the model
40
+ model.fit(X_train, y_train)
41
 
42
+ # Make predictions on the test set
43
+ y_pred = model.predict(X_test)
44
 
45
+ # Evaluate the model
46
+ mse = mean_squared_error(y_test, y_pred)
47
+ r2 = r2_score(y_test, y_pred)
 
 
 
 
 
 
 
 
48
 
49
+ print(f"Mean Squared Error: {mse}")
50
+ print(f"R-squared Score: {r2}")
 
 
 
51
 
52
+ # Save the model
53
+ joblib.dump(model, 'sugar_cane_model.joblib')
 
 
 
 
 
54
 
55
+ # Function to make predictions for new data
56
+ def predict_sugar_cane_properties(farm, variety, age):
57
+ new_data = pd.DataFrame({'Farm': [farm], 'Variety': [variety], 'Age': [age]})
58
+ prediction = model.predict(new_data)
59
+ return {
60
+ 'Brix': prediction[0][0],
61
+ 'Purity': prediction[0][1],
62
+ 'Pol': prediction[0][2],
63
+ 'RS': prediction[0][3]
64
+ }
65
+
66
+ # Example usage
67
+ print(predict_sugar_cane_properties('01-18', 'CP69', 'P'))