Repository navigation
Expand file tree
/
Copy pathpython code
More file actions
237 lines (181 loc) · 6.5 KB
/
Copy pathpython code
File metadata and controls
237 lines (181 loc) · 6.5 KB
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
import pandas as pd
C6 = [123, 456, 235, 189, 174, 139, 94, 169]
vacmotdesc['C6'] = pd.Categorical(C6)
C6_Gender = pd.crosstab(vacmotdesc['C6'], vacmotdesc['Gender'])
print(C6_Gender)
2.
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.pyplot import figure
data = vacmotdesc
figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
plt.hist(data['Age'], bins=10, by=data['Segment'])
plt.title('Age by Segment')
plt.xlabel('Age')
plt.ylabel('Frequency')
plt.subplot(1, 2, 2)
plt.hist(data['Obligation'], bins=10, by=data['Segment'])
plt.title('Obligation by Segment')
plt.xlabel('Obligation')
plt.ylabel('Frequency')
plt.tight_layout()
plt.show()
3.
import matplotlib.pyplot as plt
import seaborn as sns
plt.figure(figsize=(10, 6))
sns.boxplot(x='C6', y='Age', data=vacmotdesc)
plt.xlabel("Segment number")
plt.ylabel("Age")
plt.show()
4.
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# Assuming 'vacmotdesc' is your DataFrame
# If not, you need to load your data into a pandas DataFrame first
sns.boxplot(x='C6', y='Obligation', data=vacmotdesc,
width=0.5, notch=True)
plt.xlabel("Segment number")
plt.ylabel("Moral obligation")
plt.show()
5.
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
import statsmodels.api as sm
import matplotlib.pyplot as plt
from statsmodels.graphics.effects_plot import plot_effects
from scipy import stats
# Assuming vacmotdesc is a pandas DataFrame
# First linear model
X = pd.get_dummies(vacmotdesc['C6'], drop_first=True, prefix='C6')
y = vacmotdesc['Age']
model1 = LinearRegression(fit_intercept=False)
model1.fit(X, y)
coeffs1 = pd.Series(model1.coef_, index=['C61', 'C62', 'C63', 'C64', 'C65', 'C66'])
print(coeffs1)
# Second linear model
X = pd.get_dummies(vacmotdesc['C6'], drop_first=True, prefix='C6')
X = sm.add_constant(X)
y = vacmotdesc['Age']
model2 = sm.OLS(y, X).fit()
print(model2.summary())
# Logistic regression model
vacmotdesc['C6_3'] = (vacmotdesc['C6'] == 3).astype(int)
X = pd.get_dummies(vacmotdesc['Obligation2'], drop_first=True, prefix='Obligation2')
X['Age'] = vacmotdesc['Age']
X = sm.add_constant(X)
y = vacmotdesc['C6_3']
model_C63 = sm.GLM(y, X, family=sm.families.Binomial()).fit()
print(model_C63.summary())
# Plot effects
plot_effects(model_C63)
plt.show()
# Anova-like analysis
from statsmodels.stats.anova import anova_lm
anova_results = anova_lm(model_C63)
print(anova_results)
# Full model
X = vacmotdesc.drop(['C6', 'C6_3'], axis=1)
X = pd.get_dummies(X, drop_first=True)
X = sm.add_constant(X)
y = vacmotdesc['C6_3']
full_model_C63 = sm.GLM(y, X, family=sm.families.Binomial()).fit()
print(full_model_C63.summary())
6. Binary logistic
import pandas as pd
import statsmodels.api as sm
import numpy as np
# Assuming 'vacmotdesc' is your DataFrame
# Create the formula
f = 'C6 == 3 ~ Age + C(Obligation2)'
# Fit the logistic regression model
model_C63 = sm.formula.glm(formula=f, data=vacmotdesc, family=sm.families.Binomial())
results = model_C63.fit()
# Print the model summary
print(results.summary())
# If you want to extract specific coefficients:
coefficients = results.params
intercept = coefficients['Intercept']
age_coef = coefficients['Age']
obligation2_q2 = coefficients['C(Obligation2)[T.Q2]']
obligation2_q3 = coefficients['C(Obligation2)[T.Q3]']
obligation2_q4 = coefficients['C(Obligation2)[T.Q4]']
print(f"Intercept: {intercept}")
print(f"Age: {age_coef}")
print(f"Obligation2 Q2: {obligation2_q2}")
print(f"Obligation2 Q3: {obligation2_q3}")
print(f"Obligation2 Q4: {obligation2_q4}")
# Print degrees of freedom, deviance, and AIC
print(f"Degrees of Freedom: {results.df_model} Total (i.e. Null); {results.df_resid} Residual")
print(f"Null Deviance: {results.null_deviance:.0f}")
print(f"Residual Deviance: {results.deviance:.0f}")
print(f"AIC: {results.aic:.0f}")
Multinomial reg
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
# Assuming 'vacmotdesc' is a pandas DataFrame
vacmotdesc['Oblig2'] = vacmotdesc['Obligation2']
# Prepare the data
X = vacmotdesc[['Age', 'Oblig2']]
y = vacmotdesc['C6']
# Encode categorical variables if necessary
le = LabelEncoder()
X['Oblig2'] = le.fit_transform(X['Oblig2'])
y = le.fit_transform(y)
# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Create and train the model
model_C6 = MLPClassifier(hidden_layer_sizes=(100,), max_iter=1000, random_state=42)
model_C6.fit(X_train, y_train)
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import OneHotEncoder
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
# Assuming 'vacmotdesc' is your DataFrame
X = vacmotdesc[['Age', 'Oblig2']]
y = vacmotdesc['C6']
# Create a preprocessor for one-hot encoding 'Oblig2'
preprocessor = ColumnTransformer(
transformers=[
('cat', OneHotEncoder(drop='first'), ['Oblig2'])
],
remainder='passthrough'
)
# Create a pipeline with preprocessor and multinomial logistic regression
model_C6 = Pipeline([
('preprocessor', preprocessor),
('classifier', LogisticRegression(multi_class='multinomial', solver='lbfgs'))
])
# Fit the model
model_C6.fit(X, y)
# Print model summary
print("Model: Multinomial Logistic Regression")
print(f"Number of classes: {len(model_C6.named_steps['classifier'].classes_)}")
print(f"Features: {['Age'] + [f'Oblig2_{cat}' for cat in model_C6.named_steps['preprocessor'].named_transformers_['cat'].categories_[0][1:]] + ['Intercept']}")
print(f"Coefficients shape: {model_C6.named_steps['classifier'].coef_.shape}")
print(f"Intercepts shape: {model_C6.named_steps['classifier'].intercept_.shape}")
print(f"AIC: {model_C6.named_steps['classifier'].score(X, y):.4f}")
import pandas as pd
import statsmodels.api as sm
from statsmodels.tools import add_constant
from sklearn.preprocessing import LabelBinarizer
# Assuming vacmotdesc is a pandas DataFrame
# vacmotdesc = pd.read_csv('path_to_vacmotdesc.csv') # Load your data here
# Prepare the data
X = vacmotdesc[['Age', 'Oblig2']] # Independent variables
y = vacmotdesc['C6'] # Dependent variable
# Convert categorical variable Oblig2 to dummy/indicator variables
X = pd.get_dummies(X, columns=['Oblig2'], drop_first=True)
# Add a constant term for the intercept
X = add_constant(X)
# Fit the multinomial logistic regression model
model = sm.MNLogit(y, X)
result = model.fit()
# Print the summary
print(result.summary())