# This is a sample Python script. # Press Shift+F10 to execute it or replace it with your code. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. def print_hi(name): # Use a breakpoint in the code line below to debug your script. print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint. # Press the green button in the gutter to run the script. if __name__ == '__main__': print_hi('PyCharm') # See PyCharm help at https://www.jetbrains.com/help/pycharm/ import numpy as np import matplotlib.pyplot as plt import pandas as pd from sklearn import datasets,linear_model #读取数据 def get_data(input_data): data = pd.read_csv('input_data.csv') X_parameter = [] Y_parameter = [] for single_square_feet,single_price_value in zip(data['square_feet'],data['price']): X_parameter.append([float(single_square_feet)]) Y_parameter.append([float(single_price_value)]) return X_parameter,Y_parameter #将数据拟合到线性模型 def linear_model_main(X_parameters,Y_parameters,predict_value): #创建线性回归对象 regr = linear_model.LinearRegression() regr.fit(X_parameters,Y_parameters) predict_outcome =regr.predict(predict_value) predictions = {} predictions['intercept'] = regr.intercept_ predictions['coefficient'] = regr.coef_ predictions['predict_value'] = predict_outcome return predictions #预测 X,Y=get_data('input_data.csv') predictvalue=700 predictvalue=np.array(predictvalue).reshape(1,-1) result = linear_model_main(X,Y,predictvalue) print ("Intercept value ",result['intercept'] ) print ("coefficient",result['coefficient'] ) print ("Predicted value ",result['predict_value'] ) #显示线性拟合模型的结果 def show_linear_line(X_parameters,Y_parameters): #创建线性回归现象 regr = linear_model.LinearRegression() regr.fit(X_parameters, Y_parameters) plt.scatter(X_parameters, Y_parameters, color = 'blue') plt.plot(X_parameters, regr.predict(X_parameters), color='red', linewidth=4) plt.xticks(()) plt.yticks(()) plt.show() show_linear_line(X,Y)
运行结果如下图所示:
本文中涉及到的的知识:
1.在pycharm下创建python文件:File->New->Python File
2.安装需要的模块(windows下):
第1步,点击左上角File下的Settings
第2步,Settings->Project:main.py->Python Interpreter->找到+号进去
第3步,点击+号进去以后,出现如下界面,输入你需要的模块,点击左下角的Install Package安装模块(我的sklearn这个模块已经安装完成,所以它的字体是蓝色的)
3.关于pycharm的一些快捷键:
ctrl+d (复制当前行);ctrl+/ (批量注释);Tab (缩进);shift+Tab (取消缩进);ctrl+f (查找);ctrl+r (替换);ctrl+e (复制当前行)
4.需要知道的知识:
(1)python严格使用缩进来体现代码的逻辑从属关系。
(2)每个import语句只导入一个模块
(3)注释的话有#和三引号,#用于单行注释,三引号常用于大段说明性文本的注释
5.一开始,出现如下所示的错误
解决方法,在predictvalue=700下加入predictvalue=np.array(predictvalue).reshape(1,-1)这句就行
这里是X值类型错误linear_model_main()要求输出参数X为numpy arry类型,也了解到这里-1是指未设定行数,程序随机分配,所以这里-1表示任一正整数,所以reshape(-1,1)表示(任意行,1列),而Numpy自己会根据输入值的排布,用reshape()方法得出未知维数的值,使得输出值符合np.reshape()的规范。