-
Notifications
You must be signed in to change notification settings - Fork 0
/
scb_linearregression.py
142 lines (93 loc) · 3.14 KB
/
scb_linearregression.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# -*- coding: utf-8 -*-
"""SCB_LinearRegression
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1_Vpy2alCyZvx8AtvBGOB3ISv4m4GS57o
# Project description
Predicting explained variance score. Data gathered is number of companies with 100 percent ownership by region and year
Statistics used:
https://www.statistikdatabasen.scb.se/pxweb/sv/ssd/START__OE__OE0108/KomFtgK100/table/tableViewLayout1/
Python module for SCB api usage:
https://github.com/kirajcg/pyscbwrapper/blob/master/pyscbwrapper.ipynb
# Importing requirements
"""
import json
# from urllib import request, response
import requests
import pandas as pd
from sklearn.metrics import accuracy_score
from sklearn.metrics import explained_variance_score
from sklearn.metrics import mean_squared_error
from sklearn.metrics import mean_absolute_error
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn import linear_model
"""# Data gathering and formatting
# Request
"""
api_url = "https://api.scb.se/OV0104/v1/doris/sv/ssd/START/OE/OE0108/KomFtgK100"
user_agent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64"
headers = {
'Content-Type' : 'application/json',
"User-Agent" : user_agent,
}
payload = {
"query": [
{
"code": "ContentsCode",
"selection": {
"filter": "item",
"values": [
"00000190"
]
}
}
],
"response": {
"format": "json"
}
}
json_data = json.dumps(payload)
"""# Data
**Request**
"""
api_call = requests.post(url=api_url, data=json_data, headers=headers)
if api_call.status_code != 200:
print("Status code:", api_call.status_code)
print("Reason:", api_call.reason)
print("Response headers:", api_call.headers)
else:
print("Status code:", api_call.status_code)
print("Request successful")
print("Response headers:", api_call.headers)
json_response = api_call.json()
data_only = json_response.get('data', [])
df = pd.DataFrame(data_only)
df[['region', 'year']] = pd.DataFrame(df['key'].tolist(), index=df.index)
df['year'] = df['year'].str[:4]
df['value'] = df['values'].apply(lambda x: x[0] if isinstance(x, list) else x)
df_pivot = df.pivot(index='region', columns='year', values='value')
df_pivot.to_csv('pivoted_region_years_values.csv')
print("Pivoted data with values saved to pivoted_region_years_values.csv")
df2 = pd.read_csv("pivoted_region_years_values.csv", index_col=False)
# df2.head(20)
"""# Plot raw data
# Predictions
"""
X = df2.drop(columns=["2016", 'region'], axis=1)
y = df2["2016"]
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.3, random_state=45)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
# svm = SVC()
linear = linear_model.LinearRegression()
linear.fit(X_train, y_train)
y_pred = linear.predict(X_test)
accuracy = explained_variance_score(y_test, y_pred)
mse = mean_squared_error(y_test, y_pred)
mae = mean_absolute_error(y_test, y_pred)
print("Explained variance score:", variance_score)
print("Mean squared error:", mse)
print("Mean absolute error:", mae)