Sklearn NotFittedError: This LinearRegression instance is not fitted yet - python-2.7

I am trying a simple linear regression and I have tried this code:
x1=data.iloc[:, 9].values
y1=data.iloc[:,1].values
from sklearn.model_selection import train_test_split
seed=7
x1_train,x1_test,y1_train,y1_test=
train_test_split(x1,y1,test_size=0.15,random_state=seed)
x1_train=nm.reshape(nm.array(x1_train),(-1,1))
from sklearn.linear_model import LinearRegression
lireg=LinearRegression()
model1=LinearRegression().fit(x1_train,y1_train)
y_pred=lireg.predict(x1_test)
NotFittedError: This LinearRegression instance is not fitted yet. Call 'fit' with appropriate arguments before using this method
Please help

Here is the explanation why you got this error. Let's have a look at the following lines:
lireg=LinearRegression()
model1=LinearRegression().fit(x1_train,y1_train)
y_pred=lireg.predict(x1_test)
What happens here?
You initialise 2 LinearRegression models named: lireg and model1
For the lireg you DO NOT call .fit but for model1 you do.
y_pred=lireg.predict(x1_test) throws the error because you try to .predict using lireg, but lireg is not trained / fitted.
You just need this:
Way 1:
from sklearn.linear_model import LinearRegression
lireg=LinearRegression() # initialize the model
lireg.fit(x1_train,y1_train) # fit he model
y_pred=lireg.predict(x1_test) # now predict
Way 2:
from sklearn.linear_model import LinearRegression
lireg=LinearRegression().fit(x1_train,y1_train) # initialize & fit the model
y_pred=lireg.predict(x1_test) # now predict

Related

how can load ONNX model in C++

I have convert PyTorch SuperResouloution (.pth) Model to ONNX model (.onnx) with code below:
import torch
import onnx
from onnx_tf.backend import prepare
from basicsr.archs.rrdbnet_arch import RRDBNet
pth_path = "RESRGAN_x4plus_Main.pth"
Model = RRDBNet(num_in_ch=3, num_out_ch=3, scale=4, num_feat=64, num_block=23, num_grow_ch=32)
Model.load_state_dict(torch.load(pth_path)\["params_ema"\])
Model.eval()
X = torch.randn((1, 3, 64, 64))
torch.onnx.export(Model, X,
"Model.onnx",
export_params=True,
opset_version=11,
do_constant_folding=True,
input_names=\["input"\],
output_names=\["output"\])
and now I want to load this model into C++ and run it...
I have seen many examples of onnxruntime for loading models but I am very confused. sample codes are very complex and not for Super Resolution models.
I emphasize
I want to load the model directly in the C++ program (with onnx-runtime package)
I don't want to convert onnx model into another model format...
I have to load the .onnx model into c++ and pass the image into it and I expect to receive an Image from the model output. (model is a GAN)

Updating DateTimeField in Django

I have a DateTimeField() in my models.py. What I am trying to do is to update it, along with some other values in the model.
Everything else updates fine apart from my DateTimeField(). the error i get says that AttributeError: module 'datetime' has no attribute 'now'
anyone see where I am going wrong with m update?
sModel.objects.all().update(sPasses=pass_number_for_graph, sFails=fail_number_for_graph, sNds=p_number_for_graph, sTimestamp=datetime.now())
Import _datetime as instead of datetime
import _datetime

Integrate Dataframe from a Python File to Django

