- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个格式类似于鸢尾花数据集的数据集,我想使用自定义分类器来分析它。
由于我不太擅长 Python,所以我正在改编其他人的代码,谢谢:)到目前为止效果很好。然而,我想添加一个准确度分数,因为我的数据集超过 100 万个数据点,而且我刚刚弄清楚。
我使用的代码是:
# Dependencies
import tensorflow as tf
import pandas as pd
import numpy as np
print(tf.__version__)
# Make results reproducible
seed = 1234
np.random.seed(seed)
tf.set_random_seed(seed)
# Loading the dataset
dataset = pd.read_csv('Iris_Dataset.csv')
dataset = pd.get_dummies(dataset, columns=['Species']) # One Hot Encoding
values = list(dataset.columns.values)
#y is the CellType value x is the data
# Python is a 0 index language
y = dataset[values[-3:]]
y = np.array(y, dtype='float32')
X = dataset[values[1:-3]]
X = np.array(X, dtype='float32')
# Shuffle Data
indices = np.random.choice(len(X), len(X), replace=False)
X_values = X[indices]
y_values = y[indices]
# Creating a Train and a Test Dataset
test_size = 10
X_test = X_values[-test_size:]
X_train = X_values[:-test_size]
y_test = y_values[-test_size:]
y_train = y_values[:-test_size]
# Session
sess = tf.Session()
# Interval / Epochs
interval = 50
epoch = 500
# Initialize placeholders
X_data = tf.placeholder(shape=[None, 4], dtype=tf.float32)
y_target = tf.placeholder(shape=[None, 3], dtype=tf.float32)
# Input neurons : 4
# Hidden neurons : 8
# Output neurons : 3
hidden_layer_nodes = 9
# Create variables for Neural Network layers
w1 = tf.Variable(tf.random_normal(shape=[4,hidden_layer_nodes])) # Inputs -> Hidden Layer
b1 = tf.Variable(tf.random_normal(shape=[hidden_layer_nodes])) # First Bias
w2 = tf.Variable(tf.random_normal(shape=[hidden_layer_nodes,3])) # Hidden layer -> Outputs
b2 = tf.Variable(tf.random_normal(shape=[3])) # Second Bias
# Operations
hidden_output = tf.nn.relu(tf.add(tf.matmul(X_data, w1), b1))
final_output = tf.nn.softmax(tf.add(tf.matmul(hidden_output, w2), b2))
# Cost Function
loss = tf.reduce_mean(-tf.reduce_sum(y_target * tf.log(final_output), axis=0))
# Optimizer
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001).minimize(loss)
# Initialize variables
init = tf.global_variables_initializer()
sess.run(init)
# Training
print('Training the model...')
for i in range(1, (epoch + 1)):
sess.run(optimizer, feed_dict={X_data: X_train, y_target: y_train})
if i % interval == 0:
print('Epoch', i, '|', 'Loss:', sess.run(loss, feed_dict={X_data: X_train, y_target: y_train}))
# Prediction
print()
for i in range(len(X_test)):
print('Actual:', y_test[i], 'Predicted:', np.rint(sess.run(final_output, feed_dict={X_data: [X_test[i]]})))
# Evaluate accuracy.
accuracy_score = y_target.evaluate(input_fn=y_target)["accuracy"]
print("\nTest Accuracy: {0:f}\n".format(accuracy_score))
我得到的输出是
1.4.0
2018-04-05 09:06:35.688295: I tensorflow/core/platform/cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: SSE4.1 SSE4.2 AVX AVX2 FMA
Training the model...
Epoch 50 | Loss: 11.3519
Epoch 100 | Loss: 7.53955
Epoch 150 | Loss: 6.3168
Epoch 200 | Loss: 5.58197
Epoch 250 | Loss: 5.09148
Epoch 300 | Loss: 4.74129
Epoch 350 | Loss: 4.47681
Epoch 400 | Loss: 4.26831
Epoch 450 | Loss: 4.09931
Epoch 500 | Loss: 3.95926
Actual: [ 0. 0. 1.] Predicted: [[ 0. 0. 1.]]
Actual: [ 1. 0. 0.] Predicted: [[ 1. 0. 0.]]
Actual: [ 0. 0. 1.] Predicted: [[ 0. 0. 1.]]
Actual: [ 1. 0. 0.] Predicted: [[ 1. 0. 0.]]
Actual: [ 1. 0. 0.] Predicted: [[ 1. 0. 0.]]
Actual: [ 0. 0. 1.] Predicted: [[ 0. 0. 1.]]
Actual: [ 0. 0. 1.] Predicted: [[ 0. 0. 1.]]
Actual: [ 0. 1. 0.] Predicted: [[ 0. 1. 0.]]
Actual: [ 1. 0. 0.] Predicted: [[ 1. 0. 0.]]
Actual: [ 1. 0. 0.] Predicted: [[ 1. 0. 0.]]
Traceback (most recent call last):
File "/Users/XXXX/PycharmProjects/TensorFlow1/Iris/Iris_Network.py", line 86, in <module>
accuracy_score = y_target.evaluate(input_fn=y_target)["accuracy"]
AttributeError: 'Tensor' object has no attribute 'evaluate'
Process finished with exit code 1
正如您所看到的,只有最后两行代码是错误的。这些应该是什么?
最佳答案
您可以使用 sklearn precision score function
中的分数。如此说道。您的测试分数不需要 for 循环。因此,您可以获得所有结果。
y_pred = np.rint(sess.run(final_output, feed_dict={X_data: X_test}))
至于分数
score = sklearn.metrics.precision_score(y_test, y_pred)
当然你需要导入sklearn
包。
关于python - 准确率分数 Tensorflow(简单),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49667412/
我训练了 LSTM 分类模型,但得到了奇怪的结果(0 准确率)。这是我的带有预处理步骤的数据集: import pandas as pd from sklearn.model_selection im
使用 TFlearn 构建 DNN 后,我想计算网络的准确性。 这是代码: def create_model(self): x = tf.placeholder(dtype= tf.float
Duplicate calculating Precision, Recall and F Score 我有一个带有文本描述和分类级别(即levelA和levelB)的输入文件。我想编写一个 SVM
如何计算语义分割中前 k 个准确率?在分类中,我们可以将 topk 准确率计算为: correct = output.eq(gt.view(1, -1).expand_as(output)) 最佳答案
我正在尝试解决多标签分类问题 from sklearn.preprocessing import MultiLabelBinarizer traindf = pickl
我是一名优秀的程序员,十分优秀!