0% found this document useful (0 votes)
27 views42 pages

Mini Project Reportgg1

This project aims to build a weather prediction system using machine learning algorithms. It will predict weather parameters like temperature, humidity and wind based on past weather data. Linear regression algorithms will be used to build a model that maps past observed weather patterns to predict future weather.

Uploaded by

Rupanshi Rohilla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views42 pages

Mini Project Reportgg1

This project aims to build a weather prediction system using machine learning algorithms. It will predict weather parameters like temperature, humidity and wind based on past weather data. Linear regression algorithms will be used to build a model that maps past observed weather patterns to predict future weather.

Uploaded by

Rupanshi Rohilla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 42

AJAY KUMAR GARG ENGINEERING COLLEGE

27th KM STONE DELHI-HAPUR BYPASS ROAD, P.O. ADHYATMIK NAGAR


GHAZIABAD-201009

A
MINI PROJECT REPORT
ON

ACCUWEATHER

Submitted by

Name: GAURI GOYAL Name:ISHITA SINGHAL Name:RUPANSHI


ROHILLA
nd
Year: 2nd Year:2 Year:2nd
Semester: IIIrd Semester:IIIrd Semester:IIIrd
Section: CSE AIML- 2 Section:CSE AIML-2 Section:CSE AIML-2
Branch: CSE AIML Branch:CSE AIML Branch:CSE AIML
Univ. Roll No.-
2100270130073 2100270130087
Date: 7th February 2023
AJAY KUMAR GARG ENGINEERING COLLEGE
27TH KM STONE DELHI- HAPUR BYPASS ROAD, P.O. ADHYATMIK NAGAR GHAZIABAD-
201009

MINI PROJECT CERTIFICATE

This is to certify that GAURI GOYAL, ISHITA SINGHAL and RUPANSHI ROHILLA,
student of AJAY KUMAR GARG ENGINEERING COLLEGE B. Tech IIrd year CSE
AIML branch, has completed Mini Project on ACCUWEATHER in the duration 07th
September 2022 to 07th February 2023.

Ms. Harnit Saini Dr Sunita Yadav


Faculty Mini Project Lab HoD, CSE
Abstract

Weather prediction is the


application of science and
technology to predict the state
of the
atmosphere for a given location.
Here this system will predict
weather based on parameters such
as temperature, humidity and
wind. This system is a web
application with effective
graphical
user interface. To predict the
future’s weather condition, the
variation in the conditions in past
years must be utilized. The
probability that it will match
within the span of adjacent
fortnight of
previous year is very high .We
have proposed the use of linear
regression for weather prediction
system with parameters such as
temperature, humidity and wind. It
will predict weather based on
previous record therefore this
prediction will prove reliable.
This system can be used in Air
Traffic, Marine, Agriculture,
Forestry, Military, and Navy etc.
Weather prediction is the
application of science and
technology to predict the state
of the
atmosphere for a given location.
Here this system will predict
weather based on parameters such
as temperature, humidity and
wind. This system is a web
application with effective
graphical
user interface. To predict the
future’s weather condition, the
variation in the conditions in past
years must be utilized. The
probability that it will match
within the span of adjacent
fortnight of
previous year is very high .We
have proposed the use of linear
regression for weather prediction
system with parameters such as
temperature, humidity and wind. It
will predict weather based on
previous record therefore this
prediction will prove reliable.
This system can be used in Air
Traffic, Marine, Agriculture,
Forestry, Military, and Navy etc.
Weather prediction is the
application of science and
technology to predict the state
of the
atmosphere for a given location.
Here this system will predict
weather based on parameters such
as temperature, humidity and
wind. This system is a web
application with effective
graphical
user interface. To predict the
future’s weather condition, the
variation in the conditions in past
years must be utilized. The
probability that it will match
within the span of adjacent
fortnight of
previous year is very high .We
have proposed the use of linear
regression for weather prediction
system with parameters such as
temperature, humidity and wind. It
will predict weather based on
previous record therefore this
prediction will prove reliable.
This system can be used in Air
Traffic, Marine, Agriculture,
Forestry, Military, and Navy etc.
Weather prediction is the
application of science and
technology to predict the state
of the
atmosphere for a given location.
Here this system will predict
weather based on parameters such
as temperature, humidity and
wind. This system is a web
application with effective
graphical
user interface. To predict the
future’s weather condition, the
variation in the conditions in past
years must be utilized. The
probability that it will match
within the span of adjacent
fortnight of
previous year is very high .We
have proposed the use of linear
regression for weather prediction
system with parameters such as
temperature, humidity and wind. It
will predict weather based on
previous record therefore this
prediction will prove reliable.
This system can be used in Air
Traffic, Marine, Agriculture,
Forestry, Military, and Navy etc.
AccuWeather is the application of science and technology to predict the state of
the atmosphere for a given location. Here this system will predict weather based on
parameters such as temperature, humidity and wind. This system is a web
application with effective graphical user interface. To predict the future’s weather
condition, the variation in the conditions in past years must be utilized. The probability
that it will match within the span of adjacent fortnight of previous year is very high .We
have proposed the use of linear regression for weather prediction system with parameters
such as temperature, humidity and wind. It will predict weather based on previous record
therefore this prediction will prove reliable. This system can be used in Air Traffic,
Marine, Agriculture, Forestry, Military, and Navy etc.
Acknowledgement

