Linear regression with moving window in python
I am trying to write a program to determine the slope and intercept of a linear regression model over a moving window of points, i.e. from (x1, y1) to (x2, y2) and then from (x2, y2) to (x3, y3). I have successfully carried out a linear regression across the two numpy arrays (x and y), but I am not sure how to approach this project. I would like the window size to be a user-input parameter. I can reshape my two arrays using array subsetting and achieve the a window over which the linear regression is carried out, but i do not know how to automate this and how to save each slope and intercept into a file. I have tried my best, but I am a new programmer and don't know where to look. Can someone point me in the right direction? Thank you!
Below is my code:
import matplotlib.pyplot as plt
import seaborn as sns
import scipy as sp
import numpy as np
import math as math
##import data from file
data = np.genfromtxt('CA_data.csv', delimiter=',')
print(np.shape(data))
#print(data)
##subset 2D array into 1D arrays
Tinv = data[:,0]
A_data = data[:,1]
B_data = data[:,2]
C_data = data[:,3]
a = np.empty_like()
b = np.empty_like()
##linear regression
###for i,j in a.range(Tinv[i:j]):
Tnew[i] = Tinv[i:j]
a, b = np.polyfit(Tinv, A_data,1)
print("slope = ", a)
print("intercept = ", b)
# #visualize optimized slope
# a_vals = np.linspace(-6500, 0, 400)
# rss = np.empty_like(a_vals)
# for i, a in enumerate(a_vals):
# rss[i] = np.sum((A_data - a*Tinv - b)**2)
# _ = plt.plot(a_vals, rss, '-')
# _ = plt.xlabel('slope')
# _ = plt.ylabel('residual sum of squares')
# _ = plt.show()
##Theoretical plot for optimal values
startx = Tinv[0]
endx = Tinv[-1]
#print(startx)
#print(endx)
x = np.array([startx, endx])
y = a*x + b
##plot the data
plt.plot(Tinv, A_data, marker = '.', color = 'r', linestyle = 'none')
plt.plot(x,y) #plot theoretical data
plt.margins(0.02)
plt.axis([0.00275, 0.0035, 0.5, 3.0])
plt.xlabel("x")
plt.ylabel('y')
plt.title('title')
plt.show()
# print(Tinv)
# print(A_data)
# print(B_data)
# print(C_data)
python
add a comment |
I am trying to write a program to determine the slope and intercept of a linear regression model over a moving window of points, i.e. from (x1, y1) to (x2, y2) and then from (x2, y2) to (x3, y3). I have successfully carried out a linear regression across the two numpy arrays (x and y), but I am not sure how to approach this project. I would like the window size to be a user-input parameter. I can reshape my two arrays using array subsetting and achieve the a window over which the linear regression is carried out, but i do not know how to automate this and how to save each slope and intercept into a file. I have tried my best, but I am a new programmer and don't know where to look. Can someone point me in the right direction? Thank you!
Below is my code:
import matplotlib.pyplot as plt
import seaborn as sns
import scipy as sp
import numpy as np
import math as math
##import data from file
data = np.genfromtxt('CA_data.csv', delimiter=',')
print(np.shape(data))
#print(data)
##subset 2D array into 1D arrays
Tinv = data[:,0]
A_data = data[:,1]
B_data = data[:,2]
C_data = data[:,3]
a = np.empty_like()
b = np.empty_like()
##linear regression
###for i,j in a.range(Tinv[i:j]):
Tnew[i] = Tinv[i:j]
a, b = np.polyfit(Tinv, A_data,1)
print("slope = ", a)
print("intercept = ", b)
# #visualize optimized slope
# a_vals = np.linspace(-6500, 0, 400)
# rss = np.empty_like(a_vals)
# for i, a in enumerate(a_vals):
# rss[i] = np.sum((A_data - a*Tinv - b)**2)
# _ = plt.plot(a_vals, rss, '-')
# _ = plt.xlabel('slope')
# _ = plt.ylabel('residual sum of squares')
# _ = plt.show()
##Theoretical plot for optimal values
startx = Tinv[0]
endx = Tinv[-1]
#print(startx)
#print(endx)
x = np.array([startx, endx])
y = a*x + b
##plot the data
plt.plot(Tinv, A_data, marker = '.', color = 'r', linestyle = 'none')
plt.plot(x,y) #plot theoretical data
plt.margins(0.02)
plt.axis([0.00275, 0.0035, 0.5, 3.0])
plt.xlabel("x")
plt.ylabel('y')
plt.title('title')
plt.show()
# print(Tinv)
# print(A_data)
# print(B_data)
# print(C_data)
python
add a comment |
I am trying to write a program to determine the slope and intercept of a linear regression model over a moving window of points, i.e. from (x1, y1) to (x2, y2) and then from (x2, y2) to (x3, y3). I have successfully carried out a linear regression across the two numpy arrays (x and y), but I am not sure how to approach this project. I would like the window size to be a user-input parameter. I can reshape my two arrays using array subsetting and achieve the a window over which the linear regression is carried out, but i do not know how to automate this and how to save each slope and intercept into a file. I have tried my best, but I am a new programmer and don't know where to look. Can someone point me in the right direction? Thank you!
Below is my code:
import matplotlib.pyplot as plt
import seaborn as sns
import scipy as sp
import numpy as np
import math as math
##import data from file
data = np.genfromtxt('CA_data.csv', delimiter=',')
print(np.shape(data))
#print(data)
##subset 2D array into 1D arrays
Tinv = data[:,0]
A_data = data[:,1]
B_data = data[:,2]
C_data = data[:,3]
a = np.empty_like()
b = np.empty_like()
##linear regression
###for i,j in a.range(Tinv[i:j]):
Tnew[i] = Tinv[i:j]
a, b = np.polyfit(Tinv, A_data,1)
print("slope = ", a)
print("intercept = ", b)
# #visualize optimized slope
# a_vals = np.linspace(-6500, 0, 400)
# rss = np.empty_like(a_vals)
# for i, a in enumerate(a_vals):
# rss[i] = np.sum((A_data - a*Tinv - b)**2)
# _ = plt.plot(a_vals, rss, '-')
# _ = plt.xlabel('slope')
# _ = plt.ylabel('residual sum of squares')
# _ = plt.show()
##Theoretical plot for optimal values
startx = Tinv[0]
endx = Tinv[-1]
#print(startx)
#print(endx)
x = np.array([startx, endx])
y = a*x + b
##plot the data
plt.plot(Tinv, A_data, marker = '.', color = 'r', linestyle = 'none')
plt.plot(x,y) #plot theoretical data
plt.margins(0.02)
plt.axis([0.00275, 0.0035, 0.5, 3.0])
plt.xlabel("x")
plt.ylabel('y')
plt.title('title')
plt.show()
# print(Tinv)
# print(A_data)
# print(B_data)
# print(C_data)
python
I am trying to write a program to determine the slope and intercept of a linear regression model over a moving window of points, i.e. from (x1, y1) to (x2, y2) and then from (x2, y2) to (x3, y3). I have successfully carried out a linear regression across the two numpy arrays (x and y), but I am not sure how to approach this project. I would like the window size to be a user-input parameter. I can reshape my two arrays using array subsetting and achieve the a window over which the linear regression is carried out, but i do not know how to automate this and how to save each slope and intercept into a file. I have tried my best, but I am a new programmer and don't know where to look. Can someone point me in the right direction? Thank you!
Below is my code:
import matplotlib.pyplot as plt
import seaborn as sns
import scipy as sp
import numpy as np
import math as math
##import data from file
data = np.genfromtxt('CA_data.csv', delimiter=',')
print(np.shape(data))
#print(data)
##subset 2D array into 1D arrays
Tinv = data[:,0]
A_data = data[:,1]
B_data = data[:,2]
C_data = data[:,3]
a = np.empty_like()
b = np.empty_like()
##linear regression
###for i,j in a.range(Tinv[i:j]):
Tnew[i] = Tinv[i:j]
a, b = np.polyfit(Tinv, A_data,1)
print("slope = ", a)
print("intercept = ", b)
# #visualize optimized slope
# a_vals = np.linspace(-6500, 0, 400)
# rss = np.empty_like(a_vals)
# for i, a in enumerate(a_vals):
# rss[i] = np.sum((A_data - a*Tinv - b)**2)
# _ = plt.plot(a_vals, rss, '-')
# _ = plt.xlabel('slope')
# _ = plt.ylabel('residual sum of squares')
# _ = plt.show()
##Theoretical plot for optimal values
startx = Tinv[0]
endx = Tinv[-1]
#print(startx)
#print(endx)
x = np.array([startx, endx])
y = a*x + b
##plot the data
plt.plot(Tinv, A_data, marker = '.', color = 'r', linestyle = 'none')
plt.plot(x,y) #plot theoretical data
plt.margins(0.02)
plt.axis([0.00275, 0.0035, 0.5, 3.0])
plt.xlabel("x")
plt.ylabel('y')
plt.title('title')
plt.show()
# print(Tinv)
# print(A_data)
# print(B_data)
# print(C_data)
python
python
asked Nov 14 '18 at 22:59
telbatelba
255
255
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
Wrap the modeling and plotting in a function.
Then call this function from another function that subsets the arrays to the user specified range before feeding the "cleaned" data to the prediction function.
pseudocode:
def select_window(data, start, stop):
clean data = data[start:stop,:]
X = clean_data[without_y]
y = clean_data[y]
prediction_function(X, y)
def prediction_function(X,y):
predict_on_X_and_y_and_plot_as_you_desire
Thanks for your advice. I have such a small data set (and I am just starting out) that I opted to write this in a for loop in line with my code. With your advice, it's straightforward to define this as a function and call this subroutine in other parts of the code.
– telba
Nov 21 '18 at 2:25
@telba that also definitely works. I have come to appreciate the way wrapping steps in functions helps the code "tell you" what it's doing ... a for loop can get complex and confusing, but if wrapped inloop_that_does_x()
it becomes self explanatory.
– dozyaustin
Nov 23 '18 at 8:47
@telba Also ... if you feel like marking me as the correct answer ;) that would be lovely (would be one of my first answers).
– dozyaustin
Nov 23 '18 at 8:47
add a comment |
Here's what I ended up with:
data = np.genfromtxt('data.csv', delimiter=',')
w = data[:,0]
x = data[:,1]
y = data[:,2]
z = data[:,3]
lenw = int(len(w))
lenx = int(len(x)) #change the value within inner parenthesis to suit different dataset
window = int(6) #change window size
wdata_avg = np.zeros(lenw - window + 1)
a = np.zeros(lenw-window+1)
b = np.zeros(lenx-window + 1)
for i in np.arange(len(w)):
wdata = w[i:i + window]
xdata = x[i:i+window]
a[i], b[i] = np.polyfit(wdata, xdata,1)
wdata_avg[i] = np.mean(wdata)
if i == (lenw - window):
break
There may be some inconsistencies in the code, since I tried to format it so it was general rather than specific to my data.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53309996%2flinear-regression-with-moving-window-in-python%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
Wrap the modeling and plotting in a function.
Then call this function from another function that subsets the arrays to the user specified range before feeding the "cleaned" data to the prediction function.
pseudocode:
def select_window(data, start, stop):
clean data = data[start:stop,:]
X = clean_data[without_y]
y = clean_data[y]
prediction_function(X, y)
def prediction_function(X,y):
predict_on_X_and_y_and_plot_as_you_desire
Thanks for your advice. I have such a small data set (and I am just starting out) that I opted to write this in a for loop in line with my code. With your advice, it's straightforward to define this as a function and call this subroutine in other parts of the code.
– telba
Nov 21 '18 at 2:25
@telba that also definitely works. I have come to appreciate the way wrapping steps in functions helps the code "tell you" what it's doing ... a for loop can get complex and confusing, but if wrapped inloop_that_does_x()
it becomes self explanatory.
– dozyaustin
Nov 23 '18 at 8:47
@telba Also ... if you feel like marking me as the correct answer ;) that would be lovely (would be one of my first answers).
– dozyaustin
Nov 23 '18 at 8:47
add a comment |
Wrap the modeling and plotting in a function.
Then call this function from another function that subsets the arrays to the user specified range before feeding the "cleaned" data to the prediction function.
pseudocode:
def select_window(data, start, stop):
clean data = data[start:stop,:]
X = clean_data[without_y]
y = clean_data[y]
prediction_function(X, y)
def prediction_function(X,y):
predict_on_X_and_y_and_plot_as_you_desire
Thanks for your advice. I have such a small data set (and I am just starting out) that I opted to write this in a for loop in line with my code. With your advice, it's straightforward to define this as a function and call this subroutine in other parts of the code.
– telba
Nov 21 '18 at 2:25
@telba that also definitely works. I have come to appreciate the way wrapping steps in functions helps the code "tell you" what it's doing ... a for loop can get complex and confusing, but if wrapped inloop_that_does_x()
it becomes self explanatory.
– dozyaustin
Nov 23 '18 at 8:47
@telba Also ... if you feel like marking me as the correct answer ;) that would be lovely (would be one of my first answers).
– dozyaustin
Nov 23 '18 at 8:47
add a comment |
Wrap the modeling and plotting in a function.
Then call this function from another function that subsets the arrays to the user specified range before feeding the "cleaned" data to the prediction function.
pseudocode:
def select_window(data, start, stop):
clean data = data[start:stop,:]
X = clean_data[without_y]
y = clean_data[y]
prediction_function(X, y)
def prediction_function(X,y):
predict_on_X_and_y_and_plot_as_you_desire
Wrap the modeling and plotting in a function.
Then call this function from another function that subsets the arrays to the user specified range before feeding the "cleaned" data to the prediction function.
pseudocode:
def select_window(data, start, stop):
clean data = data[start:stop,:]
X = clean_data[without_y]
y = clean_data[y]
prediction_function(X, y)
def prediction_function(X,y):
predict_on_X_and_y_and_plot_as_you_desire
answered Nov 15 '18 at 0:17
dozyaustindozyaustin
14411
14411
Thanks for your advice. I have such a small data set (and I am just starting out) that I opted to write this in a for loop in line with my code. With your advice, it's straightforward to define this as a function and call this subroutine in other parts of the code.
– telba
Nov 21 '18 at 2:25
@telba that also definitely works. I have come to appreciate the way wrapping steps in functions helps the code "tell you" what it's doing ... a for loop can get complex and confusing, but if wrapped inloop_that_does_x()
it becomes self explanatory.
– dozyaustin
Nov 23 '18 at 8:47
@telba Also ... if you feel like marking me as the correct answer ;) that would be lovely (would be one of my first answers).
– dozyaustin
Nov 23 '18 at 8:47
add a comment |
Thanks for your advice. I have such a small data set (and I am just starting out) that I opted to write this in a for loop in line with my code. With your advice, it's straightforward to define this as a function and call this subroutine in other parts of the code.
– telba
Nov 21 '18 at 2:25
@telba that also definitely works. I have come to appreciate the way wrapping steps in functions helps the code "tell you" what it's doing ... a for loop can get complex and confusing, but if wrapped inloop_that_does_x()
it becomes self explanatory.
– dozyaustin
Nov 23 '18 at 8:47
@telba Also ... if you feel like marking me as the correct answer ;) that would be lovely (would be one of my first answers).
– dozyaustin
Nov 23 '18 at 8:47
Thanks for your advice. I have such a small data set (and I am just starting out) that I opted to write this in a for loop in line with my code. With your advice, it's straightforward to define this as a function and call this subroutine in other parts of the code.
– telba
Nov 21 '18 at 2:25
Thanks for your advice. I have such a small data set (and I am just starting out) that I opted to write this in a for loop in line with my code. With your advice, it's straightforward to define this as a function and call this subroutine in other parts of the code.
– telba
Nov 21 '18 at 2:25
@telba that also definitely works. I have come to appreciate the way wrapping steps in functions helps the code "tell you" what it's doing ... a for loop can get complex and confusing, but if wrapped in
loop_that_does_x()
it becomes self explanatory.– dozyaustin
Nov 23 '18 at 8:47
@telba that also definitely works. I have come to appreciate the way wrapping steps in functions helps the code "tell you" what it's doing ... a for loop can get complex and confusing, but if wrapped in
loop_that_does_x()
it becomes self explanatory.– dozyaustin
Nov 23 '18 at 8:47
@telba Also ... if you feel like marking me as the correct answer ;) that would be lovely (would be one of my first answers).
– dozyaustin
Nov 23 '18 at 8:47
@telba Also ... if you feel like marking me as the correct answer ;) that would be lovely (would be one of my first answers).
– dozyaustin
Nov 23 '18 at 8:47
add a comment |
Here's what I ended up with:
data = np.genfromtxt('data.csv', delimiter=',')
w = data[:,0]
x = data[:,1]
y = data[:,2]
z = data[:,3]
lenw = int(len(w))
lenx = int(len(x)) #change the value within inner parenthesis to suit different dataset
window = int(6) #change window size
wdata_avg = np.zeros(lenw - window + 1)
a = np.zeros(lenw-window+1)
b = np.zeros(lenx-window + 1)
for i in np.arange(len(w)):
wdata = w[i:i + window]
xdata = x[i:i+window]
a[i], b[i] = np.polyfit(wdata, xdata,1)
wdata_avg[i] = np.mean(wdata)
if i == (lenw - window):
break
There may be some inconsistencies in the code, since I tried to format it so it was general rather than specific to my data.
add a comment |
Here's what I ended up with:
data = np.genfromtxt('data.csv', delimiter=',')
w = data[:,0]
x = data[:,1]
y = data[:,2]
z = data[:,3]
lenw = int(len(w))
lenx = int(len(x)) #change the value within inner parenthesis to suit different dataset
window = int(6) #change window size
wdata_avg = np.zeros(lenw - window + 1)
a = np.zeros(lenw-window+1)
b = np.zeros(lenx-window + 1)
for i in np.arange(len(w)):
wdata = w[i:i + window]
xdata = x[i:i+window]
a[i], b[i] = np.polyfit(wdata, xdata,1)
wdata_avg[i] = np.mean(wdata)
if i == (lenw - window):
break
There may be some inconsistencies in the code, since I tried to format it so it was general rather than specific to my data.
add a comment |
Here's what I ended up with:
data = np.genfromtxt('data.csv', delimiter=',')
w = data[:,0]
x = data[:,1]
y = data[:,2]
z = data[:,3]
lenw = int(len(w))
lenx = int(len(x)) #change the value within inner parenthesis to suit different dataset
window = int(6) #change window size
wdata_avg = np.zeros(lenw - window + 1)
a = np.zeros(lenw-window+1)
b = np.zeros(lenx-window + 1)
for i in np.arange(len(w)):
wdata = w[i:i + window]
xdata = x[i:i+window]
a[i], b[i] = np.polyfit(wdata, xdata,1)
wdata_avg[i] = np.mean(wdata)
if i == (lenw - window):
break
There may be some inconsistencies in the code, since I tried to format it so it was general rather than specific to my data.
Here's what I ended up with:
data = np.genfromtxt('data.csv', delimiter=',')
w = data[:,0]
x = data[:,1]
y = data[:,2]
z = data[:,3]
lenw = int(len(w))
lenx = int(len(x)) #change the value within inner parenthesis to suit different dataset
window = int(6) #change window size
wdata_avg = np.zeros(lenw - window + 1)
a = np.zeros(lenw-window+1)
b = np.zeros(lenx-window + 1)
for i in np.arange(len(w)):
wdata = w[i:i + window]
xdata = x[i:i+window]
a[i], b[i] = np.polyfit(wdata, xdata,1)
wdata_avg[i] = np.mean(wdata)
if i == (lenw - window):
break
There may be some inconsistencies in the code, since I tried to format it so it was general rather than specific to my data.
answered Nov 21 '18 at 2:30
telbatelba
255
255
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53309996%2flinear-regression-with-moving-window-in-python%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown