python - 如何使用python对单个矩阵值求平方?
问题描述
使用 Python 实现的成本函数:**感谢您的帮助。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
load_data = pd.read_csv('C:\python_program\ex1data1.txt',sep = ",",header = None)
feature_vale = load_data[0]
y = np.matrix(load_data[1])
m = len(feature_vale)
plt.scatter(load_data[0],load_data[1],marker='+',c = 'r')
plt.title("Cost_Function")
plt.xlabel("Population of City in 10,000s")
plt.ylabel("Profit in $10,000s")
df = pd.DataFrame(pd.Series(1,index= range(0,m)))
df[1] = load_data[0]
X = np.matrix(df)
row_theta = np.zeros(2,dtype = int)
theta = np.array([row_theta]) # Transpose the array
prediction = np.dot(X,theta.T)
error = (prediction-y.T)
error_df = pd.DataFrame(error)
#square the error
squared_error = np.square(error_df)
sum = np.sum(squared_error)
print(sum)
J = np.sum(squared_error) / (2 * m)
print(J)
资料参考链接:searchcode.com/codesearch/view/5404318
解决方案
重复以下步骤并告诉我
load_data = pd.read_csv('data.txt',sep = ",",header = None)
feature_vale = load_data[0]
y = np.matrix(load_data[1])
m = len(feature_vale)
#print(m)
#plt.scatter(load_data[0],load_data[1])
df = pd.DataFrame(pd.Series(1,index= range(0,m)))
df[1] = load_data[0]
X = np.matrix(df)
row_theta = np.zeros(2,dtype = int)
theta = np.array([row_theta]) # Transpose the array
print(theta.T)
prediction = np.matmul(X,theta.T)
error = (prediction-y)
error_df = pd.DataFrame(error)
squared_error = np.square(error_df)
print(squared_error)
推荐阅读
- selenium - 在 Selenium 的 div 类中选择项目
- frameworks - Xcode 10 的胖框架脚本?
- android - 如何在listview上获取所选项目的ID
- java - 如何使这个二叉搜索树工作???(在 Java 中)
- git - 如何在更新 .gitignore 之前从 git push 中删除文件?
- python - 使用 db.create_all 让 flask-sqlalchemy 从模型创建表
- java - 在 Android/Java 中通过 URL 将 Google 表格导出为 CSV/JSON
- django - 如何在我的 url 中实现我的 sluig 而不是 Django 中的主键?
- sql - 在右连接中访问嵌套内连接
- javascript - MongoDB 检查 $switch 语句中的空字段