我有这个情节
现在我要为其添加一条趋势线,该怎么做?
数据如下:
我只想弄清楚多年来加州的平均挂牌价如何上涨,所以我这样做了:
#86400000 = 24h
$FilterXPath = '*[System[EventID=4624 and TimeCreated[timediff(@SystemTime) <= 86400000]]]'
$LogonEvents = Get-WinEvent -LogName Security -FilterXPath $FilterXPath
$Logons = foreach ($LogonEvent in $LogonEvents) {
[PSCustomObject]@{
LogonDate = $LogonEvent.TimeCreated
UserName = $LogonEvent.Properties[5].Value
UserDomain = $LogonEvent.Properties[6].Value
LogonType = $LogonEvent.Properties[8].Value
}
}
$LogonsGroupedByUserName = $Logons | Group-Object -Property UserName
foreach ($Group in $LogonsGroupedByUserName) {
$Group.Group |
Sort-Object -Property LogonDate -Descending |
Select-Object -First 1
}
然后我将字符串state_ca_month转换为datetime:
# Get California data
state_ca = []
state_median_price = []
state_ca_month = []
for state, price, date in zip(data['ZipName'], data['Median Listing Price'], data['Month']):
if ", CA" not in state:
continue
else:
state_ca.append(state)
state_median_price.append(price)
state_ca_month.append(date)
然后将其绘制
# Convert state_ca_month to datetime
state_ca_month = [datetime.strptime(x, '%m/%d/%Y %H:%M') for x in state_ca_month]
我考虑添加趋势线或某种类型的线,但是我对可视化还是陌生的。如果有人有其他建议,我将不胜感激。
按照评论中的建议,我得到了这个散点图
我想知道是否应该进一步格式化数据以便更清晰地检查。
答案 0 :(得分:1)
如果用“趋势线”表示文字线,那么您可能希望对数据进行线性回归。 {{1}中的sklearn
provides this functionality。
来自上面的超链接示例:
python
要澄清的是,“总体趋势”不是明确定义的事情。很多时候,人们用“趋势”来指代一条“适合”数据的字面行。反过来,“拟合数据”是指“预测数据”。因此,获取趋势线的最常见方法是选择一条最能预测您观察到的数据的线。事实证明,我们甚至需要弄清“预测”的含义。一种方法(也是非常常见的一种方法)是通过定义“最佳预测”,以使“趋势线”和观测数据之间所有误差的平方和最小。这称为ordinary least squares linear regression,是获得“趋势线”的最简单方法之一。这是在import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error, r2_score
# Load the diabetes dataset
diabetes = datasets.load_diabetes()
# Use only one feature
diabetes_X = diabetes.data[:, np.newaxis, 2]
# Split the data into training/testing sets
diabetes_X_train = diabetes_X[:-20]
diabetes_X_test = diabetes_X[-20:]
# Split the targets into training/testing sets
diabetes_y_train = diabetes.target[:-20]
diabetes_y_test = diabetes.target[-20:]
# Create linear regression object
regr = linear_model.LinearRegression()
# Train the model using the training sets
regr.fit(diabetes_X_train, diabetes_y_train)
# Make predictions using the testing set
diabetes_y_pred = regr.predict(diabetes_X_test)
# The coefficients
print('Coefficients: \n', regr.coef_)
# The mean squared error
print("Mean squared error: %.2f"
% mean_squared_error(diabetes_y_test, diabetes_y_pred))
# Explained variance score: 1 is perfect prediction
print('Variance score: %.2f' % r2_score(diabetes_y_test, diabetes_y_pred))
# Plot outputs
plt.scatter(diabetes_X_test, diabetes_y_test, color='black')
plt.plot(diabetes_X_test, diabetes_y_pred, color='blue', linewidth=3)
plt.xticks(())
plt.yticks(())
plt.show()
中实现的算法。