We would like to express our deepest thanks to Dr Shashank Sahu, an mini project
advisor, for his cooperative attitude and consistent guidance, due to which we were able to
complete our project successfully. We would also like to thank Ms. Harnit Saini ma’am
for her support and help.

We would like to express our sincere gratitude to Dr Sunita Yadav (H.O.D. CSE
Department), Ajay Kumar Garg Engineering College, Ghaziabad and Dr R. K. Aggarwal
(Director General), Ajay Kumar Garg Engineering College for allowing us to pursue our
choice of project. They gave us valuable guidance and support.

We wish to thank various people in my college, Ajay Kumar Garg Engineering College,
for their valuable guidance. We received practical as well as theoretical knowledge and
experience in this project. Finally, last but by no means least, a paper is not enough for us
to express the support and guidance we received from them.

Gauri Goyal , Ishita Singhal, Rupanshi Rohilla


2nd Year CSE AIML
Contents
Topics Page No.
Mini Project Certificate i
Abstract ii
Acknowledgement iii
Contents iv

List of Figures 1
CHAPTER 1: INTRODUCTION TO PROJECT 2
CHAPTER 2: SOFTWARE AND HARDWARE REQUIREMENT 4
CHAPTER 3: DESIGN AND TESTING 5
CHAPTER 4: RESULTS AND DISCUSSION 7
References 23
Appendix 24
List of Figures

Fig No. Name Page No

Fig 4.1 Intro Screen 7


Fig 4.2 Location 8
Fig 4.3 Search 9
Fig 4.4 Output 10
CHAPTER 1: INTRODUCTION

Weather forecasting is the task of


predicting the state of the
atmosphere at a future time and a
specified location. Traditionally,
this has been done through
physical simulations in which the
atmosphere is modeled as a fluid.
The present state of the
atmosphere is sampled, and the
future
state is computed by numerically
solving the equations of fluid
dynamics and thermodynamics.
However, the system of ordinary
differential equations that govern
this physical model is
unstable under perturbations, and
uncertainties in the initial
measurements of the
atmospheric
conditions and an incomplete
understanding of complex
atmospheric processes restrict the
extent
of accurate weather forecasting
to a 10 day period, beyond
which weather forecasts are
significantly unreliable. Machine
learning, on the contrary, is
relatively robust to perturbations
and doesn’t require a complete
understanding of the physical
processes that govern the
atmosphere. Therefore, machine
learning may represent a viable
alternative to physical models in
weather forecasting.
Machine learning is the ability
of computer to learn without
being explicitly programmed. It
allows machines to find hidden
patterns and insights. In supervised
learning, we build a model
based on labeled training data. The
model is then used for mapping
new examples. So, based on
the observed weather patterns
from the past, a model can be
built and used to predict the
weather.
This project work focuses on
solving the weather prediction
anomalies and in-efficiency based
on linear regression algorithms and
to formulate an efficient weather
prediction model based on
the linear regression algorithms
Weather forecasting is the task of predicting the state of the atmosphere at a future time
and a specified location. Traditionally, this has been done through physical simulations
in which the atmosphere is modeled as a fluid. The present state of the atmosphere is
sampled, and the future state is computed by numerically solving the equations of fluid
dynamics and thermodynamics. However, the system of ordinary differential
equations that govern this physical model is unstable under perturbations, and
uncertainties in the initial measurements of the atmospheric conditions and an
incomplete understanding of complex atmospheric processes restrict the extent of
accurate weather forecasting to a 10 day period, beyond which weather forecasts
are significantly unreliable. Machine learning, on the contrary, is relatively robust to
perturbations and doesn’t require a complete understanding of the physical processes
that govern the atmosphere. Therefore, machine learning may represent a viable
alternative to physical models in weather forecasting. Machine learning is the ability of
computer to learn without being explicitly programmed. It allows machines to find
hidden patterns and insights. In supervised learning, we build a model based on labeled
training data. The model is then used for mapping new examples. So, based on the
observed weather patterns from the past, a model can be built and used to predict
the weather. This project work focuses on solving the weather prediction anomalies and
in-efficiency based on linear regression algorithms and to formulate an efficient weather
prediction model based on the linear regression algorithms.

