利用 numpy 将 age 列和 fare 列数据转化为矩阵,形式为 [[age fare]],命名为 titanic2。
时间: 2024-02-12 17:02:40 浏览: 26
假设你已经将数据读入为名为titanic的DataFrame,可以使用以下代码将age列和fare列数据转化为矩阵形式:
```python
import numpy as np
titanic2 = np.array([titanic['age'], titanic['fare']]).T
```
其中,np.array()将age列和fare列合并为一个二维数组,.T表示转置操作,将行向量转化为列向量。最终得到的titanic2矩阵的形式为[[age, fare], [age, fare], ...],每一行代表一组样本的age和fare数据。
相关问题
(1) 使用 pandas 读入数据 titanic.csv,命名为 origin,并查看数据维度与前 10 行。 (2) 处理缺失值: (a) 查看哪些列存在缺失值。 (b) 发现原始数据中存在年龄为空值的记录,可能是无法识别乘客年龄的缘故,因此去除 年龄为空的记录。(满足 age 为空的一行数据全部丢弃)并再次查看哪些列存在缺失 值。保存上述数据清洗后的数据至“titanic2_cleaned.csv”文件中,随后的题目都在 “titanic2_cleaned.csv”上进行。 1 (3) 筛选列名为 pclass,sex,age,fare,who,adult_male 的列,构成模型数据,命名为 titanic_model。 (4) 使用 patsy.dmatrices() 函数,建立变量 fare 对变量 age 的线性回归,为该线性模型产生设 计矩阵;根据最小二乘法计算回归拟合系数。 (5) 使用 Pandas.get_dummies() 将分类变量 sex、who 转化为虚拟变量,利用 patsy 将数值列 pclass 转化为分类变量。 (6) 使用 statsmodels 包,基于 statsmodels.api(数组接入),利用最小二乘法建立 fare 对 pclass、 sex、age、who 的线性回归模型,(pclass、age 为数值型变量,sex、who 为虚变量),并添 加截距项,展示拟合系数。
好的,以下是针对你的问题的回答:
(1) 使用 pandas 读入数据 titanic.csv,命名为 origin,并查看数据维度与前 10 行。
```python
import pandas as pd
origin = pd.read_csv('titanic.csv')
print("数据维度为:", origin.shape)
print("前10行数据为:\n", origin.head(10))
```
(2) 处理缺失值:
(a) 查看哪些列存在缺失值。
```python
print(origin.isnull().sum())
```
(b) 发现原始数据中存在年龄为空值的记录,可能是无法识别乘客年龄的缘故,因此去除年龄为空的记录。(满足 age 为空的一行数据全部丢弃)并再次查看哪些列存在缺失值。保存上述数据清洗后的数据至“titanic2_cleaned.csv”文件中,随后的题目都在“titanic2_cleaned.csv”上进行。
```python
# 去除 age 为空的行
titanic2 = origin.dropna(subset=['age'])
# 再次查看哪些列存在缺失值
print(titanic2.isnull().sum())
# 保存数据到 titanic2_cleaned.csv 文件中
titanic2.to_csv('titanic2_cleaned.csv', index=False)
```
(3) 筛选列名为 pclass,sex,age,fare,who,adult_male 的列,构成模型数据,命名为 titanic_model。
```python
titanic_model = titanic2[['pclass', 'sex', 'age', 'fare', 'who', 'adult_male']]
```
(4) 使用 patsy.dmatrices() 函数,建立变量 fare 对变量 age 的线性回归,为该线性模型产生设计矩阵;根据最小二乘法计算回归拟合系数。
```python
import patsy
import numpy as np
# 构建设计矩阵
y, X = patsy.dmatrices('fare ~ age', data=titanic_model, return_type='dataframe')
# 根据最小二乘法计算回归拟合系数
from sklearn.linear_model import LinearRegression
lr = LinearRegression()
lr.fit(X, y)
print("回归系数为:", lr.coef_)
```
(5) 使用 Pandas.get_dummies() 将分类变量 sex、who 转化为虚拟变量,利用 patsy 将数值列 pclass 转化为分类变量。
```python
# 将 sex、who 转化为虚拟变量
titanic_model = pd.get_dummies(titanic_model, columns=['sex', 'who'])
# 将 pclass 转化为分类变量
titanic_model['pclass'] = titanic_model['pclass'].astype('category')
titanic_model = patsy.dmatrix('pclass + age + fare + sex_female + sex_male + who_child + who_man + who_woman', data=titanic_model, return_type='dataframe')
```
(6) 使用 statsmodels 包,基于 statsmodels.api(数组接入),利用最小二乘法建立 fare 对 pclass、sex、age、who 的线性回归模型,(pclass、age 为数值型变量,sex、who 为虚变量),并添加截距项,展示拟合系数。
```python
import statsmodels.api as sm
# 为矩阵添加截距项
X = sm.add_constant(titanic_model)
# 建立线性回归模型
model = sm.OLS(y, X).fit()
# 展示拟合系数
print(model.params)
```
1. 利用随机森林求出Titanic数据集的训练集及测试集预测准确率。 2. 跑出影响因素的重要性排序图。 3. 跑出随机森林收敛图。 4. 将代码列出。
1. 利用随机森林求出Titanic数据集的训练集及测试集预测准确率的代码如下:
```python
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
# 读取数据
data = pd.read_csv('titanic.csv')
# 筛选特征和标签
features = data[['Pclass', 'Age', 'SibSp', 'Parch', 'Fare', 'Sex', 'Embarked']]
target = data['Survived']
# 特征处理
features['Age'] = features['Age'].fillna(features['Age'].mean())
features['Fare'] = features['Fare'].fillna(features['Fare'].mean())
features['Sex'] = features['Sex'].map({'male': 0, 'female': 1})
features['Embarked'] = features['Embarked'].fillna('S')
features['Embarked'] = features['Embarked'].map({'C': 0, 'Q': 1, 'S': 2})
# 划分训练集和测试集
x_train, x_test, y_train, y_test = train_test_split(features, target, test_size=0.2, random_state=42)
# 随机森林模型
rf = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=42)
rf.fit(x_train, y_train)
# 预测结果
y_train_pred = rf.predict(x_train)
y_test_pred = rf.predict(x_test)
# 计算准确率
train_acc = accuracy_score(y_train, y_train_pred)
test_acc = accuracy_score(y_test, y_test_pred)
print("训练集准确率:", train_acc)
print("测试集准确率:", test_acc)
```
2. 跑出影响因素的重要性排序图的代码如下:
```python
import matplotlib.pyplot as plt
# 获取特征重要性
importances = rf.feature_importances_
indices = np.argsort(importances)[::-1]
# 绘制特征重要性排序图
plt.figure()
plt.title("Feature importances")
plt.bar(range(features.shape[1]), importances[indices], color="r", align="center")
plt.xticks(range(features.shape[1]), features.columns[indices], rotation=90)
plt.xlim([-1, features.shape[1]])
plt.show()
```
3. 跑出随机森林收敛图的代码如下:
```python
import numpy as np
# 随机森林的oob误差
n_estimators = [1, 2, 4, 8, 16, 32, 64, 100, 200]
train_accs = []
test_accs = []
for n_estimator in n_estimators:
rf = RandomForestClassifier(n_estimators=n_estimator, max_depth=5, oob_score=True, random_state=42)
rf.fit(x_train, y_train)
train_accs.append(rf.score(x_train, y_train))
test_accs.append(rf.score(x_test, y_test))
plt.figure()
plt.plot(n_estimators, train_accs, '-o', label='train')
plt.plot(n_estimators, test_accs, '-o', label='test')
plt.xlabel('n_estimators')
plt.ylabel('accuracy')
plt.legend()
plt.show()
```
4. 完整代码如下:
```python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
# 读取数据
data = pd.read_csv('titanic.csv')
# 筛选特征和标签
features = data[['Pclass', 'Age', 'SibSp', 'Parch', 'Fare', 'Sex', 'Embarked']]
target = data['Survived']
# 特征处理
features['Age'] = features['Age'].fillna(features['Age'].mean())
features['Fare'] = features['Fare'].fillna(features['Fare'].mean())
features['Sex'] = features['Sex'].map({'male': 0, 'female': 1})
features['Embarked'] = features['Embarked'].fillna('S')
features['Embarked'] = features['Embarked'].map({'C': 0, 'Q': 1, 'S': 2})
# 划分训练集和测试集
x_train, x_test, y_train, y_test = train_test_split(features, target, test_size=0.2, random_state=42)
# 随机森林模型
rf = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=42)
rf.fit(x_train, y_train)
# 预测结果
y_train_pred = rf.predict(x_train)
y_test_pred = rf.predict(x_test)
# 计算准确率
train_acc = accuracy_score(y_train, y_train_pred)
test_acc = accuracy_score(y_test, y_test_pred)
print("训练集准确率:", train_acc)
print("测试集准确率:", test_acc)
# 获取特征重要性
importances = rf.feature_importances_
indices = np.argsort(importances)[::-1]
# 绘制特征重要性排序图
plt.figure()
plt.title("Feature importances")
plt.bar(range(features.shape[1]), importances[indices], color="r", align="center")
plt.xticks(range(features.shape[1]), features.columns[indices], rotation=90)
plt.xlim([-1, features.shape[1]])
plt.show()
# 随机森林的oob误差
n_estimators = [1, 2, 4, 8, 16, 32, 64, 100, 200]
train_accs = []
test_accs = []
for n_estimator in n_estimators:
rf = RandomForestClassifier(n_estimators=n_estimator, max_depth=5, oob_score=True, random_state=42)
rf.fit(x_train, y_train)
train_accs.append(rf.score(x_train, y_train))
test_accs.append(rf.score(x_test, y_test))
plt.figure()
plt.plot(n_estimators, train_accs, '-o', label='train')
plt.plot(n_estimators, test_accs, '-o', label='test')
plt.xlabel('n_estimators')
plt.ylabel('accuracy')
plt.legend()
plt.show()
```