I've developed a complex data analysis model using Python (for the sake of simplicity, let's call it analysis.py) which contains multiple long algorithms to transform a set of raw data and spits out output in the form of dataframe as well.
I've been looking into some tutorials recently on Django framework and have tried building a simple web app that resembles a forum/blog post web app.
With the dataframe output from the analysis.py, I would like to display the data in the form of multiple charts on the web app.
Can anyone point me to a direction to move from here? I've looked for multiple resources online but I think I am unable to find the correct keywords that match with what I actually want to build. I just want a shell code kind of a thing to integrate into my current django backend in order to be able to call the dataframe from the analysis.py
Thank you very much in advance.
It amazes me somehow that after posting a question here, I managed to come up with better keywords in finding the solution that is closely matched to my intended product.
Again, I would like to apologize if my question was too vague or did not contain any script that I've done so far, since I was merely looking for direction to move forward. And fortunately I did after giving it much thought and integrating different solutions from multiple sources on the net.
I'm not sure if my solution is the best solution, but it works for me and if it at least helps other people who were on the same boat as I did before, I'd be glad!
So my solution entails importing a dataframe from the analysis.py and then pass the data that I want as API Endpoints (using Django Rest Framework) in order to be displayed in my dashboard.
The following are some details (with some scripts) of my solution:
views.py
# Importing the external python script (analysis.py).
#This is where the data from csv is imported and is transformed.
#The script is written in a function form and returns the dataframe.
from . import analysis
from .analysis import data_transform
#Django Rest Framework
from rest_framework.views import APIView
from rest_framework.response import Response
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
class ChartData(APIView):
authentication_classes = []
permission_classes =[]
def get(self, request, format=None):
# Assign dataframe output to a new dataframe
df = data_transform()
# Assigning variables from datafram
data1 = df['VOL'].values.tolist()
data2 = df['PRICE'].values.tolist()
data = {
"data1":data1,
"data2":data2,
}
#Return endpoints in Json format
return Response(data)
Analysis.py looks more like this
import pandas as pd
import numpy as np
def data_transform()
#where all the transformations happened
return dataframe
And then I passed the endpoints ('data') to a html in order to visualize them using chart.js. You can find some good resources in the Tube. Look up keywords chart.js and django.
Again, I'm not sure this is the best method. I am open to a better solution, if you guys have any!

Load Alexnet weights into keras model using theano backend

I am using a pre-trained model such as Alexnet, In this case also, ending up with the same error.
I was downloaded the alexnet_weights from here-->https://github.com/heuritech/convnets-keras
then I tried like this
from keras.models import load_model
base_model=load_model('alexnet_weights.h5')
I ended up with
ValueError: No model found in config file.
please help me to get rid out of it.
AlexNet is not a supported default model in Keras. Maybe you could try with VGG16 first:
from keras.applications.vgg16 import VGG16
from keras.preprocessing import image
from keras.applications.vgg16 import preprocess_input
import numpy as np
model = VGG16(weights='imagenet', include_top=False)
img_path = 'elephant.jpg'
img = image.load_img(img_path, target_size=(224, 224))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
features = model.predict(x)
Then you could move to using AlexNet, but you will need to build the model structure first and store that as "base_model" in your case. You only have the weight file I believe. Then you can load the weight file you have.

Django reversion does not save revisions made in shell

I did the initial installation steps and created the initial revisions, but then when I save a model in django shell, the new revision is not created:
In [1]: s = Shop.objects.all()[0]
In [2]: import reversion
In [3]: s.name = 'a'
In [4]: s.save()
In [5]: s.name = 'b'
In [6]: s.save()
In [7]: reversion.get_for_object(s)
Out[7]: [<Version: <1> "X">]
This is the initial revision.
When I update the model from a view, a revision is created successfully.
What am I missing?
The models.py file is:
...
class Shop(Model):
...
import reversion
reversion.register(Shop)
<EOF>
I see a reversion method among post_save receiver, although it isn't called when I debug it.
I have Django v1.4.1, reversion v1.6.2.
I wrote django-reversion, so I think I can shed some light on this issue.
A Version of a model is automatically saved when a model is saved, providing the following are true:
The model is registered with django-reversion.
The code block is marked up as being within a revision.
Point 1 can be achieved by either registering a model with VersionAdmin, or explicitly calling reversion.register() in your models.py file.
Point 2 can be achieved by using RevisionMiddleware, or the reversion.create_revision() decorator or context manager. Any admin views in VersionAdmin also save a revision.
So, if your shell is not creating Versions, then either point 1 or point 2 is not being met. Here's how to fix it:
If you're using VersionAdmin, import the relevant admin module in your shell code to kick in the auto-registration. Alternatively, call reversion.register() in your models.py file.
In your shell code, using the reversion.create_revision() context manager around your call to save.
with reversion.create_revision():
s.save()
More about this sort of thing on the Low Level API wiki page:
http://django-reversion.readthedocs.org/en/latest/api.html