Methodology used

In a developing country and an economy like India where major population is


dependent on agriculture, weather conditions play an important and vital role in
economic growth of the overall nation. So, weather prediction should be more precise
and accurate. Weather parameters are collected from the open source . The data used in
this project is of the years 2013-2019. The programming language used is ‘Python’. The
weather is predicted using various indices like temperature, humidity and dew-
point. Temperature is the measure of hotness or coldness, generally measured using
thermometer. Units of temperature most frequently used are Celsius and Fahrenheit.
We have used maximum and minimum temperature values along with normal
temperature as different index values for prediction of the weather. Humidity is the
quantity of water vapor present in the atmosphere. It is a relative quantity. Dew point is
the temperature of the atmosphere (which varies according to pressure and
humidity) below which water droplets begin to condense and dew is formed.

Technologies Used

Machine learning – Linear Regression Linear regression is the most basic and frequently
used predictive model for analysis. Regression estimates are generally used to describe the
data and elucidate relationship between one or more independent and dependent
variables. Linear regression finds the best-fit through the points, graphically. The
best-fit line through the points is known as the regression line.
Javascript- JavaScript is a lightweight, interpreted programming language. It is
designed for creating network-centric applications. It is complimentary to and integrated
with Java. JavaScript is very easy to implement because it is integrated with HTML. It is
open and cross-platform. Once you learnt Javascript, it helps you developing great
front-end as well as back-end softwares using different Javascript based frameworks
like jQuery, Node.JS etc. JavaScript is used to create interactive websites. It is mainly
used for: o Client-side validation o Displaying pop-up windows and dialog boxes

Json- JSON (JavaScript Object Notation) is a lightweight format that is used for data
interchanging. It is based on a subset of JavaScript language. It has been the preferred
format because it is much more lightweight JSON is built on two structures:
 A collection of name/value pairs. In various languages, this is realized as an
object, record, structure, dictionary, hash table, keyed list, or associative array.
 An ordered list of values. In most languages, this is realized as an array, vector, list, or
sequence.

ReactJS- ReactJS is a declarative, efficient, and flexible JavaScript library for building
reusable UI components. It is an open-source, component-based front-end library which
is responsible only for the view layer of the application. It was initially developed and
maintained by Facebook and later used in its products like WhatsApp & Instagram. The
main objective of ReactJS is to develop User Interfaces (UI) that improves the speed of
the apps. It uses virtual DOM (JavaScript object), which improves the performance of the
app. The JavaScript virtual DOM is faster than the regular DOM. We can use ReactJS on
the client and server-side as well as with other frameworks. It uses component and data
patterns that improve readability and helps to maintain larger apps.

