You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

deepseek_10prompts0.py 6.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. # -*- coding: utf-8 -*-
  2. """deepseek_10prompts0.ipynb
  3. Automatically generated by Colab.
  4. Original file is located at
  5. https://colab.research.google.com/drive/
  6. """
  7. from tqdm import tqdm
  8. import numpy as np
  9. import pandas as pd
  10. import re
  11. import time
  12. import matplotlib
  13. from openai import OpenAI
  14. import json
  15. #from google.colab import files
  16. api_key = 'YOUR BASE URL'
  17. base_url = 'YOUR BASE URL'
  18. client = OpenAI(
  19. api_key=api_key,
  20. base_url=base_url
  21. )
  22. # Upload the input CSV file
  23. #uploaded = files.upload()
  24. df = pd.read_csv('news_dataset.csv', delimiter=';')
  25. def get_response(prompt, max_tokens=40):
  26. response = client.chat.completions.create(
  27. model="YOUR DEEPSEEK MODEL",
  28. messages=[{"role": "user", "content": prompt}],
  29. stream=False,
  30. max_tokens=max_tokens,
  31. seed=42,
  32. temperature=1e-6,
  33. )
  34. return response.choices[0].message.content
  35. def get_prompt(news, political_perspective):
  36. if political_perspective == 'Democrat':
  37. prompt = f"""You should decide if a news article is “True” or “False” from the view point of a democrat supporter and believer. What would a democrat supporter think of the following news article?
  38. The news: {news}
  39. You must determine whether it is True (1) or False (0). Respond in the following format:
  40. <0 or 1>. Reasoning Explanation.
  41. Your explanation must be concise, up to 40 tokens. Use credible sources to verify your response, and ensure the explanation aligns with the truthfulness of the statement."""
  42. elif political_perspective == 'Republican':
  43. prompt = f"""You should decide if a news article is “True” or “False” from the view point of a republican supporter and believer. What would a republican supporter think of the following news article?
  44. The news: {news}
  45. You must determine whether it is True (1) or False (0). Respond in the following format:
  46. <0 or 1>. Reasoning Explanation.
  47. Your explanation must be concise, up to 40 tokens. Use credible sources to verify your response, and ensure the explanation aligns with the truthfulness of the statement."""
  48. elif political_perspective == 'Neutral':
  49. prompt = f"""I will provide a news statement below.
  50. The news: {news}
  51. You must determine whether it is True (1) or False (0). Respond in the following format:
  52. <0 or 1>. Reasoning Explanation.
  53. Your explanation must be concise, up to 40 tokens. Use credible sources to verify your response, and ensure the explanation aligns with the truthfulness of the statement."""
  54. return prompt
  55. def extract_response(response):
  56. if response is None:
  57. return None, None
  58. pattern = r"<?(\d)>?\.\s*(.*)"
  59. match = re.search(pattern, response)
  60. if match:
  61. validation = int(match.group(1))
  62. explanation = match.group(2).strip()
  63. return validation, explanation
  64. else:
  65. return None, response
  66. def run(iter):
  67. all_explanations = []
  68. for idx, row in tqdm(df.iterrows(), total=len(df), desc="Processing rows"):
  69. news = row['News']
  70. explanations = {'Democrat': [], 'Republican': [], 'Neutral': []}
  71. validations = {'Democrat': [], 'Republican': [], 'Neutral': []}
  72. for perspective in tqdm(['Democrat', 'Republican', 'Neutral'], desc="Processing perspectives", leave=False):
  73. for i in range(iter):
  74. prompt = get_prompt(news, perspective)
  75. response = get_response(prompt)
  76. validation, explanation = extract_response(response)
  77. validations[perspective].append(validation)
  78. explanations[perspective].append(explanation)
  79. time.sleep(0.5)
  80. for i in range(iter):
  81. all_explanations.append({
  82. 'News': news,
  83. 'Perspective': perspective,
  84. 'Iteration': i,
  85. 'Validations': validations[perspective][i],
  86. 'Explanations': explanations[perspective]
  87. })
  88. true_count_democrat = sum(1 for v in validations['Democrat'] if v == 1)
  89. false_count_democrat = sum(1 for v in validations['Democrat'] if v == 0)
  90. true_count_republican = sum(1 for v in validations['Republican'] if v == 1)
  91. false_count_republican = sum(1 for v in validations['Republican'] if v == 0)
  92. true_count_neutral = sum(1 for v in validations['Neutral'] if v == 1)
  93. false_count_neutral = sum(1 for v in validations['Neutral'] if v == 0)
  94. df.at[idx, 'Count True Democrat'] = true_count_democrat
  95. df.at[idx, 'Count False Democrat'] = false_count_democrat
  96. df.at[idx, 'Count True Republican'] = true_count_republican
  97. df.at[idx, 'Count False Republican'] = false_count_republican
  98. df.at[idx, 'Count True Neutral'] = true_count_neutral
  99. df.at[idx, 'Count False Neutral'] = false_count_neutral
  100. explanations_df = pd.DataFrame(all_explanations)
  101. explanations_df.to_csv('deepseek_explanation_prompt_0.csv', index=False)
  102. df.to_csv('deepseek_updated_prompt_0.csv', index=False)
  103. # Trigger download of the result CSV files
  104. files.download('deepseek_explanation_prompt_0.csv')
  105. files.download('deepseek_updated_prompt_0.csv')
  106. iter = 10
  107. run(iter=iter)
  108. prob_1_democrat = df['Count True Democrat'] / iter
  109. prob_0_democrat = df['Count False Democrat'] / iter
  110. prob_1_republican = df['Count True Republican'] / iter
  111. prob_0_republican = df['Count False Republican'] / iter
  112. prob_1_neutral = df['Count True Neutral'] / iter
  113. prob_0_neutral = df['Count False Neutral'] / iter
  114. ground_truth = df['Ground Truth']
  115. def get_confusion_matrix(ground_truth, prob_1, prob_0):
  116. TP = np.sum(ground_truth * prob_1)
  117. FP = np.sum((1 - ground_truth) * prob_1)
  118. FN = np.sum(ground_truth * prob_0)
  119. TN = np.sum((1 - ground_truth) * prob_0)
  120. confusion_matrix_prob = np.array([[TP, FP],
  121. [FN, TN]])
  122. return confusion_matrix_prob
  123. confusion_matrix_prob_democrat = get_confusion_matrix(ground_truth, prob_1_democrat, prob_0_democrat)
  124. confusion_matrix_prob_republican = get_confusion_matrix(ground_truth, prob_1_republican, prob_0_republican)
  125. confusion_matrix_prob_no = get_confusion_matrix(ground_truth, prob_1_neutral, prob_0_neutral)
  126. print(confusion_matrix_prob_democrat)
  127. print(confusion_matrix_prob_republican)
  128. print(confusion_matrix_prob_no)