各位好:
我在尝试使用 Python3 把下面的图像拟合成符号幂律分布的曲线方程
参考了论坛上某位高手的帖子:https://blog.csdn.net/kevinelstri/article/details/52685934
但和原贴中不同的是,帖子里面的数据是自动声成的, 而我的数据是从一张EXCEL中提取的。
在运行的过程中出现了报错:
TypeError: zip argument #1 must support iteration
我的 EXCEL 原始数据是这样的求懂行的高手指点迷津
以下是我的代码:
import matplotlib.pyplot as plt
import numpy as np
from sklearn import linear_model
def open_excel(): # 从EXCEL 中获取数据
try:
book = xlrd.open_workbook('D:/data/Excel_data.xlsx') #文件名,把文件与py文件放在同一目录下
except:
print("open excel file failed!")
try:
sheet = book.sheet_by_name('data2') # 第一个页签 指定了其中的一个页签
return sheet
except:
print("locate worksheet in excel failed!")
def extraction(): # 提取excel列信息
sheet = open_excel() # 这个在上面定义了
Xs = []
Ys = []
logXs = []
logYs = []
for i in range(1, sheet.nrows): #前3行是标题名,对应表中的字段名所以应该从第3行开始,计算机以0开始计数,所以值是2
Z =sheet.cell(i,0).value #取第i行第1列 # 信息:APP 名称
X = sheet.cell(i,1).value # 信息:APP 排名序号
Y = sheet.cell(i,2).value # 信息:APP 用户数
Xs.append(X)
Ys.append(Y)
logX=np.log10(X)
logY=np.log10(Y)
logXs.append(logX)
logYs.append(logY)
print("Xs 如下:")
print(Xs)
print("Ys 如下:")
print(Ys)
print("logXs 如下:")
print(logXs)
print("logYs 如下:")
print(logYs)
print("------------")
plt.title("top50 APPs in 2020 China")
plt.scatter(Xs, Ys, color='blue')
plt.xlabel('Ranking',fontproperties='SimHei')
plt.ylabel('Number of users (10000)',fontproperties='SimHei')
plt.show()
return logX,logY
def DataFitAndVisualization(logX,logY):
X_parameter=[]
Y_parameter=[]
for single_square_feet ,single_price_value in zip(logX,logY):
X_parameter.append([float(single_square_feet)])
Y_parameter.append(float(single_price_value))
# 模型拟合
regr = linear_model.LinearRegression()
regr.fit(X_parameter, Y_parameter)
# 模型结果与得分
print('Coefficients: \n', regr.coef_,)
print("Intercept:\n",regr.intercept_)
# The mean square error
print("Residual sum of squares: %.8f" % np.mean((regr.predict(X_parameter) - Y_parameter) ** 2)) # 残差平方和
# 可视化
plt.title("Log Data")
plt.scatter(X_parameter, Y_parameter, color='black')
plt.plot(X_parameter, regr.predict(X_parameter), color='blue',linewidth=3)
plt.show()
if __name__=="__main__":
logX,logY=extraction()
DataFitAndVisualization(logX,logY)`