Adobe After Effects- Adobe After Effects is a digital visual effect, motion graphics,
and compositing application developed by Adobe Systems and used in the post-
production process of film making and television production. Among other things,
After Effects can be used for keying, tracking, compositing, and animation. It also
functions as a very basic non-linear editor, audio editor, and media transcoder. After
Effects has extensive plug-in support; a broad range of third-party plug-ins are available.
A variety of plug-in styles exist, such as particle systems for realistic effects for rain,
snow, fire, etc. With or without third-party plug-ins, After Effects can render 3D effects.
Some of these 3D plug-ins use basic 2D layers from After Effects. In addition to
3D effects, there are plug-ins for making video look like film or cartoons; simulating
fire, smoke, or water; particle systems; slow motion; creating animated charts, graphs,
and other data visualization; calculating the 3D movement of a camera in a 2D video
shot; eliminating flicker, noise, or rigging lines; translating timelines from FCP or
Avid; adding high-end color correction; and other workflow improvements and visual
effects.

Python- Python is an interpreted, object-oriented, high-level programming language


with dynamic semantics. Its high-level built in data structures, combined with
dynamic typing and dynamic binding, make it very attractive for Rapid Application
Development, as well as for use as a scripting or glue language to connect existing
components together. Python's simple, easy to learn syntax emphasizes readability
and therefore reduces the cost of program maintenance. Python supports modules and
packages, which encourages program modularity and code reuse. The Python interpreter
and the extensive standard library are available in source or binary form without charge
for all major platforms, and can be freely distributed.

Weather API- Weather APIs are Application Programming Interfaces that allow you
to connect to large databases of weather forecast and historical information. The
weather API provides enough weather data for basic weather information (eg
current weather, forecast, UV index data, and historical weather information). You can
use geolocation and names to get a city location.

Weather forecasting is the task of


predicting the state of the
atmosphere at a future time and a
specified location. Traditionally,
this has been done through
physical simulations in which the
atmosphere is modeled as a fluid.
The present state of the
atmosphere is sampled, and the
future
state is computed by numerically
solving the equations of fluid
dynamics and thermodynamics.
However, the system of ordinary
differential equations that govern
this physical model is
unstable under perturbations, and
uncertainties in the initial
measurements of the
atmospheric
conditions and an incomplete
understanding of complex
atmospheric processes restrict the
extent
of accurate weather forecasting
to a 10 day period, beyond
which weather forecasts are
significantly unreliable. Machine
learning, on the contrary, is
relatively robust to perturbations
and doesn’t require a complete
understanding of the physical
processes that govern the
atmosphere. Therefore, machine
learning may represent a viable
alternative to physical models in
weather forecasting.
Machine learning is the ability
of computer to learn without
being explicitly programmed. It
allows machines to find hidden
patterns and insights. In supervised
learning, we build a model
based on labeled training data. The
model is then used for mapping
new examples. So, based on
the observed weather patterns
from the past, a model can be
built and used to predict the
weather.
This project work focuses on
solving the weather prediction
anomalies and in-efficiency based
on linear regression algorithms and
to formulate an efficient weather
prediction model based on
the linear regression algorithms

CHAPTER 2: SOFTWARE & HARDWARE REQUIREMENT

Functional Requirements

1. Accessing a database

 The system should allow administrator to add historical weather data.


 The system should be able to recognize patterns in temperature, humidity, and wind
with use of historical data.

2. Prediction algorithm

 System should periodically apply prediction algorithms or models on obtained data


and store results to central database.
 System shall obtain and display confidence value for each prediction given to user.

3. Actions performed by system

 System shall allow users to check weather for future three days.

Non-Functional Requirements

1.User Non-Functional Requirements


 System shall allow for users to get prediction for weather within almost two
mouse clicks.
 System should ensure that features that do not require a user to be logged in.

2.System Non-Functional Requirements

 System should be able to run with core functionality from computer system.
 System should be able to show interactive animations to users regarding
current and future climatic conditions.

3.Other Non-Functional Requirements

 System should textual prediction of climate conditions.

Other Requirements

1.Performance Requirements

 The proposed software that we are going to develop will be used as the
general-purpose application software. Therefore, it is expected that the database
would perform functionally all the requirements that are specified by the user.

2.Safety Requirements

 The database may get crashed at any certain time due to virus or operating
system failure. Therefore, it is required to take the database backup

3.Security Requirements

 We are going to develop a secured database for the user. Software Quality
Attributes. The Quality of the database is maintained in such a way so that it can be
very user friendly to all the users.

4.Hardware Requirements

 The system requires a database in order to store persistent data.


5.Software Constraints

 The development of the system will be constrained by the availability of required


software such as web servers, dataset and development tools.

CHAPTER 3: DESIGN AND TESTING

Design

Weather Prediction System Architecture


The system is developed in python along with javascript. Daily data sets of last
6 years (2013-2019) has been fetched to train our model. The system
takes input from the datasets and produces the result.
The system building process consists of following sequential steps:
1. Fetching the dataset
2. Cleaning the dataset
3. Selection of the features of dataset
4. Train Model
5. Use the model to predict results.

Use-Case Diagram

An interaction between a user and a system is described by use case diagram.


Use case diagrams describe what a system does from the standpoint of an
external observer. The emphasis is on what a system does rather than how. Use
case diagrams are closely connected to scenarios. A scenario is an example of
what happens when someone interacts with the system. A use case diagram is a
collection of actors, use cases, and their communications. For initial
development we can use this use case. In this use case diagram we can see
following use cases and actor. Use cases are self explanatory and they represent
the main functions of Weather Prediction System.

Testing

Testing is the process of evaluating a system or its component with the intent to
find whether it satisfies the specified requirement or not. Testing is executing a
system in order to identify any gaps, errors, or missing requirements in
contrary to the actual requirements. Systems should not be tested as a single,
monolithic unit. The testing process should therefore proceed in the stages
where testing is carried out incrementally in conjunction with system
implementation. Errors in program components may come to light at a later
stage of the testing process. The process is therefore an iterative one with
information being fed back from later stage to earlier parts of the process.
Following testings were done during the course of our project.

1.Unit Testing

Unit testing focuses verification efforts on the smaller unit of software design.
Using the detailed design description as a guide, important control paths
are tested to uncover errors within the boundary of the module. The relative
complexity of the test and the error detected as a result is limited by the
constraint scope established for unit testing. The unit test is always white
box oriented, and the step can be conducted in parallel for multiple modules
 Tested individual python file by debugging and using print statement
 Individual Component rendering

2.Integration Testing

With unit testing the modules may function properly, but at times they
may have inadvertent affect on another, sub function when combined, may
not produce the desired functions; individually acceptable impression may
be signed to unacceptable levels then global data structure may present
problems. Integration testing is a systematic technique for constructing the
program structure while at the same time conducting tests to uncover
errors associated with interfacing. The objective is to take unit tested modules
and build a program structure that has been dictated by the design.
CHAPTER 4: RESULTS & DISCUSSION

(1) Intro/Splash Screen:

Fig 4.1: Intro Screen


It is the snapshot of the intro screen that will be displayed when the website is
launched.
(2)Location

Fig 4.2: Location


It is the snapshot of the main menu screen . User have to enter the location that he wants
to search the temperature of in the “search by location” field.
(3)Search

Fig 4.3: Search


It is the snapshot when the user has entered the location , he has to press “ enter” key on
the keyboard to view result.
(4)Output

Fig 4.4: Output


It is the snapshot the temperature and weather condition of the searched location by the
user will be shown. This is the final result.
References

1.https.wikipedia.com
2. https.w3schools.com
3. https.reactjs.org
4.https://dev.to/achowba/building-a-modal-in-react-15hg#:~:targetText=Open%20the
%20Modal.js%20file,%7B%7B%20transform%3A%20props.show%20%3F
Appendix - A: Coding

Data Downloading

from wwo_hist import retrieve_hist_data


from backbone import getConfig
def getData(start_date=None, end_date=None, location=None):
config, corePath = getConfig("dataset")
config = config["api"]
if start_date is None:
start_date = config["start_date"]
if end_date is None:
end_date = config["end_date"]
if location is None:
location = config["location"]
data = retrieve_hist_data(
api_key=config["key"],
location_list=location,
start_date=start_date,
end_date=end_date,
frequency=config["frequency"],
export_csv=False,
store_df=True
)
dataset = {}
for i in range(len(location)):
loc = location[i]
dataset[loc] = data[i].set_index(
'date_time').drop(columns=['uvIndex'])
return dataset

Data Processing

# dataProcessing.py
import pandas as pd
from dataDownload import getData
class DataProcessor:
def __init__(self):
self.loadConfig()
def loadConfig(self):
import os
from backbone import getConfig

datasetConfig, corePath = getConfig("dataset")


datasetDir = os.path.join(corePath, datasetConfig["dataset_dir"])
self.location = datasetConfig['api']['location'][0]
self.labels = datasetConfig["labels"]
self.predictionIndices = [label for label in self.labels]
self.index = datasetConfig["index"]
if self.index not in self.predictionIndices:
self.predictionIndices.insert(0, self.index)
self.nPrior = datasetConfig["n_prior"]
self.rawDataFile = os.path.join(
datasetDir, datasetConfig["raw_dataset_file"])
self.dataFile = os.path.join(datasetDir, datasetConfig["dataset_file"])
# print(self.labels)
# print(self.predictionIndices)
def __deriveNthPriorFeatures(self, data, feature, n):
rows = data.shape[0]
n = n * 24
nthPriopData = [None]*n + [data[feature][i-n] for i in range(n, rows)]
col_name = "{}_{}".format(feature, n)
data[col_name] = nthPriopData
def processRawData(self, rawDataFile=None):
if rawDataFile is None:
rawDataFile = self.rawDataFile
try:
data = pd.read_csv(rawDataFile, parse_dates=[self.index])[
self.predictionIndices].set_index(self.index)
except FileNotFoundError:
data = getData()[self.location]
# self.save(data, file=rawDataFile)
for feature in self.predictionIndices:
if feature != self.index:
for n in range(1, self.nPrior+1):
self.__deriveNthPriorFeatures(data, feature, n)
return data
def getFeatureLabels(self, data):
y = pd.DataFrame()
for label in self.labels:
y[label] = data.pop(label)
# data = data.drop(columns=self.labels)
return data, y
def getLabels(self):
return self.labels
def save(self, data, file=None):
if file is None:
file = self.dataFile
data = data.dropna()
data.to_csv(file)
def load(self, date=None, file=None):
try:
if file is None:
file = self.dataFile
dataset = pd.read_csv(file, parse_dates=[
self.index]).set_index(self.index)
if date is not None:
dataset = dataset.loc[pd.datetime(
date.year, date.month, date.day, date.hour)]
dataset = pd.DataFrame(dataset).T
except KeyError:
from backbone import getCoreConfig, updateCoreConfig
from datetime import datetime, timedelta
start_date = getCoreConfig()['last_date']
end_date = datetime.now().strftime('%d-%b-%Y')
dataset = getData(start_date=start_date, end_date=end_date)[
self.location]
raw_data = pd.read_csv(self.rawDataFile).set_index(self.index)
d = pd.concat([raw_data, dataset]).drop_duplicates()
d.to_csv(self.rawDataFile)
dataset = self.processRawData()
self.save(dataset)
next_date = datetime.strftime(
datetime.now()+timedelta(1), "%d-%b-%Y")
updateCoreConfig({"last_date": next_date})
except FileNotFoundError:
dataset = self.processRawData()
self.save(dataset)
if date is not None:
dataset = dataset.loc[pd.datetime(
date.year, date.month, date.day, date.hour)]
dataset = pd.DataFrame(dataset).T
return dataset
if __name__ == "__main__":

from datetime import datetime


dataProcessor = DataProcessor()
print(dataProcessor.load(datetime.now()))

Model Training

from backbone import getConfig


from dataProcessor import DataProcessor
import pandas as pd
from sklearn.linear_model import LinearRegression
import joblib
from os import path
class ModelTrain:
def __init__(self):
config, corePath = getConfig("dataset")
self.index = config["index"]
self.labels = config["labels"]
self.corePath = corePath
self.modelDir = config["models_dir"]
self.datasetDir = config["dataset_dir"]
def setUpDataset(self, train_size=0.8):
dataProcessor = DataProcessor()
data = dataProcessor.load()
dataset = data.dropna()
dataset_train = dataset.sample(frac=train_size, random_state=42)
dataset_test = dataset.drop(dataset_train.index)
X_train, y_train = dataProcessor.getFeatureLabels(dataset_train)
X_test, y_test = dataProcessor.getFeatureLabels(dataset_test)
# dataset_train = dataset_train.drop(columns=labels_train.columns)
# dataset_test = dataset_test.drop(columns=labels_test.columns)
return X_train, y_train, X_test, y_test
def trainModel(self):
try:
X_train, y_train, X_test, y_test = self.setUpDataset(
train_size=0.8)
except FileNotFoundError as e:
print(e)
else:
for label in self.labels:
model = LinearRegression(n_jobs=-1)
model.fit(X_train, y_train[label])
joblib.dump(model, path.join(self.corePath,
self.modelDir, label+"_model.mdl"))
print(model.score(X_test, y_test[label]))
return X_test, y_test, self.labels

Model Prediction

from backbone import getConfig


import joblib
from os import path
class PredictionEngine:
def __init__(self):
self.models = {}
config, corePath = getConfig("dataset")
self.config = config
for label in config["labels"]:
try:
self.models[label] = joblib.load(
path.join(corePath, config["models_dir"], label+"_model.mdl"))
except FileNotFoundError:
from modelTrain import ModelTrain
modelTrain = ModelTrain()
modelTrain.trainModel()
self.models[label] = joblib.load(
path.join(corePath, config["models_dir"], label+"_model.mdl"))
def predict(self, X, y, labels=None):
if labels == None:
labels = self.config["labels"]
prediction = {}
for label in labels:
prediction[label] = self.models[label].predict(X)[0]
return prediction

UI Components

import React, { Component } from "react";


// import Splash from "./components/Splash";
import Window from "./components/Window";
import Splash from "./components/Splash";
import axios from "axios";
const { remote } = window.require("electron");
export default class WeatherApp extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
data: null
};
}
componentDidMount() {
axios
.get("http://localhost:5000/")
.then(response => {
const data = response.data;
console.log(data);
this.setState({
isLoading: false,
data: data
});
})
.catch(error => {
console.log(error);
});
}
renderMainWindow() {
const win = remote.getCurrentWindow();
win.setSize(1900, 1080, true);
win.setPosition(0, 0, true);
}
handleTheme() {
const hr = new Date().getHours();
let theme;
if (hr >= 6 && hr <= 11) {
theme = "morning";
} else if (hr > 11 && hr < 16) {
theme = "afternoon";
} else if (hr >= 16 && hr < 19) {
theme = "evening";
} else {
theme = "night";
}
return theme + "-theme";
}
render() {
const theme = this.handleTheme();
const { isLoading } = this.state;
let ui = null;
if (isLoading) {
ui = (
<div>
<Splash />
</div>
);
} else {
this.renderMainWindow();
ui = (
<div className={theme}>
<Window data={this.state.data} theme={theme} />
</div>
);
}
return <React.Fragment>{ui}</React.Fragment>;
}
}

Window

import React, { Component } from "react";


import TitleBar from "./TitleBar";
import MainContent from "./MainContent";
import Modal from "./Modal";
import PredictionModal from "./PredictionModal";
export default class Window extends Component {
constructor(props) {
super(props);
this.state = {
showModal: false
};
}
modalShow = () => {
this.setState({
showModal: true
});
};
modalHide = () => {
this.setState({
showModal: false
});
};
render() {
const { prediction, real } = this.props.data;
console.log(this.props.data);
const modal = this.state.showModal ? (
<Modal theme={this.props.theme}>
<div className='modal'>
<PredictionModal data={prediction} handleClose={this.modalHide} />
</div>
</Modal>
) : null;
return (
<div className='GridContainer'>
<div className='TitleBarConatainer'>
<TitleBar title='Weather Prediction' />
</div>
<div className='AnimationContainer'>Animation</div>
<div className='ContentContainer'>
<div className='MainContent'>
<MainContent data={real} handleClick={this.modalShow} />
</div>
</div>
{modal}
</div>
);
}
}

Modal

import { Component } from "react";


import ReactDOM from "react-dom";
export default class Modal extends Component {
constructor(props) {
super(props);
this.modalRoot = document.getElementById("modal-root");
this.element = document.createElement("div");
this.element.classList.add(this.props.theme);
}
componentDidMount() {
this.modalRoot.appendChild(this.element);
}
componentWillUnmount() {
this.modalRoot.removeChild(this.element);
}
render() {
return ReactDOM.createPortal(this.props.children, this.element);
}
}

You might also like